From: Bdale Garbee Date: Sun, 18 Aug 2013 00:49:57 +0000 (+0200) Subject: completely repackage as an installer only X-Git-Tag: debian/13.05.1~4 X-Git-Url: https://git.gag.com/?a=commitdiff_plain;ds=sidebyside;h=6a035c579fbab078bafcc6d097ab784c5ffa3637;hp=4095cb0dd61a75b7b6b0bd811f8e803af5b27919;p=debian%2Fopenrocket completely repackage as an installer only --- diff --git a/android-libraries/ActionBarSherlock/.classpath b/android-libraries/ActionBarSherlock/.classpath deleted file mode 100644 index 8531be10..00000000 --- a/android-libraries/ActionBarSherlock/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/.project b/android-libraries/ActionBarSherlock/.project deleted file mode 100644 index cbcf5a22..00000000 --- a/android-libraries/ActionBarSherlock/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - ActionBarSherlock - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/android-libraries/ActionBarSherlock/AndroidManifest.xml b/android-libraries/ActionBarSherlock/AndroidManifest.xml deleted file mode 100644 index c4a75f32..00000000 --- a/android-libraries/ActionBarSherlock/AndroidManifest.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/android-libraries/ActionBarSherlock/bin/actionbarsherlock.jar b/android-libraries/ActionBarSherlock/bin/actionbarsherlock.jar deleted file mode 100644 index 02f36678..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/actionbarsherlock.jar and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$Implementation.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$Implementation.class deleted file mode 100644 index 07a0de98..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$Implementation.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeFinishedListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeFinishedListener.class deleted file mode 100644 index ba2cfcab..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeFinishedListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeStartedListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeStartedListener.class deleted file mode 100644 index 3ccc3b16..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeStartedListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreateOptionsMenuListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreateOptionsMenuListener.class deleted file mode 100644 index d0ffc34a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreateOptionsMenuListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreatePanelMenuListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreatePanelMenuListener.class deleted file mode 100644 index 7bf337c5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreatePanelMenuListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnMenuItemSelectedListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnMenuItemSelectedListener.class deleted file mode 100644 index 03609bbb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnMenuItemSelectedListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnOptionsItemSelectedListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnOptionsItemSelectedListener.class deleted file mode 100644 index 4076b48e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnOptionsItemSelectedListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPrepareOptionsMenuListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPrepareOptionsMenuListener.class deleted file mode 100644 index b9704c8e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPrepareOptionsMenuListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPreparePanelListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPreparePanelListener.class deleted file mode 100644 index 4e022428..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPreparePanelListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock.class deleted file mode 100644 index 3e4437f8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/BuildConfig.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/BuildConfig.class deleted file mode 100644 index f3ea991b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/BuildConfig.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$attr.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$attr.class deleted file mode 100644 index 79d19d6d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$attr.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$bool.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$bool.class deleted file mode 100644 index a9853b12..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$bool.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$color.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$color.class deleted file mode 100644 index 92c994f9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$color.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$dimen.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$dimen.class deleted file mode 100644 index 1423fa8c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$dimen.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$drawable.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$drawable.class deleted file mode 100644 index d1d77adb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$drawable.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$id.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$id.class deleted file mode 100644 index cb66e602..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$id.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$integer.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$integer.class deleted file mode 100644 index 2a1eb05f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$integer.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$layout.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$layout.class deleted file mode 100644 index 2e28b63a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$layout.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$string.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$string.class deleted file mode 100644 index cf862a46..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$string.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$style.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$style.class deleted file mode 100644 index b8c2a02a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$style.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$styleable.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$styleable.class deleted file mode 100644 index ce1bf2ac..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$styleable.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R.class deleted file mode 100644 index a9c24203..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$LayoutParams.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$LayoutParams.class deleted file mode 100644 index 19f2d713..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$LayoutParams.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnMenuVisibilityListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnMenuVisibilityListener.class deleted file mode 100644 index 377c6cbd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnMenuVisibilityListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnNavigationListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnNavigationListener.class deleted file mode 100644 index e7631ef1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnNavigationListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$Tab.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$Tab.class deleted file mode 100644 index 2c612f7c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$Tab.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$TabListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$TabListener.class deleted file mode 100644 index d3c82802..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$TabListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar.class deleted file mode 100644 index 95cae968..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockActivity.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockActivity.class deleted file mode 100644 index 0e5cc235..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockActivity.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockDialogFragment.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockDialogFragment.class deleted file mode 100644 index b235aed1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockDialogFragment.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockExpandableListActivity.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockExpandableListActivity.class deleted file mode 100644 index 3e60b010..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockExpandableListActivity.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragment.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragment.class deleted file mode 100644 index 5fe7b56e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragment.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragmentActivity.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragmentActivity.class deleted file mode 100644 index e7f20aa5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragmentActivity.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListActivity.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListActivity.class deleted file mode 100644 index ccea5880..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListActivity.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListFragment.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListFragment.class deleted file mode 100644 index 20d394d4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListFragment.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockPreferenceActivity.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockPreferenceActivity.class deleted file mode 100644 index d8af5912..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockPreferenceActivity.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$1.class deleted file mode 100644 index 40b3c68d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$ActionModeCallbackWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$ActionModeCallbackWrapper.class deleted file mode 100644 index 2015aba0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$ActionModeCallbackWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat.class deleted file mode 100644 index 1d77c593..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeCallbackWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeCallbackWrapper.class deleted file mode 100644 index e0514eb7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeCallbackWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeWrapper.class deleted file mode 100644 index 85099923..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative.class deleted file mode 100644 index 4180bec1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ResourcesCompat.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ResourcesCompat.class deleted file mode 100644 index 453d4a23..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ResourcesCompat.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$1.class deleted file mode 100644 index 2869fb12..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$2.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$2.class deleted file mode 100644 index ceab0c41..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$2.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$ActionModeImpl.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$ActionModeImpl.class deleted file mode 100644 index a49e0510..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$ActionModeImpl.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$TabImpl.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$TabImpl.class deleted file mode 100644 index f0947b4b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$TabImpl.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl.class deleted file mode 100644 index eba5fc17..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper$TabWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper$TabWrapper.class deleted file mode 100644 index 0ce995af..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper$TabWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper.class deleted file mode 100644 index 686d2bb6..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator$AnimatorListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator$AnimatorListener.class deleted file mode 100644 index e47ad311..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator$AnimatorListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.class deleted file mode 100644 index 281a4520..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.class deleted file mode 100644 index ae4b8657..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$1.class deleted file mode 100644 index aaedb90e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$AnimatorSetListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$AnimatorSetListener.class deleted file mode 100644 index d144adcb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$AnimatorSetListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Builder.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Builder.class deleted file mode 100644 index 5cbbc681..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Builder.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Dependency.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Dependency.class deleted file mode 100644 index 5e076406..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Dependency.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$DependencyListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$DependencyListener.class deleted file mode 100644 index 9f09b675..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$DependencyListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Node.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Node.class deleted file mode 100644 index f94b2b61..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Node.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.class deleted file mode 100644 index 7ffd50ff..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.class deleted file mode 100644 index 2d950bc3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.class deleted file mode 100644 index b3f70f87..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.class deleted file mode 100644 index 515af5da..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.class deleted file mode 100644 index 86bf0f67..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$FloatKeyframe.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$FloatKeyframe.class deleted file mode 100644 index 56d147a7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$FloatKeyframe.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$IntKeyframe.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$IntKeyframe.class deleted file mode 100644 index aa36b75a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$IntKeyframe.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$ObjectKeyframe.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$ObjectKeyframe.class deleted file mode 100644 index 69995146..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$ObjectKeyframe.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.class deleted file mode 100644 index 168f790d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.class deleted file mode 100644 index 58317c43..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.class deleted file mode 100644 index 32cefbfd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$FloatPropertyValuesHolder.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$FloatPropertyValuesHolder.class deleted file mode 100644 index be6568f8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$FloatPropertyValuesHolder.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$IntPropertyValuesHolder.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$IntPropertyValuesHolder.class deleted file mode 100644 index 4427b091..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$IntPropertyValuesHolder.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.class deleted file mode 100644 index 483a115b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.class deleted file mode 100644 index 6b090a67..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$1.class deleted file mode 100644 index 6f04d6bc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$2.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$2.class deleted file mode 100644 index c38e111f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$2.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$3.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$3.class deleted file mode 100644 index 90b41d76..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$3.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$4.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$4.class deleted file mode 100644 index fea2a587..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$4.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$5.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$5.class deleted file mode 100644 index 7fad8e7f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$5.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimationHandler.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimationHandler.class deleted file mode 100644 index a3b14ccc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimationHandler.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimatorUpdateListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimatorUpdateListener.class deleted file mode 100644 index b5bcde23..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimatorUpdateListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.class deleted file mode 100644 index 24581f1a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.class deleted file mode 100644 index c05ca82f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.class deleted file mode 100644 index 2838e4dd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.class deleted file mode 100644 index 664c61bd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.class deleted file mode 100644 index 46b2f34e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.class deleted file mode 100644 index 747aa2b3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/ActionProviderWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/ActionProviderWrapper.class deleted file mode 100644 index c7111d03..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/ActionProviderWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/StandaloneActionMode.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/StandaloneActionMode.class deleted file mode 100644 index 546d29f8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/StandaloneActionMode.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.class deleted file mode 100644 index 64f7c21b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.class deleted file mode 100644 index a0db78b2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenu.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenu.class deleted file mode 100644 index 984fbada..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenu.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItem.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItem.class deleted file mode 100644 index 1b120bf7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItem.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.class deleted file mode 100644 index 8d7071d3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$ActionButtonSubmenu.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$ActionButtonSubmenu.class deleted file mode 100644 index 728c15c9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$ActionButtonSubmenu.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$HasPermanentMenuKey.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$HasPermanentMenuKey.class deleted file mode 100644 index 061492e2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$HasPermanentMenuKey.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OpenOverflowRunnable.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OpenOverflowRunnable.class deleted file mode 100644 index 503b009d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OpenOverflowRunnable.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowMenuButton.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowMenuButton.class deleted file mode 100644 index 4b31f642..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowMenuButton.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowPopup.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowPopup.class deleted file mode 100644 index 01507fb1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowPopup.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$PopupPresenterCallback.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$PopupPresenterCallback.class deleted file mode 100644 index 37d158d0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$PopupPresenterCallback.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState$1.class deleted file mode 100644 index 5008ae82..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState.class deleted file mode 100644 index 115ca101..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.class deleted file mode 100644 index 6dbc5200..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$ActionMenuChildView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$ActionMenuChildView.class deleted file mode 100644 index bd4e448e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$ActionMenuChildView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$LayoutParams.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$LayoutParams.class deleted file mode 100644 index 50d67fcb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$LayoutParams.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView.class deleted file mode 100644 index a84ab5cb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.class deleted file mode 100644 index b6f25ad0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ListMenuItemView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ListMenuItemView.class deleted file mode 100644 index c190507c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ListMenuItemView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$Callback.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$Callback.class deleted file mode 100644 index 48c1cb93..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$Callback.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$ItemInvoker.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$ItemInvoker.class deleted file mode 100644 index fd0e5d07..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$ItemInvoker.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder.class deleted file mode 100644 index 9395c4d9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemImpl.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemImpl.class deleted file mode 100644 index 4ecae954..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemImpl.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper$1.class deleted file mode 100644 index 8dad1823..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.class deleted file mode 100644 index 72db4048..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$ExpandedIndexObserver.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$ExpandedIndexObserver.class deleted file mode 100644 index 2ce6f8c4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$ExpandedIndexObserver.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$MenuAdapter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$MenuAdapter.class deleted file mode 100644 index 4a6e4c9a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$MenuAdapter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.class deleted file mode 100644 index ad6557a1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter$Callback.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter$Callback.class deleted file mode 100644 index 15e9b40b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter$Callback.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter.class deleted file mode 100644 index c6ab90ed..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView$ItemView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView$ItemView.class deleted file mode 100644 index 5f30df61..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView$ItemView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView.class deleted file mode 100644 index fbf5f9a2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuWrapper.class deleted file mode 100644 index aba5f4aa..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.class deleted file mode 100644 index e71c67dd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.class deleted file mode 100644 index bda99e96..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$1.class deleted file mode 100644 index 22b352b9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$VisibilityAnimListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$VisibilityAnimListener.class deleted file mode 100644 index 7360e62d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$VisibilityAnimListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView.class deleted file mode 100644 index 4f9e7ae7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContainer.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContainer.class deleted file mode 100644 index c4d56c54..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContainer.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView$1.class deleted file mode 100644 index b9e15900..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView.class deleted file mode 100644 index a1ee08e5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$1.class deleted file mode 100644 index 964edb3b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$2.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$2.class deleted file mode 100644 index 3a996aeb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$2.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$3.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$3.class deleted file mode 100644 index e8b210b7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$3.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$ExpandedActionViewMenuPresenter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$ExpandedActionViewMenuPresenter.class deleted file mode 100644 index 1922d890..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$ExpandedActionViewMenuPresenter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$HomeView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$HomeView.class deleted file mode 100644 index 094326d5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$HomeView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState$1.class deleted file mode 100644 index a7ba80c7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState.class deleted file mode 100644 index fb4c07bc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView.class deleted file mode 100644 index 0be7be63..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingButton.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingButton.class deleted file mode 100644 index 1465ae4f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingButton.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingTextView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingTextView.class deleted file mode 100644 index 4b95130d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingTextView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.class deleted file mode 100644 index 5d6d2e80..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$RecycleBin.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$RecycleBin.class deleted file mode 100644 index bce39568..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$RecycleBin.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState$1.class deleted file mode 100644 index b7f5fd40..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState.class deleted file mode 100644 index 4ab7e256..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner.class deleted file mode 100644 index 3381ced0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterContextMenuInfo.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterContextMenuInfo.class deleted file mode 100644 index 70d41eb8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterContextMenuInfo.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterDataSetObserver.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterDataSetObserver.class deleted file mode 100644 index 27169b1e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterDataSetObserver.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemLongClickListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemLongClickListener.class deleted file mode 100644 index de5845ec..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemLongClickListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemSelectedListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemSelectedListener.class deleted file mode 100644 index aa2f8535..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemSelectedListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$SelectionNotifier.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$SelectionNotifier.class deleted file mode 100644 index ea5e114f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$SelectionNotifier.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView.class deleted file mode 100644 index 96c541aa..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsLinearLayout.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsLinearLayout.class deleted file mode 100644 index 6f20f856..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsLinearLayout.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$1.class deleted file mode 100644 index 69efaa42..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$DropDownListView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$DropDownListView.class deleted file mode 100644 index b2720332..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$DropDownListView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ListSelectorHider.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ListSelectorHider.class deleted file mode 100644 index 4a81a4c9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ListSelectorHider.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupDataSetObserver.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupDataSetObserver.class deleted file mode 100644 index ec726ae0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupDataSetObserver.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupScrollListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupScrollListener.class deleted file mode 100644 index 13db2149..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupScrollListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupTouchInterceptor.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupTouchInterceptor.class deleted file mode 100644 index cbdfee54..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupTouchInterceptor.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ResizePopupRunnable.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ResizePopupRunnable.class deleted file mode 100644 index 77b61129..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ResizePopupRunnable.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow.class deleted file mode 100644 index cf7938fe..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$AccessibilityEventSender.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$AccessibilityEventSender.class deleted file mode 100644 index ca6f3b75..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$AccessibilityEventSender.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$RefreshProgressRunnable.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$RefreshProgressRunnable.class deleted file mode 100644 index 4fc92e77..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$RefreshProgressRunnable.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState$1.class deleted file mode 100644 index 1ffe42b6..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState.class deleted file mode 100644 index 344299f0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar.class deleted file mode 100644 index 1dfd7f39..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropDownAdapter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropDownAdapter.class deleted file mode 100644 index 464dd5b3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropDownAdapter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup$1.class deleted file mode 100644 index 302265b6..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup.class deleted file mode 100644 index 5b646122..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$SpinnerPopup.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$SpinnerPopup.class deleted file mode 100644 index b4b1e9c4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$SpinnerPopup.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner.class deleted file mode 100644 index af41e52a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsView.class deleted file mode 100644 index 5f358247..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$1.class deleted file mode 100644 index 65980f24..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabAdapter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabAdapter.class deleted file mode 100644 index 00dd3041..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabAdapter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabClickListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabClickListener.class deleted file mode 100644 index 71ff8a54..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabClickListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabView.class deleted file mode 100644 index 0910edf7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$VisibilityAnimListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$VisibilityAnimListener.class deleted file mode 100644 index 51d073d2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$VisibilityAnimListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.class deleted file mode 100644 index 9553dff5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode$Callback.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode$Callback.class deleted file mode 100644 index c122c6d3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode$Callback.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode.class deleted file mode 100644 index cc64b67a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider$SubUiVisibilityListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider$SubUiVisibilityListener.class deleted file mode 100644 index 48f981ac..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider$SubUiVisibilityListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider.class deleted file mode 100644 index 1699a0fc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/CollapsibleActionView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/CollapsibleActionView.class deleted file mode 100644 index e33c6664..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/CollapsibleActionView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Menu.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Menu.class deleted file mode 100644 index 917380a1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Menu.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$InflatedOnMenuItemClickListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$InflatedOnMenuItemClickListener.class deleted file mode 100644 index 87ae93fd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$InflatedOnMenuItemClickListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$MenuState.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$MenuState.class deleted file mode 100644 index 0c03c6ca..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$MenuState.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater.class deleted file mode 100644 index ce2200ce..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnActionExpandListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnActionExpandListener.class deleted file mode 100644 index c9055243..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnActionExpandListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnMenuItemClickListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnMenuItemClickListener.class deleted file mode 100644 index 67695aff..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnMenuItemClickListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem.class deleted file mode 100644 index 647b3331..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/SubMenu.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/SubMenu.class deleted file mode 100644 index 6bb94ff1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/SubMenu.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window$Callback.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window$Callback.class deleted file mode 100644 index 7dfe3560..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window$Callback.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window.class deleted file mode 100644 index 13353f82..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityChooserModelClient.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityChooserModelClient.class deleted file mode 100644 index 10861aa2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityChooserModelClient.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityResolveInfo.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityResolveInfo.class deleted file mode 100644 index f1aec6dc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityResolveInfo.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivitySorter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivitySorter.class deleted file mode 100644 index 3c1a4ee8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivitySorter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$DefaultSorter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$DefaultSorter.class deleted file mode 100644 index f462a6fc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$DefaultSorter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoricalRecord.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoricalRecord.class deleted file mode 100644 index 7de936f7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoricalRecord.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader$1.class deleted file mode 100644 index 5a7e018d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader.class deleted file mode 100644 index d08e2aed..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryPersister.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryPersister.class deleted file mode 100644 index 4a0ff822..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryPersister.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$OnChooseActivityListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$OnChooseActivityListener.class deleted file mode 100644 index 151d2d57..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$OnChooseActivityListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor$1.class deleted file mode 100644 index 5a8476b3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor.class deleted file mode 100644 index 1e98dd25..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel.class deleted file mode 100644 index d933174f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$1.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$1.class deleted file mode 100644 index 9e35e283..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$1.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$2.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$2.class deleted file mode 100644 index 895599e8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$2.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$3.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$3.class deleted file mode 100644 index 41aceb93..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$3.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$ActivityChooserViewAdapter.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$ActivityChooserViewAdapter.class deleted file mode 100644 index 9c059969..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$ActivityChooserViewAdapter.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$Callbacks.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$Callbacks.class deleted file mode 100644 index 806c9a55..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$Callbacks.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$SetActivated.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$SetActivated.class deleted file mode 100644 index a42d8f25..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$SetActivated.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView.class deleted file mode 100644 index f457429e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$OnShareTargetSelectedListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$OnShareTargetSelectedListener.class deleted file mode 100644 index 25d140b5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$OnShareTargetSelectedListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareAcitivityChooserModelPolicy.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareAcitivityChooserModelPolicy.class deleted file mode 100644 index 6fb964b3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareAcitivityChooserModelPolicy.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareMenuItemOnMenuItemClickListener.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareMenuItemOnMenuItemClickListener.class deleted file mode 100644 index acbf8a67..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareMenuItemOnMenuItemClickListener.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider.class deleted file mode 100644 index 51329f7b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider.class and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/jarlist.cache b/android-libraries/ActionBarSherlock/bin/jarlist.cache deleted file mode 100644 index 1b5ec3f9..00000000 --- a/android-libraries/ActionBarSherlock/bin/jarlist.cache +++ /dev/null @@ -1,3 +0,0 @@ -# cache for current jar dependecy. DO NOT EDIT. -# format is -# Encoding is UTF-8 diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png deleted file mode 100644 index 42bb3664..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png deleted file mode 100644 index d12d923c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png deleted file mode 100644 index 612889a4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png deleted file mode 100644 index 9a80fb7b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png deleted file mode 100644 index 2b4a61ab..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png deleted file mode 100644 index 75d3269b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png deleted file mode 100644 index ca7df22e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png deleted file mode 100644 index b110188b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_light_holo.9.png deleted file mode 100644 index 95c76e3d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png deleted file mode 100644 index d6b96349..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png deleted file mode 100644 index 20d7080b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png deleted file mode 100644 index 1dc40c9b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png deleted file mode 100644 index 48bc5369..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png deleted file mode 100644 index 46fcf718..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png deleted file mode 100644 index 2adaa18e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png deleted file mode 100644 index 629911f0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png deleted file mode 100644 index 11c79406..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png deleted file mode 100644 index 720f52d3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png deleted file mode 100644 index 6e4332fb..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png deleted file mode 100644 index ac9f39b4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png deleted file mode 100644 index 932b70a9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png deleted file mode 100644 index f4ddedfd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png deleted file mode 100644 index fc2e90a8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png deleted file mode 100644 index 2d8352bf..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png deleted file mode 100644 index 365e83e5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png deleted file mode 100644 index 0a42fb2b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png deleted file mode 100644 index 8051417d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_light.9.png deleted file mode 100644 index c9065de5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png deleted file mode 100644 index 9deb8f03..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_light.png deleted file mode 100644 index 5b29b1cc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png deleted file mode 100644 index bd2d459b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_light.png deleted file mode 100644 index c6c30a10..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png deleted file mode 100644 index cb6ebdaf..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png deleted file mode 100644 index 48d47284..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png deleted file mode 100644 index f5c51305..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_light.png deleted file mode 100644 index 7c12c576..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_activated_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_activated_holo.9.png deleted file mode 100644 index 4da70ac7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_activated_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_dark.9.png deleted file mode 100644 index a57e66ac..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_light.9.png deleted file mode 100644 index 75bd2d7d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_focused_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_focused_holo.9.png deleted file mode 100644 index f9587289..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_longpressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_longpressed_holo.9.png deleted file mode 100644 index 4da70ac7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_longpressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png deleted file mode 100644 index d3e72411..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_light.9.png deleted file mode 100644 index d3e72411..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png deleted file mode 100644 index cb128962..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png deleted file mode 100644 index 233da8e3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png deleted file mode 100644 index 29ad572b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png deleted file mode 100644 index 612b8872..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png deleted file mode 100644 index 6cde0bd6..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_light.9.png deleted file mode 100644 index 82af131a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png deleted file mode 100644 index 15f110b9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_light.9.png deleted file mode 100644 index 15f110b9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png deleted file mode 100644 index 4bf430f1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png deleted file mode 100644 index 4bf430f1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_inner_holo.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_inner_holo.png deleted file mode 100644 index 919c328b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_inner_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_outer_holo.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_outer_holo.png deleted file mode 100644 index ad987cb4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_outer_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png deleted file mode 100644 index 9ae770c1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png deleted file mode 100644 index e932deee..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png deleted file mode 100644 index 5caed9d4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png deleted file mode 100644 index 55abe710..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png deleted file mode 100644 index 88742927..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png deleted file mode 100644 index a071008e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png deleted file mode 100644 index 8747bfc5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png deleted file mode 100644 index 6893b36b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png deleted file mode 100644 index 1e6ab9aa..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_holo.9.png deleted file mode 100644 index 4dfaac80..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png deleted file mode 100644 index 4060199b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png deleted file mode 100644 index 86304e5a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/ic_launcher.png deleted file mode 100644 index bcfa0581..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-ldpi/ic_launcher.png b/android-libraries/ActionBarSherlock/bin/res/drawable-ldpi/ic_launcher.png deleted file mode 100644 index dd7c05b0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png deleted file mode 100644 index c2fef9ad..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png deleted file mode 100644 index 54c82238..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png deleted file mode 100644 index baa52989..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png deleted file mode 100644 index fed7fa6a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png deleted file mode 100644 index d582d390..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png deleted file mode 100644 index 735c0490..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png deleted file mode 100644 index 1071e098..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png deleted file mode 100644 index a9f2be43..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_light_holo.9.png deleted file mode 100644 index a51dc9bc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png deleted file mode 100644 index 89eccd47..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png deleted file mode 100644 index fa4ca757..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png deleted file mode 100644 index f2f6fc79..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png deleted file mode 100644 index 6584f956..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png deleted file mode 100644 index f3a769b2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png deleted file mode 100644 index 06010e92..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png deleted file mode 100644 index ff64b454..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png deleted file mode 100644 index b1ac62c7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png deleted file mode 100644 index f2924247..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png deleted file mode 100644 index b1d51c67..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png deleted file mode 100644 index 10b0432b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png deleted file mode 100644 index 96329958..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png deleted file mode 100644 index 0837e7d2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png deleted file mode 100644 index 0a71f49f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png deleted file mode 100644 index 4e4e5165..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png deleted file mode 100644 index a6c5c8fd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png deleted file mode 100644 index 9da38a32..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png deleted file mode 100644 index 58d8dc1d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_light.9.png deleted file mode 100644 index f5a473b2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png deleted file mode 100644 index 7290c5c8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_light.png deleted file mode 100644 index 7d944d3a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png deleted file mode 100644 index 3382680c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_light.png deleted file mode 100644 index f11b21f4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png deleted file mode 100644 index 3b4e7462..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png deleted file mode 100644 index aa5ea4fd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png deleted file mode 100644 index 00e499c8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_light.png deleted file mode 100644 index 240d4069..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_activated_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_activated_holo.9.png deleted file mode 100644 index 92030f26..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_activated_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_dark.9.png deleted file mode 100644 index a57e66ac..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_light.9.png deleted file mode 100644 index 75bd2d7d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_focused_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_focused_holo.9.png deleted file mode 100644 index 7c9fdbf1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_longpressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_longpressed_holo.9.png deleted file mode 100644 index 92030f26..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_longpressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png deleted file mode 100644 index d6717c1f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_light.9.png deleted file mode 100644 index d6717c1f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png deleted file mode 100644 index 9428f21a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png deleted file mode 100644 index 80cd8e61..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png deleted file mode 100644 index 99cf362c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png deleted file mode 100644 index 50636873..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png deleted file mode 100644 index efe935f2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_light.9.png deleted file mode 100644 index 8672828a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png deleted file mode 100644 index 333dda5a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_light.9.png deleted file mode 100644 index 333dda5a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png deleted file mode 100644 index 29ffde6a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png deleted file mode 100644 index 29ffde6a..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_inner_holo.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_inner_holo.png deleted file mode 100644 index ff1dc7f5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_inner_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_outer_holo.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_outer_holo.png deleted file mode 100644 index 0b113bf9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_outer_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png deleted file mode 100644 index 6c63dd4b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png deleted file mode 100644 index 3928d0d0..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png deleted file mode 100644 index f7219e89..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png deleted file mode 100644 index ede8b34c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png deleted file mode 100644 index e4de3f63..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png deleted file mode 100644 index 334ec168..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png deleted file mode 100644 index 8d9531e4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png deleted file mode 100644 index 0f504f82..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png deleted file mode 100644 index bce0e08e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_holo.9.png deleted file mode 100644 index dd022de2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png deleted file mode 100644 index 2852fb5d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png deleted file mode 100644 index d2716b33..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/ic_launcher.png deleted file mode 100644 index 85848ff4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png deleted file mode 100644 index d01fae99..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png deleted file mode 100644 index 5fc7d87f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png deleted file mode 100644 index f6cbc621..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png deleted file mode 100644 index f395cbde..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png deleted file mode 100644 index 6e6b999b..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png deleted file mode 100644 index ca2e57bd..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png deleted file mode 100644 index a57c1b53..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png deleted file mode 100644 index 2c4dd4f9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png deleted file mode 100644 index 27d6c8b9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png deleted file mode 100644 index 58263065..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png deleted file mode 100644 index 3e722238..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png deleted file mode 100644 index d2d77540..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png deleted file mode 100644 index 140518f8..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png deleted file mode 100644 index 97a6bd57..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png deleted file mode 100644 index 3069943f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png deleted file mode 100644 index 920d2b58..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png deleted file mode 100644 index dfe74064..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png deleted file mode 100644 index 959ca7af..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png deleted file mode 100644 index df972124..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png deleted file mode 100644 index 79201882..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png deleted file mode 100644 index 1801d343..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png deleted file mode 100644 index b3d3e199..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png deleted file mode 100644 index 1bf70ca2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png deleted file mode 100644 index 100d3166..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png deleted file mode 100644 index 58bdedd2..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png deleted file mode 100644 index 66d9d8dc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png deleted file mode 100644 index 86e24585..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png deleted file mode 100644 index b4058439..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png deleted file mode 100644 index bfc1c660..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png deleted file mode 100644 index 87a5a420..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png deleted file mode 100644 index fd5f4161..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png deleted file mode 100644 index 0ccab808..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png deleted file mode 100644 index ef9792a4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png deleted file mode 100644 index 3f275ad1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png deleted file mode 100644 index 4492c498..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png deleted file mode 100644 index a61854b4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_activated_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_activated_holo.9.png deleted file mode 100644 index c6cbc4d6..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_activated_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png deleted file mode 100644 index c1692f8e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_light.9.png deleted file mode 100644 index e190cfc4..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_focused_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_focused_holo.9.png deleted file mode 100644 index 9059f3e5..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_longpressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_longpressed_holo.9.png deleted file mode 100644 index c6cbc4d6..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_longpressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png deleted file mode 100644 index 8acdbf45..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png deleted file mode 100644 index 8acdbf45..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png deleted file mode 100644 index 0117091f..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png deleted file mode 100644 index 4f123024..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png deleted file mode 100644 index d9108065..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png deleted file mode 100644 index 68494e75..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png deleted file mode 100644 index b8a964bc..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png deleted file mode 100644 index 380f8d1e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png deleted file mode 100644 index a6bd0ce7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png deleted file mode 100644 index a6bd0ce7..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png deleted file mode 100644 index 058c512c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png deleted file mode 100644 index 058c512c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_inner_holo.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_inner_holo.png deleted file mode 100644 index 662036ca..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_inner_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_outer_holo.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_outer_holo.png deleted file mode 100644 index 6d33f314..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_outer_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png deleted file mode 100644 index 487c06b3..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png deleted file mode 100644 index 3724097e..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png deleted file mode 100644 index b7088e1d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png deleted file mode 100644 index 8e91ab97..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png deleted file mode 100644 index e16fead1..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png deleted file mode 100644 index 475dfcd9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png deleted file mode 100644 index 3b6ec51d..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png deleted file mode 100644 index 6e829720..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png deleted file mode 100644 index 140ebfde..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_holo.9.png deleted file mode 100644 index a94f0984..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png deleted file mode 100644 index 25ec789c..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png deleted file mode 100644 index c5ed3cb9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/ic_launcher.png deleted file mode 100644 index 916901e9..00000000 Binary files a/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/BuildConfig.java b/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/BuildConfig.java deleted file mode 100644 index ceb2ab07..00000000 --- a/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/BuildConfig.java +++ /dev/null @@ -1,6 +0,0 @@ -/** Automatically generated file. DO NOT MODIFY */ -package com.actionbarsherlock; - -public final class BuildConfig { - public final static boolean DEBUG = true; -} \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/R.java b/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/R.java deleted file mode 100644 index b48b6242..00000000 --- a/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/R.java +++ /dev/null @@ -1,2813 +0,0 @@ -/* AUTO-GENERATED FILE. DO NOT MODIFY. - * - * This class was automatically generated by the - * aapt tool from the resource data it found. It - * should not be modified by hand. - */ - -package com.actionbarsherlock; - -public final class R { - public static final class attr { - /** Specified if we are forcing an action item overflow menu. -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int absForceOverflow=0x7f010039; - /** Custom divider drawable to use for elements in the action bar. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarDivider=0x7f01000e; - /** Custom item state list drawable background for action bar items. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarItemBackground=0x7f01000f; - /** Size of the Action Bar, including the contextual - bar used to present Action Modes. -

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

May be one of the following constant values.

- ---- - -
ConstantValueDescription
wrap_content0
- */ - public static int actionBarSize=0x7f01000d; - /** Reference to a style for the split Action Bar. This style - controls the split component that holds the menu/action - buttons. actionBarStyle is still used for the primary - bar. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarSplitStyle=0x7f01000b; - /** Reference to a style for the Action Bar -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarStyle=0x7f01000a; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarTabBarStyle=0x7f010007; - /** Default style for tabs within an action bar -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarTabStyle=0x7f010006; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarTabTextStyle=0x7f010008; - /** Reference to a theme that should be used to inflate widgets - and layouts destined for the action bar. Most of the time - this will be a reference to the current theme, but when - the action bar has a significantly different contrast - profile than the rest of the activity the difference - can become important. If this is set to @null the current - theme will be used. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionBarWidgetTheme=0x7f01000c; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionButtonStyle=0x7f01002b; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionDropDownStyle=0x7f01002a; - /** TextAppearance style that will be applied to text that - appears within action menu items. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionMenuTextAppearance=0x7f010010; - /** Color for text that appears within action menu items. -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int actionMenuTextColor=0x7f010011; - /** Background drawable to use for action mode UI -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModeBackground=0x7f010014; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModeCloseButtonStyle=0x7f010013; - /** Drawable to use for the close action mode button -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModeCloseDrawable=0x7f010016; - /** PopupWindow style to use for action modes when showing as a window overlay. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModePopupWindowStyle=0x7f010018; - /** Drawable to use for the Share action button in WebView selection action modes -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModeShareDrawable=0x7f010017; - /** Background drawable to use for action mode UI in the lower split bar -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModeSplitBackground=0x7f010015; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionModeStyle=0x7f010012; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionOverflowButtonStyle=0x7f010009; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int actionSpinnerItemStyle=0x7f010030; - /** Drawable used as a background for activated items. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int activatedBackgroundIndicator=0x7f010038; - /** Default ActivityChooserView style. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int activityChooserViewStyle=0x7f010037; - /**

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int background=0x7f010002; - /**

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int backgroundSplit=0x7f010003; - /** Specifies a background drawable for a second stacked row of the action bar. -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int backgroundStacked=0x7f010040; - /** Small Button style. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int buttonStyleSmall=0x7f010019; - /** Specifies a layout for custom navigation. Overrides navigationMode. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int customNavigationLayout=0x7f010041; - /** Options affecting how the action bar is displayed. -

Must be one or more (separated by '|') of the following constant values.

- ---- - - - - - - -
ConstantValueDescription
useLogo0x1
showHome0x2
homeAsUp0x4
showTitle0x8
showCustom0x10
disableHome0x20
- */ - public static int displayOptions=0x7f01003b; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int divider=0x7f010005; - /** Drawable to use for generic vertical dividers. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int dividerVertical=0x7f010029; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int dropDownListViewStyle=0x7f01002d; - /**

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int dropdownListPreferredItemHeight=0x7f01002f; - /** The drawable to show in the button for expanding the activities overflow popup. - Note: Clients would like to set this drawable - as a clue about the action the chosen activity will perform. For - example, if share activity is to be chosen the drawable should - give a clue that sharing is to be performed. - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int expandActivityOverflowButtonDrawable=0x7f010050; - /** Default background for the menu header. -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int headerBackground=0x7f01004a; - /**

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int height=0x7f010004; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int homeAsUpIndicator=0x7f01002c; - /** Specifies a layout to use for the "home" section of the action bar. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int homeLayout=0x7f010042; - /** Default horizontal divider between rows of menu items. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int horizontalDivider=0x7f010048; - /** Specifies the drawable used for the application icon. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int icon=0x7f01003e; - /** Specifies a style resource to use for an indeterminate progress spinner. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int indeterminateProgressStyle=0x7f010044; - /** The maximal number of items initially shown in the activity list. -

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int initialActivityCount=0x7f01004f; - /** Default background for each menu item. -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int itemBackground=0x7f01004b; - /** Default disabled icon alpha for each menu item that shows an icon. -

Must be a floating point value, such as "1.2". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int itemIconDisabledAlpha=0x7f01004d; - /** Specifies padding that should be applied to the left and right sides of - system-provided items in the bar. -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int itemPadding=0x7f010046; - /** Default appearance of menu item text. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int itemTextAppearance=0x7f010047; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int listPopupWindowStyle=0x7f010036; - /** A smaller, sleeker list item height. -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int listPreferredItemHeightSmall=0x7f010023; - /** The preferred padding along the left edge of list items. -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int listPreferredItemPaddingLeft=0x7f010024; - /** The preferred padding along the right edge of list items. -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int listPreferredItemPaddingRight=0x7f010025; - /** Specifies the drawable used for the application logo. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int logo=0x7f01003f; - /** The type of navigation to use. -

Must be one of the following constant values.

- ---- - - - -
ConstantValueDescription
normal0 Normal static title text
listMode1 The action bar will use a selection list for navigation.
tabMode2 The action bar will use a series of horizontal tabs for navigation.
- */ - public static int navigationMode=0x7f01003a; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int popupMenuStyle=0x7f01002e; - /** Whether space should be reserved in layout when an icon is missing. -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int preserveIconSpacing=0x7f01004e; - /** Specifies the horizontal padding on either end for an embedded progress bar. -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int progressBarPadding=0x7f010045; - /** Specifies a style resource to use for an embedded progress bar. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int progressBarStyle=0x7f010043; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int spinnerDropDownItemStyle=0x7f010022; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int spinnerItemStyle=0x7f010021; - /** Specifies subtitle text used for navigationMode="normal" -

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int subtitle=0x7f01003d; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int subtitleTextStyle=0x7f010001; - /** Text color, typeface, size, and style for the text inside of a popup menu. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int textAppearanceLargePopupMenu=0x7f01001b; - /** The preferred TextAppearance for the primary text of small list items. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int textAppearanceListItemSmall=0x7f010026; - /** Text color, typeface, size, and style for "small" text. Defaults to secondary text color. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int textAppearanceSmall=0x7f01001d; - /** Text color, typeface, size, and style for small text inside of a popup menu. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int textAppearanceSmallPopupMenu=0x7f01001c; - /**

Must be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int textColorPrimary=0x7f01001e; - /**

Must be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int textColorPrimaryDisableOnly=0x7f01001f; - /**

Must be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int textColorPrimaryInverse=0x7f010020; - /** Specifies title text used for navigationMode="normal" -

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int title=0x7f01003c; - /**

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int titleTextStyle=0x7f010000; - /** Default vertical divider between menu items. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int verticalDivider=0x7f010049; - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowActionBar=0x7f010032; - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowActionBarOverlay=0x7f010033; - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowActionModeOverlay=0x7f010034; - /** Default animations for the menu. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int windowAnimationStyle=0x7f01004c; - /** This Drawable is overlaid over the foreground of the Window's content area, usually - to place a shadow below the title. -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - */ - public static int windowContentOverlay=0x7f01001a; - /**

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowMinWidthMajor=0x7f010027; - /**

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowMinWidthMinor=0x7f010028; - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowNoTitle=0x7f010031; - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int windowSplitActionBar=0x7f010035; - } - public static final class bool { - public static int abs__action_bar_embed_tabs=0x7f050000; - public static int abs__action_bar_expanded_action_views_exclusive=0x7f050002; - /** Whether action menu items should be displayed in ALLCAPS or not. - Defaults to true. If this is not appropriate for specific locales - it should be disabled in that locale's resources. - */ - public static int abs__config_actionMenuItemAllCaps=0x7f050004; - /** Whether action menu items should obey the "withText" showAsAction - flag. This may be set to false for situations where space is - extremely limited. - Whether action menu items should obey the "withText" showAsAction - flag. This may be set to false for situations where space is - extremely limited. - */ - public static int abs__config_allowActionMenuItemTextWithIcon=0x7f050005; - /** Sets whether menu shortcuts should be displayed on panel menus when - a keyboard is present. - */ - public static int abs__config_showMenuShortcutsWhenKeyboardPresent=0x7f050003; - public static int abs__split_action_bar_is_narrow=0x7f050001; - } - public static final class color { - public static int abs__background_holo_dark=0x7f060000; - public static int abs__background_holo_light=0x7f060001; - public static int abs__bright_foreground_disabled_holo_dark=0x7f060004; - public static int abs__bright_foreground_disabled_holo_light=0x7f060005; - public static int abs__bright_foreground_holo_dark=0x7f060002; - public static int abs__bright_foreground_holo_light=0x7f060003; - public static int abs__bright_foreground_inverse_holo_dark=0x7f060006; - public static int abs__bright_foreground_inverse_holo_light=0x7f060007; - public static int abs__holo_blue_light=0x7f060008; - public static int abs__primary_text_disable_only_holo_dark=0x7f060009; - public static int abs__primary_text_disable_only_holo_light=0x7f06000a; - public static int abs__primary_text_holo_dark=0x7f06000b; - public static int abs__primary_text_holo_light=0x7f06000c; - } - public static final class dimen { - /** Default height of an action bar. - Default height of an action bar. - Default height of an action bar. - Default height of an action bar. - Default height of an action bar. - Default height of an action bar. - Default height of an action bar. - Default height of an action bar. - */ - public static int abs__action_bar_default_height=0x7f070001; - /** Vertical padding around action bar icons. - Vertical padding around action bar icons. - Vertical padding around action bar icons. - Vertical padding around action bar icons. - Vertical padding around action bar icons. - Vertical padding around action bar icons. - Vertical padding around action bar icons. - Vertical padding around action bar icons. - */ - public static int abs__action_bar_icon_vertical_padding=0x7f070002; - /** Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - Bottom margin for action bar subtitles - */ - public static int abs__action_bar_subtitle_bottom_margin=0x7f070006; - /** Text size for action bar subtitles - Text size for action bar subtitles - Text size for action bar subtitles - Text size for action bar subtitles - Text size for action bar subtitles - Text size for action bar subtitles - Text size for action bar subtitles - Text size for action bar subtitles - */ - public static int abs__action_bar_subtitle_text_size=0x7f070004; - /** Top margin for action bar subtitles - Top margin for action bar subtitles - Top margin for action bar subtitles - Top margin for action bar subtitles - Top margin for action bar subtitles - Top margin for action bar subtitles - Top margin for action bar subtitles - Top margin for action bar subtitles - */ - public static int abs__action_bar_subtitle_top_margin=0x7f070005; - /** Text size for action bar titles - Text size for action bar titles - Text size for action bar titles - Text size for action bar titles - Text size for action bar titles - Text size for action bar titles - Text size for action bar titles - Text size for action bar titles - */ - public static int abs__action_bar_title_text_size=0x7f070003; - /** Minimum width for an action button in the menu area of an action bar - Minimum width for an action button in the menu area of an action bar - */ - public static int abs__action_button_min_width=0x7f070007; - /** Dialog title height - */ - public static int abs__alert_dialog_title_height=0x7f070008; - /** The maximum width we would prefer dialogs to be. 0 if there is no - maximum (let them grow as large as the screen). Actual values are - specified for -large and -xlarge configurations. - */ - public static int abs__config_prefDialogWidth=0x7f070000; - /** The platform's desired minimum size for a dialog's width when it - is along the major axis (that is the screen is landscape). This may - be either a fraction or a dimension. - The platform's desired minimum size for a dialog's width when it - is along the major axis (that is the screen is landscape). This may - be either a fraction or a dimension. - The platform's desired minimum size for a dialog's width when it - is along the major axis (that is the screen is landscape). This may - be either a fraction or a dimension. - */ - public static int abs__dialog_min_width_major=0x7f070009; - /** The platform's desired minimum size for a dialog's width when it - is along the minor axis (that is the screen is portrait). This may - be either a fraction or a dimension. - The platform's desired minimum size for a dialog's width when it - is along the minor axis (that is the screen is portrait). This may - be either a fraction or a dimension. - The platform's desired minimum size for a dialog's width when it - is along the minor axis (that is the screen is portrait). This may - be either a fraction or a dimension. - */ - public static int abs__dialog_min_width_minor=0x7f07000a; - /** Minimum width for an action button in the menu area of an action bar - Minimum width for an action button in the menu area of an action bar - */ - public static int action_button_min_width=0x7f07000b; - } - public static final class drawable { - public static int abs__ab_bottom_solid_dark_holo=0x7f020000; - public static int abs__ab_bottom_solid_inverse_holo=0x7f020001; - public static int abs__ab_bottom_solid_light_holo=0x7f020002; - public static int abs__ab_bottom_transparent_dark_holo=0x7f020003; - public static int abs__ab_bottom_transparent_light_holo=0x7f020004; - public static int abs__ab_share_pack_holo_dark=0x7f020005; - public static int abs__ab_share_pack_holo_light=0x7f020006; - public static int abs__ab_solid_dark_holo=0x7f020007; - public static int abs__ab_solid_light_holo=0x7f020008; - public static int abs__ab_solid_shadow_holo=0x7f020009; - public static int abs__ab_stacked_solid_dark_holo=0x7f02000a; - public static int abs__ab_stacked_solid_light_holo=0x7f02000b; - public static int abs__ab_stacked_transparent_dark_holo=0x7f02000c; - public static int abs__ab_stacked_transparent_light_holo=0x7f02000d; - public static int abs__ab_transparent_dark_holo=0x7f02000e; - public static int abs__ab_transparent_light_holo=0x7f02000f; - public static int abs__activated_background_holo_dark=0x7f020010; - public static int abs__activated_background_holo_light=0x7f020011; - public static int abs__btn_cab_done_default_holo_dark=0x7f020012; - public static int abs__btn_cab_done_default_holo_light=0x7f020013; - public static int abs__btn_cab_done_focused_holo_dark=0x7f020014; - public static int abs__btn_cab_done_focused_holo_light=0x7f020015; - public static int abs__btn_cab_done_holo_dark=0x7f020016; - public static int abs__btn_cab_done_holo_light=0x7f020017; - public static int abs__btn_cab_done_pressed_holo_dark=0x7f020018; - public static int abs__btn_cab_done_pressed_holo_light=0x7f020019; - public static int abs__cab_background_bottom_holo_dark=0x7f02001a; - public static int abs__cab_background_bottom_holo_light=0x7f02001b; - public static int abs__cab_background_top_holo_dark=0x7f02001c; - public static int abs__cab_background_top_holo_light=0x7f02001d; - public static int abs__dialog_full_holo_dark=0x7f02001e; - public static int abs__dialog_full_holo_light=0x7f02001f; - public static int abs__ic_ab_back_holo_dark=0x7f020020; - public static int abs__ic_ab_back_holo_light=0x7f020021; - public static int abs__ic_cab_done_holo_dark=0x7f020022; - public static int abs__ic_cab_done_holo_light=0x7f020023; - public static int abs__ic_menu_moreoverflow_holo_dark=0x7f020024; - public static int abs__ic_menu_moreoverflow_holo_light=0x7f020025; - public static int abs__ic_menu_moreoverflow_normal_holo_dark=0x7f020026; - public static int abs__ic_menu_moreoverflow_normal_holo_light=0x7f020027; - public static int abs__ic_menu_share_holo_dark=0x7f020028; - public static int abs__ic_menu_share_holo_light=0x7f020029; - public static int abs__item_background_holo_dark=0x7f02002a; - public static int abs__item_background_holo_light=0x7f02002b; - public static int abs__list_activated_holo=0x7f02002c; - public static int abs__list_divider_holo_dark=0x7f02002d; - public static int abs__list_divider_holo_light=0x7f02002e; - public static int abs__list_focused_holo=0x7f02002f; - public static int abs__list_longpressed_holo=0x7f020030; - public static int abs__list_pressed_holo_dark=0x7f020031; - public static int abs__list_pressed_holo_light=0x7f020032; - public static int abs__list_selector_background_transition_holo_dark=0x7f020033; - public static int abs__list_selector_background_transition_holo_light=0x7f020034; - public static int abs__list_selector_disabled_holo_dark=0x7f020035; - public static int abs__list_selector_disabled_holo_light=0x7f020036; - public static int abs__list_selector_holo_dark=0x7f020037; - public static int abs__list_selector_holo_light=0x7f020038; - public static int abs__menu_dropdown_panel_holo_dark=0x7f020039; - public static int abs__menu_dropdown_panel_holo_light=0x7f02003a; - public static int abs__progress_bg_holo_dark=0x7f02003b; - public static int abs__progress_bg_holo_light=0x7f02003c; - public static int abs__progress_horizontal_holo_dark=0x7f02003d; - public static int abs__progress_horizontal_holo_light=0x7f02003e; - public static int abs__progress_medium_holo=0x7f02003f; - public static int abs__progress_primary_holo_dark=0x7f020040; - public static int abs__progress_primary_holo_light=0x7f020041; - public static int abs__progress_secondary_holo_dark=0x7f020042; - public static int abs__progress_secondary_holo_light=0x7f020043; - public static int abs__spinner_48_inner_holo=0x7f020044; - public static int abs__spinner_48_outer_holo=0x7f020045; - public static int abs__spinner_ab_default_holo_dark=0x7f020046; - public static int abs__spinner_ab_default_holo_light=0x7f020047; - public static int abs__spinner_ab_disabled_holo_dark=0x7f020048; - public static int abs__spinner_ab_disabled_holo_light=0x7f020049; - public static int abs__spinner_ab_focused_holo_dark=0x7f02004a; - public static int abs__spinner_ab_focused_holo_light=0x7f02004b; - public static int abs__spinner_ab_holo_dark=0x7f02004c; - public static int abs__spinner_ab_holo_light=0x7f02004d; - public static int abs__spinner_ab_pressed_holo_dark=0x7f02004e; - public static int abs__spinner_ab_pressed_holo_light=0x7f02004f; - public static int abs__tab_indicator_ab_holo=0x7f020050; - public static int abs__tab_selected_focused_holo=0x7f020051; - public static int abs__tab_selected_holo=0x7f020052; - public static int abs__tab_selected_pressed_holo=0x7f020053; - public static int abs__tab_unselected_pressed_holo=0x7f020054; - public static int ic_launcher=0x7f020055; - } - public static final class id { - public static int abs__action_bar=0x7f040022; - public static int abs__action_bar_container=0x7f040021; - public static int abs__action_bar_subtitle=0x7f040011; - public static int abs__action_bar_title=0x7f040010; - public static int abs__action_context_bar=0x7f040023; - public static int abs__action_menu_divider=0x7f04000c; - public static int abs__action_menu_presenter=0x7f04000d; - public static int abs__action_mode_bar=0x7f040026; - public static int abs__action_mode_bar_stub=0x7f040025; - public static int abs__action_mode_close_button=0x7f040014; - public static int abs__activity_chooser_view_content=0x7f040015; - public static int abs__checkbox=0x7f04001e; - public static int abs__content=0x7f04001d; - public static int abs__default_activity_button=0x7f040018; - public static int abs__expand_activities_button=0x7f040016; - public static int abs__home=0x7f04000a; - public static int abs__icon=0x7f04001a; - public static int abs__image=0x7f040017; - public static int abs__imageButton=0x7f040012; - public static int abs__list_item=0x7f040019; - public static int abs__progress_circular=0x7f04000e; - public static int abs__progress_horizontal=0x7f04000f; - public static int abs__radio=0x7f040020; - public static int abs__shortcut=0x7f04001f; - public static int abs__split_action_bar=0x7f040024; - public static int abs__textButton=0x7f040013; - public static int abs__title=0x7f04001b; - public static int abs__titleDivider=0x7f04001c; - public static int abs__up=0x7f04000b; - public static int disableHome=0x7f040009; - public static int homeAsUp=0x7f040006; - public static int listMode=0x7f040002; - public static int normal=0x7f040001; - public static int showCustom=0x7f040008; - public static int showHome=0x7f040005; - public static int showTitle=0x7f040007; - public static int tabMode=0x7f040003; - public static int useLogo=0x7f040004; - public static int wrap_content=0x7f040000; - } - public static final class integer { - public static int abs__max_action_buttons=0x7f080000; - } - public static final class layout { - public static int abs__action_bar_home=0x7f030000; - public static int abs__action_bar_tab=0x7f030001; - public static int abs__action_bar_tab_bar_view=0x7f030002; - public static int abs__action_bar_title_item=0x7f030003; - public static int abs__action_menu_item_layout=0x7f030004; - public static int abs__action_menu_layout=0x7f030005; - public static int abs__action_mode_bar=0x7f030006; - public static int abs__action_mode_close_item=0x7f030007; - public static int abs__activity_chooser_view=0x7f030008; - public static int abs__activity_chooser_view_list_item=0x7f030009; - public static int abs__dialog_title_holo=0x7f03000a; - public static int abs__list_menu_item_checkbox=0x7f03000b; - public static int abs__list_menu_item_icon=0x7f03000c; - public static int abs__list_menu_item_layout=0x7f03000d; - public static int abs__list_menu_item_radio=0x7f03000e; - public static int abs__popup_menu_item_layout=0x7f03000f; - public static int abs__screen_action_bar=0x7f030010; - public static int abs__screen_action_bar_overlay=0x7f030011; - public static int abs__screen_simple=0x7f030012; - public static int abs__screen_simple_overlay_action_mode=0x7f030013; - public static int main=0x7f030014; - public static int sherlock_spinner_dropdown_item=0x7f030015; - public static int sherlock_spinner_item=0x7f030016; - } - public static final class string { - /** Content description for the action bar "home" affordance. [CHAR LIMIT=NONE] - */ - public static int abs__action_bar_home_description=0x7f090000; - /** Content description for the action bar "up" affordance. [CHAR LIMIT=NONE] - */ - public static int abs__action_bar_up_description=0x7f090001; - /** Content description for the action menu overflow button. [CHAR LIMIT=NONE] - */ - public static int abs__action_menu_overflow_description=0x7f090002; - /** Label for the "Done" button on the far left of action mode toolbars. - */ - public static int abs__action_mode_done=0x7f090003; - /** Title default for a dialog showing possible activities in ActivityChooserView [CHAR LIMIT=25] - */ - public static int abs__activity_chooser_view_dialog_title_default=0x7f090005; - /** Title for a button to expand the list of activities in ActivityChooserView [CHAR LIMIT=25] - */ - public static int abs__activity_chooser_view_see_all=0x7f090004; - /** Description of the shwoing of a popup window with activities to choose from. [CHAR LIMIT=NONE] - */ - public static int abs__activitychooserview_choose_application=0x7f090007; - /** Title for a dialog showing possible activities for sharing in ShareActionProvider [CHAR LIMIT=25] - */ - public static int abs__share_action_provider_share_with=0x7f090006; - /** Description of the choose target button in a ShareActionProvider (share UI). [CHAR LIMIT=NONE] - */ - public static int abs__shareactionprovider_share_with=0x7f090008; - /** Description of a share target (both in the list of such or the default share button) in a ShareActionProvider (share UI). [CHAR LIMIT=NONE] - */ - public static int abs__shareactionprovider_share_with_application=0x7f090009; - public static int app_name=0x7f09000b; - public static int hello=0x7f09000a; - } - public static final class style { - public static int DialogWindowTitle_Sherlock=0x7f0a0033; - public static int DialogWindowTitle_Sherlock_Light=0x7f0a0034; - public static int Sherlock___TextAppearance_Small=0x7f0a0047; - public static int Sherlock___Theme=0x7f0a004a; - public static int Sherlock___Theme_DarkActionBar=0x7f0a004c; - public static int Sherlock___Theme_Dialog=0x7f0a004d; - public static int Sherlock___Theme_Light=0x7f0a004b; - public static int Sherlock___Widget_ActionBar=0x7f0a0001; - public static int Sherlock___Widget_ActionMode=0x7f0a0016; - public static int Sherlock___Widget_ActivityChooserView=0x7f0a001e; - public static int Sherlock___Widget_Holo_DropDownItem=0x7f0a0029; - public static int Sherlock___Widget_Holo_ListView=0x7f0a0026; - public static int Sherlock___Widget_Holo_Spinner=0x7f0a0023; - public static int TextAppearance_Sherlock_DialogWindowTitle=0x7f0a0045; - public static int TextAppearance_Sherlock_Light_DialogWindowTitle=0x7f0a0046; - public static int TextAppearance_Sherlock_Light_Small=0x7f0a0049; - public static int TextAppearance_Sherlock_Light_Widget_PopupMenu_Large=0x7f0a0040; - public static int TextAppearance_Sherlock_Light_Widget_PopupMenu_Small=0x7f0a0042; - public static int TextAppearance_Sherlock_Small=0x7f0a0048; - public static int TextAppearance_Sherlock_Widget_ActionBar_Menu=0x7f0a0035; - public static int TextAppearance_Sherlock_Widget_ActionBar_Subtitle=0x7f0a0038; - public static int TextAppearance_Sherlock_Widget_ActionBar_Subtitle_Inverse=0x7f0a0039; - public static int TextAppearance_Sherlock_Widget_ActionBar_Title=0x7f0a0036; - public static int TextAppearance_Sherlock_Widget_ActionBar_Title_Inverse=0x7f0a0037; - public static int TextAppearance_Sherlock_Widget_ActionMode_Subtitle=0x7f0a003c; - public static int TextAppearance_Sherlock_Widget_ActionMode_Subtitle_Inverse=0x7f0a003d; - public static int TextAppearance_Sherlock_Widget_ActionMode_Title=0x7f0a003a; - public static int TextAppearance_Sherlock_Widget_ActionMode_Title_Inverse=0x7f0a003b; - public static int TextAppearance_Sherlock_Widget_DropDownItem=0x7f0a0044; - public static int TextAppearance_Sherlock_Widget_PopupMenu=0x7f0a003e; - public static int TextAppearance_Sherlock_Widget_PopupMenu_Large=0x7f0a003f; - public static int TextAppearance_Sherlock_Widget_PopupMenu_Small=0x7f0a0041; - public static int TextAppearance_Sherlock_Widget_TextView_SpinnerItem=0x7f0a0043; - public static int Theme_Sherlock=0x7f0a004e; - public static int Theme_Sherlock_Dialog=0x7f0a0056; - public static int Theme_Sherlock_ForceOverflow=0x7f0a0053; - public static int Theme_Sherlock_Light=0x7f0a004f; - public static int Theme_Sherlock_Light_DarkActionBar=0x7f0a0050; - public static int Theme_Sherlock_Light_DarkActionBar_ForceOverflow=0x7f0a0055; - public static int Theme_Sherlock_Light_Dialog=0x7f0a0057; - public static int Theme_Sherlock_Light_ForceOverflow=0x7f0a0054; - public static int Theme_Sherlock_Light_NoActionBar=0x7f0a0052; - public static int Theme_Sherlock_NoActionBar=0x7f0a0051; - public static int Widget=0x7f0a0000; - public static int Widget_Sherlock_ActionBar=0x7f0a0002; - public static int Widget_Sherlock_ActionBar_Solid=0x7f0a0003; - public static int Widget_Sherlock_ActionBar_TabBar=0x7f0a000a; - public static int Widget_Sherlock_ActionBar_TabText=0x7f0a000d; - public static int Widget_Sherlock_ActionBar_TabView=0x7f0a0007; - public static int Widget_Sherlock_ActionButton=0x7f0a0010; - public static int Widget_Sherlock_ActionButton_CloseMode=0x7f0a0012; - public static int Widget_Sherlock_ActionButton_Overflow=0x7f0a0014; - public static int Widget_Sherlock_ActionMode=0x7f0a0017; - public static int Widget_Sherlock_ActivityChooserView=0x7f0a001f; - public static int Widget_Sherlock_Button_Small=0x7f0a0021; - public static int Widget_Sherlock_DropDownItem_Spinner=0x7f0a002a; - public static int Widget_Sherlock_Light_ActionBar=0x7f0a0004; - public static int Widget_Sherlock_Light_ActionBar_Solid=0x7f0a0005; - public static int Widget_Sherlock_Light_ActionBar_Solid_Inverse=0x7f0a0006; - public static int Widget_Sherlock_Light_ActionBar_TabBar=0x7f0a000b; - public static int Widget_Sherlock_Light_ActionBar_TabBar_Inverse=0x7f0a000c; - public static int Widget_Sherlock_Light_ActionBar_TabText=0x7f0a000e; - public static int Widget_Sherlock_Light_ActionBar_TabText_Inverse=0x7f0a000f; - public static int Widget_Sherlock_Light_ActionBar_TabView=0x7f0a0008; - public static int Widget_Sherlock_Light_ActionBar_TabView_Inverse=0x7f0a0009; - public static int Widget_Sherlock_Light_ActionButton=0x7f0a0011; - public static int Widget_Sherlock_Light_ActionButton_CloseMode=0x7f0a0013; - public static int Widget_Sherlock_Light_ActionButton_Overflow=0x7f0a0015; - public static int Widget_Sherlock_Light_ActionMode=0x7f0a0018; - public static int Widget_Sherlock_Light_ActionMode_Inverse=0x7f0a0019; - public static int Widget_Sherlock_Light_ActivityChooserView=0x7f0a0020; - public static int Widget_Sherlock_Light_Button_Small=0x7f0a0022; - public static int Widget_Sherlock_Light_DropDownItem_Spinner=0x7f0a002b; - public static int Widget_Sherlock_Light_ListPopupWindow=0x7f0a001b; - public static int Widget_Sherlock_Light_ListView_DropDown=0x7f0a0028; - public static int Widget_Sherlock_Light_PopupMenu=0x7f0a001d; - public static int Widget_Sherlock_Light_PopupWindow_ActionMode=0x7f0a002d; - public static int Widget_Sherlock_Light_ProgressBar=0x7f0a002f; - public static int Widget_Sherlock_Light_ProgressBar_Horizontal=0x7f0a0031; - public static int Widget_Sherlock_Light_Spinner_DropDown_ActionBar=0x7f0a0025; - public static int Widget_Sherlock_ListPopupWindow=0x7f0a001a; - public static int Widget_Sherlock_ListView_DropDown=0x7f0a0027; - public static int Widget_Sherlock_PopupMenu=0x7f0a001c; - public static int Widget_Sherlock_PopupWindow_ActionMode=0x7f0a002c; - public static int Widget_Sherlock_ProgressBar=0x7f0a002e; - public static int Widget_Sherlock_ProgressBar_Horizontal=0x7f0a0030; - public static int Widget_Sherlock_Spinner_DropDown_ActionBar=0x7f0a0024; - public static int Widget_Sherlock_TextView_SpinnerItem=0x7f0a0032; - } - public static final class styleable { - /** Attributes used to style the Action Bar. -

Includes the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - -
AttributeDescription
{@link #SherlockActionBar_background com.actionbarsherlock:background} Specifies a background drawable for the action bar.
{@link #SherlockActionBar_backgroundSplit com.actionbarsherlock:backgroundSplit} Specifies a background drawable for the bottom component of a split action bar.
{@link #SherlockActionBar_backgroundStacked com.actionbarsherlock:backgroundStacked} Specifies a background drawable for a second stacked row of the action bar.
{@link #SherlockActionBar_customNavigationLayout com.actionbarsherlock:customNavigationLayout} Specifies a layout for custom navigation.
{@link #SherlockActionBar_displayOptions com.actionbarsherlock:displayOptions} Options affecting how the action bar is displayed.
{@link #SherlockActionBar_divider com.actionbarsherlock:divider} Specifies the drawable used for item dividers.
{@link #SherlockActionBar_height com.actionbarsherlock:height} Specifies a fixed height.
{@link #SherlockActionBar_homeLayout com.actionbarsherlock:homeLayout} Specifies a layout to use for the "home" section of the action bar.
{@link #SherlockActionBar_icon com.actionbarsherlock:icon} Specifies the drawable used for the application icon.
{@link #SherlockActionBar_indeterminateProgressStyle com.actionbarsherlock:indeterminateProgressStyle} Specifies a style resource to use for an indeterminate progress spinner.
{@link #SherlockActionBar_itemPadding com.actionbarsherlock:itemPadding} Specifies padding that should be applied to the left and right sides of - system-provided items in the bar.
{@link #SherlockActionBar_logo com.actionbarsherlock:logo} Specifies the drawable used for the application logo.
{@link #SherlockActionBar_navigationMode com.actionbarsherlock:navigationMode} The type of navigation to use.
{@link #SherlockActionBar_progressBarPadding com.actionbarsherlock:progressBarPadding} Specifies the horizontal padding on either end for an embedded progress bar.
{@link #SherlockActionBar_progressBarStyle com.actionbarsherlock:progressBarStyle} Specifies a style resource to use for an embedded progress bar.
{@link #SherlockActionBar_subtitle com.actionbarsherlock:subtitle} Specifies subtitle text used for navigationMode="normal"
{@link #SherlockActionBar_subtitleTextStyle com.actionbarsherlock:subtitleTextStyle} Specifies a style to use for subtitle text.
{@link #SherlockActionBar_title com.actionbarsherlock:title} Specifies title text used for navigationMode="normal"
{@link #SherlockActionBar_titleTextStyle com.actionbarsherlock:titleTextStyle} Specifies a style to use for title text.
- @see #SherlockActionBar_background - @see #SherlockActionBar_backgroundSplit - @see #SherlockActionBar_backgroundStacked - @see #SherlockActionBar_customNavigationLayout - @see #SherlockActionBar_displayOptions - @see #SherlockActionBar_divider - @see #SherlockActionBar_height - @see #SherlockActionBar_homeLayout - @see #SherlockActionBar_icon - @see #SherlockActionBar_indeterminateProgressStyle - @see #SherlockActionBar_itemPadding - @see #SherlockActionBar_logo - @see #SherlockActionBar_navigationMode - @see #SherlockActionBar_progressBarPadding - @see #SherlockActionBar_progressBarStyle - @see #SherlockActionBar_subtitle - @see #SherlockActionBar_subtitleTextStyle - @see #SherlockActionBar_title - @see #SherlockActionBar_titleTextStyle - */ - public static final int[] SherlockActionBar = { - 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, - 0x7f010004, 0x7f010005, 0x7f01003a, 0x7f01003b, - 0x7f01003c, 0x7f01003d, 0x7f01003e, 0x7f01003f, - 0x7f010040, 0x7f010041, 0x7f010042, 0x7f010043, - 0x7f010044, 0x7f010045, 0x7f010046 - }; - /** -

- @attr description - Specifies a background drawable for the action bar. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:background - */ - public static final int SherlockActionBar_background = 2; - /** -

- @attr description - Specifies a background drawable for the bottom component of a split action bar. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:backgroundSplit - */ - public static final int SherlockActionBar_backgroundSplit = 3; - /** -

- @attr description - Specifies a background drawable for a second stacked row of the action bar. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:backgroundStacked - */ - public static final int SherlockActionBar_backgroundStacked = 12; - /** -

- @attr description - Specifies a layout for custom navigation. Overrides navigationMode. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:customNavigationLayout - */ - public static final int SherlockActionBar_customNavigationLayout = 13; - /** -

- @attr description - Options affecting how the action bar is displayed. - - -

Must be one or more (separated by '|') of the following constant values.

- ---- - - - - - - -
ConstantValueDescription
useLogo0x1
showHome0x2
homeAsUp0x4
showTitle0x8
showCustom0x10
disableHome0x20
-

This is a private symbol. - @attr name android:displayOptions - */ - public static final int SherlockActionBar_displayOptions = 7; - /** -

- @attr description - Specifies the drawable used for item dividers. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:divider - */ - public static final int SherlockActionBar_divider = 5; - /** -

- @attr description - Specifies a fixed height. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:height - */ - public static final int SherlockActionBar_height = 4; - /** -

- @attr description - Specifies a layout to use for the "home" section of the action bar. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:homeLayout - */ - public static final int SherlockActionBar_homeLayout = 14; - /** -

- @attr description - Specifies the drawable used for the application icon. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:icon - */ - public static final int SherlockActionBar_icon = 10; - /** -

- @attr description - Specifies a style resource to use for an indeterminate progress spinner. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:indeterminateProgressStyle - */ - public static final int SherlockActionBar_indeterminateProgressStyle = 16; - /** -

- @attr description - Specifies padding that should be applied to the left and right sides of - system-provided items in the bar. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:itemPadding - */ - public static final int SherlockActionBar_itemPadding = 18; - /** -

- @attr description - Specifies the drawable used for the application logo. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:logo - */ - public static final int SherlockActionBar_logo = 11; - /** -

- @attr description - The type of navigation to use. - - -

Must be one of the following constant values.

- ---- - - - -
ConstantValueDescription
normal0 Normal static title text
listMode1 The action bar will use a selection list for navigation.
tabMode2 The action bar will use a series of horizontal tabs for navigation.
-

This is a private symbol. - @attr name android:navigationMode - */ - public static final int SherlockActionBar_navigationMode = 6; - /** -

- @attr description - Specifies the horizontal padding on either end for an embedded progress bar. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:progressBarPadding - */ - public static final int SherlockActionBar_progressBarPadding = 17; - /** -

- @attr description - Specifies a style resource to use for an embedded progress bar. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:progressBarStyle - */ - public static final int SherlockActionBar_progressBarStyle = 15; - /** -

- @attr description - Specifies subtitle text used for navigationMode="normal" - - -

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:subtitle - */ - public static final int SherlockActionBar_subtitle = 9; - /** -

- @attr description - Specifies a style to use for subtitle text. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:subtitleTextStyle - */ - public static final int SherlockActionBar_subtitleTextStyle = 1; - /** -

- @attr description - Specifies title text used for navigationMode="normal" - - -

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:title - */ - public static final int SherlockActionBar_title = 8; - /** -

- @attr description - Specifies a style to use for title text. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:titleTextStyle - */ - public static final int SherlockActionBar_titleTextStyle = 0; - /** Attributes that can be used with a SherlockActionMenuItemView. -

Includes the following attributes:

- - - - - -
AttributeDescription
{@link #SherlockActionMenuItemView_android_minWidth com.actionbarsherlock:android_minWidth}
- @see #SherlockActionMenuItemView_android_minWidth - */ - public static final int[] SherlockActionMenuItemView = { - 0x0101013f - }; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#android_minWidth} - attribute's value can be found in the {@link #SherlockActionMenuItemView} array. - @attr name android:android_minWidth - */ - public static final int SherlockActionMenuItemView_android_minWidth = 0; - /** Attributes that can be used with a SherlockActionMode. -

Includes the following attributes:

- - - - - - - - - -
AttributeDescription
{@link #SherlockActionMode_background com.actionbarsherlock:background} Specifies a background for the action mode bar.
{@link #SherlockActionMode_backgroundSplit com.actionbarsherlock:backgroundSplit} Specifies a background for the split action mode bar.
{@link #SherlockActionMode_height com.actionbarsherlock:height} Specifies a fixed height for the action mode bar.
{@link #SherlockActionMode_subtitleTextStyle com.actionbarsherlock:subtitleTextStyle} Specifies a style to use for subtitle text.
{@link #SherlockActionMode_titleTextStyle com.actionbarsherlock:titleTextStyle} Specifies a style to use for title text.
- @see #SherlockActionMode_background - @see #SherlockActionMode_backgroundSplit - @see #SherlockActionMode_height - @see #SherlockActionMode_subtitleTextStyle - @see #SherlockActionMode_titleTextStyle - */ - public static final int[] SherlockActionMode = { - 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, - 0x7f010004 - }; - /** -

- @attr description - Specifies a background for the action mode bar. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:background - */ - public static final int SherlockActionMode_background = 2; - /** -

- @attr description - Specifies a background for the split action mode bar. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:backgroundSplit - */ - public static final int SherlockActionMode_backgroundSplit = 3; - /** -

- @attr description - Specifies a fixed height for the action mode bar. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:height - */ - public static final int SherlockActionMode_height = 4; - /** -

- @attr description - Specifies a style to use for subtitle text. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:subtitleTextStyle - */ - public static final int SherlockActionMode_subtitleTextStyle = 1; - /** -

- @attr description - Specifies a style to use for title text. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:titleTextStyle - */ - public static final int SherlockActionMode_titleTextStyle = 0; - /** Attributes that can be used with a SherlockActivityChooserView. -

Includes the following attributes:

- - - - - - - -
AttributeDescription
{@link #SherlockActivityChooserView_android_background com.actionbarsherlock:android_background}
{@link #SherlockActivityChooserView_expandActivityOverflowButtonDrawable com.actionbarsherlock:expandActivityOverflowButtonDrawable} The drawable to show in the button for expanding the activities overflow popup.
{@link #SherlockActivityChooserView_initialActivityCount com.actionbarsherlock:initialActivityCount} The maximal number of items initially shown in the activity list.
- @see #SherlockActivityChooserView_android_background - @see #SherlockActivityChooserView_expandActivityOverflowButtonDrawable - @see #SherlockActivityChooserView_initialActivityCount - */ - public static final int[] SherlockActivityChooserView = { - 0x010100d4, 0x7f01004f, 0x7f010050 - }; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#android_background} - attribute's value can be found in the {@link #SherlockActivityChooserView} array. - @attr name android:android_background - */ - public static final int SherlockActivityChooserView_android_background = 0; - /** -

- @attr description - The drawable to show in the button for expanding the activities overflow popup. - Note: Clients would like to set this drawable - as a clue about the action the chosen activity will perform. For - example, if share activity is to be chosen the drawable should - give a clue that sharing is to be performed. - - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:expandActivityOverflowButtonDrawable - */ - public static final int SherlockActivityChooserView_expandActivityOverflowButtonDrawable = 2; - /** -

- @attr description - The maximal number of items initially shown in the activity list. - - -

Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character. -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:initialActivityCount - */ - public static final int SherlockActivityChooserView_initialActivityCount = 1; - /** Base attributes that are available to all groups. -

Includes the following attributes:

- - - - - - - - - - -
AttributeDescription
{@link #SherlockMenuGroup_android_checkableBehavior com.actionbarsherlock:android_checkableBehavior} Whether the items are capable of displaying a check mark.
{@link #SherlockMenuGroup_android_enabled com.actionbarsherlock:android_enabled} Whether the items are enabled.
{@link #SherlockMenuGroup_android_id com.actionbarsherlock:android_id} The ID of the group.
{@link #SherlockMenuGroup_android_menuCategory com.actionbarsherlock:android_menuCategory} The category applied to all items within this group.
{@link #SherlockMenuGroup_android_orderInCategory com.actionbarsherlock:android_orderInCategory} The order within the category applied to all items within this group.
{@link #SherlockMenuGroup_android_visible com.actionbarsherlock:android_visible} Whether the items are shown/visible.
- @see #SherlockMenuGroup_android_checkableBehavior - @see #SherlockMenuGroup_android_enabled - @see #SherlockMenuGroup_android_id - @see #SherlockMenuGroup_android_menuCategory - @see #SherlockMenuGroup_android_orderInCategory - @see #SherlockMenuGroup_android_visible - */ - public static final int[] SherlockMenuGroup = { - 0x0101000e, 0x010100d0, 0x01010194, 0x010101de, - 0x010101df, 0x010101e0 - }; - /** -

- @attr description - Whether the items are capable of displaying a check mark. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_checkableBehavior}. - @attr name android:android_checkableBehavior - */ - public static final int SherlockMenuGroup_android_checkableBehavior = 5; - /** -

- @attr description - Whether the items are enabled. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_enabled}. - @attr name android:android_enabled - */ - public static final int SherlockMenuGroup_android_enabled = 0; - /** -

- @attr description - The ID of the group. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_id}. - @attr name android:android_id - */ - public static final int SherlockMenuGroup_android_id = 1; - /** -

- @attr description - The category applied to all items within this group. - (This will be or'ed with the orderInCategory attribute.) -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_menuCategory}. - @attr name android:android_menuCategory - */ - public static final int SherlockMenuGroup_android_menuCategory = 3; - /** -

- @attr description - The order within the category applied to all items within this group. - (This will be or'ed with the category attribute.) -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_orderInCategory}. - @attr name android:android_orderInCategory - */ - public static final int SherlockMenuGroup_android_orderInCategory = 4; - /** -

- @attr description - Whether the items are shown/visible. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_visible}. - @attr name android:android_visible - */ - public static final int SherlockMenuGroup_android_visible = 2; - /** Base attributes that are available to all Item objects. -

Includes the following attributes:

- - - - - - - - - - - - - - - - - - - - - -
AttributeDescription
{@link #SherlockMenuItem_android_actionLayout com.actionbarsherlock:android_actionLayout} An optional layout to be used as an action view.
{@link #SherlockMenuItem_android_actionProviderClass com.actionbarsherlock:android_actionProviderClass} The name of an optional ActionProvider class to instantiate an action view - and perform operations such as default action for that menu item.
{@link #SherlockMenuItem_android_actionViewClass com.actionbarsherlock:android_actionViewClass} The name of an optional View class to instantiate and use as an - action view.
{@link #SherlockMenuItem_android_alphabeticShortcut com.actionbarsherlock:android_alphabeticShortcut} The alphabetic shortcut key.
{@link #SherlockMenuItem_android_checkable com.actionbarsherlock:android_checkable} Whether the item is capable of displaying a check mark.
{@link #SherlockMenuItem_android_checked com.actionbarsherlock:android_checked} Whether the item is checked.
{@link #SherlockMenuItem_android_enabled com.actionbarsherlock:android_enabled} Whether the item is enabled.
{@link #SherlockMenuItem_android_icon com.actionbarsherlock:android_icon} The icon associated with this item.
{@link #SherlockMenuItem_android_id com.actionbarsherlock:android_id} The ID of the item.
{@link #SherlockMenuItem_android_menuCategory com.actionbarsherlock:android_menuCategory} The category applied to the item.
{@link #SherlockMenuItem_android_numericShortcut com.actionbarsherlock:android_numericShortcut} The numeric shortcut key.
{@link #SherlockMenuItem_android_onClick com.actionbarsherlock:android_onClick} Name of a method on the Context used to inflate the menu that will be - called when the item is clicked.
{@link #SherlockMenuItem_android_orderInCategory com.actionbarsherlock:android_orderInCategory} The order within the category applied to the item.
{@link #SherlockMenuItem_android_showAsAction com.actionbarsherlock:android_showAsAction} How this item should display in the Action Bar, if present.
{@link #SherlockMenuItem_android_title com.actionbarsherlock:android_title} The title associated with the item.
{@link #SherlockMenuItem_android_titleCondensed com.actionbarsherlock:android_titleCondensed} The condensed title associated with the item.
{@link #SherlockMenuItem_android_visible com.actionbarsherlock:android_visible} Whether the item is shown/visible.
- @see #SherlockMenuItem_android_actionLayout - @see #SherlockMenuItem_android_actionProviderClass - @see #SherlockMenuItem_android_actionViewClass - @see #SherlockMenuItem_android_alphabeticShortcut - @see #SherlockMenuItem_android_checkable - @see #SherlockMenuItem_android_checked - @see #SherlockMenuItem_android_enabled - @see #SherlockMenuItem_android_icon - @see #SherlockMenuItem_android_id - @see #SherlockMenuItem_android_menuCategory - @see #SherlockMenuItem_android_numericShortcut - @see #SherlockMenuItem_android_onClick - @see #SherlockMenuItem_android_orderInCategory - @see #SherlockMenuItem_android_showAsAction - @see #SherlockMenuItem_android_title - @see #SherlockMenuItem_android_titleCondensed - @see #SherlockMenuItem_android_visible - */ - public static final int[] SherlockMenuItem = { - 0x01010002, 0x0101000e, 0x010100d0, 0x01010106, - 0x01010194, 0x010101de, 0x010101df, 0x010101e1, - 0x010101e2, 0x010101e3, 0x010101e4, 0x010101e5, - 0x0101026f, 0x010102d9, 0x010102fb, 0x010102fc, - 0x01010389 - }; - /** -

- @attr description - An optional layout to be used as an action view. - See {@link android.view.MenuItem#setActionView(android.view.View)} - for more info. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_actionLayout}. - @attr name android:android_actionLayout - */ - public static final int SherlockMenuItem_android_actionLayout = 14; - /** -

- @attr description - The name of an optional ActionProvider class to instantiate an action view - and perform operations such as default action for that menu item. - See {@link android.view.MenuItem#setActionProvider(android.view.ActionProvider)} - for more info. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_actionProviderClass}. - @attr name android:android_actionProviderClass - */ - public static final int SherlockMenuItem_android_actionProviderClass = 16; - /** -

- @attr description - The name of an optional View class to instantiate and use as an - action view. See {@link android.view.MenuItem#setActionView(android.view.View)} - for more info. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_actionViewClass}. - @attr name android:android_actionViewClass - */ - public static final int SherlockMenuItem_android_actionViewClass = 15; - /** -

- @attr description - The alphabetic shortcut key. This is the shortcut when using a keyboard - with alphabetic keys. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_alphabeticShortcut}. - @attr name android:android_alphabeticShortcut - */ - public static final int SherlockMenuItem_android_alphabeticShortcut = 9; - /** -

- @attr description - Whether the item is capable of displaying a check mark. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_checkable}. - @attr name android:android_checkable - */ - public static final int SherlockMenuItem_android_checkable = 11; - /** -

- @attr description - Whether the item is checked. Note that you must first have enabled checking with - the checkable attribute or else the check mark will not appear. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_checked}. - @attr name android:android_checked - */ - public static final int SherlockMenuItem_android_checked = 3; - /** -

- @attr description - Whether the item is enabled. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_enabled}. - @attr name android:android_enabled - */ - public static final int SherlockMenuItem_android_enabled = 1; - /** -

- @attr description - The icon associated with this item. This icon will not always be shown, so - the title should be sufficient in describing this item. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_icon}. - @attr name android:android_icon - */ - public static final int SherlockMenuItem_android_icon = 0; - /** -

- @attr description - The ID of the item. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_id}. - @attr name android:android_id - */ - public static final int SherlockMenuItem_android_id = 2; - /** -

- @attr description - The category applied to the item. - (This will be or'ed with the orderInCategory attribute.) -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_menuCategory}. - @attr name android:android_menuCategory - */ - public static final int SherlockMenuItem_android_menuCategory = 5; - /** -

- @attr description - The numeric shortcut key. This is the shortcut when using a numeric (e.g., 12-key) - keyboard. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_numericShortcut}. - @attr name android:android_numericShortcut - */ - public static final int SherlockMenuItem_android_numericShortcut = 10; - /** -

- @attr description - Name of a method on the Context used to inflate the menu that will be - called when the item is clicked. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_onClick}. - @attr name android:android_onClick - */ - public static final int SherlockMenuItem_android_onClick = 12; - /** -

- @attr description - The order within the category applied to the item. - (This will be or'ed with the category attribute.) -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_orderInCategory}. - @attr name android:android_orderInCategory - */ - public static final int SherlockMenuItem_android_orderInCategory = 6; - /** -

- @attr description - How this item should display in the Action Bar, if present. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_showAsAction}. - @attr name android:android_showAsAction - */ - public static final int SherlockMenuItem_android_showAsAction = 13; - /** -

- @attr description - The title associated with the item. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_title}. - @attr name android:android_title - */ - public static final int SherlockMenuItem_android_title = 7; - /** -

- @attr description - The condensed title associated with the item. This is used in situations where the - normal title may be too long to be displayed. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_titleCondensed}. - @attr name android:android_titleCondensed - */ - public static final int SherlockMenuItem_android_titleCondensed = 8; - /** -

- @attr description - Whether the item is shown/visible. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_visible}. - @attr name android:android_visible - */ - public static final int SherlockMenuItem_android_visible = 4; - /** Attributes that can be used with a SherlockMenuView. -

Includes the following attributes:

- - - - - - - - - - - - -
AttributeDescription
{@link #SherlockMenuView_headerBackground com.actionbarsherlock:headerBackground} Default background for the menu header.
{@link #SherlockMenuView_horizontalDivider com.actionbarsherlock:horizontalDivider} Default horizontal divider between rows of menu items.
{@link #SherlockMenuView_itemBackground com.actionbarsherlock:itemBackground} Default background for each menu item.
{@link #SherlockMenuView_itemIconDisabledAlpha com.actionbarsherlock:itemIconDisabledAlpha} Default disabled icon alpha for each menu item that shows an icon.
{@link #SherlockMenuView_itemTextAppearance com.actionbarsherlock:itemTextAppearance} Default appearance of menu item text.
{@link #SherlockMenuView_preserveIconSpacing com.actionbarsherlock:preserveIconSpacing} Whether space should be reserved in layout when an icon is missing.
{@link #SherlockMenuView_verticalDivider com.actionbarsherlock:verticalDivider} Default vertical divider between menu items.
{@link #SherlockMenuView_windowAnimationStyle com.actionbarsherlock:windowAnimationStyle} Default animations for the menu.
- @see #SherlockMenuView_headerBackground - @see #SherlockMenuView_horizontalDivider - @see #SherlockMenuView_itemBackground - @see #SherlockMenuView_itemIconDisabledAlpha - @see #SherlockMenuView_itemTextAppearance - @see #SherlockMenuView_preserveIconSpacing - @see #SherlockMenuView_verticalDivider - @see #SherlockMenuView_windowAnimationStyle - */ - public static final int[] SherlockMenuView = { - 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, - 0x7f01004b, 0x7f01004c, 0x7f01004d, 0x7f01004e - }; - /** -

- @attr description - Default background for the menu header. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:headerBackground - */ - public static final int SherlockMenuView_headerBackground = 3; - /** -

- @attr description - Default horizontal divider between rows of menu items. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:horizontalDivider - */ - public static final int SherlockMenuView_horizontalDivider = 1; - /** -

- @attr description - Default background for each menu item. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:itemBackground - */ - public static final int SherlockMenuView_itemBackground = 4; - /** -

- @attr description - Default disabled icon alpha for each menu item that shows an icon. - - -

Must be a floating point value, such as "1.2". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:itemIconDisabledAlpha - */ - public static final int SherlockMenuView_itemIconDisabledAlpha = 6; - /** -

- @attr description - Default appearance of menu item text. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:itemTextAppearance - */ - public static final int SherlockMenuView_itemTextAppearance = 0; - /** -

- @attr description - Whether space should be reserved in layout when an icon is missing. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:preserveIconSpacing - */ - public static final int SherlockMenuView_preserveIconSpacing = 7; - /** -

- @attr description - Default vertical divider between menu items. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:verticalDivider - */ - public static final int SherlockMenuView_verticalDivider = 2; - /** -

- @attr description - Default animations for the menu. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:windowAnimationStyle - */ - public static final int SherlockMenuView_windowAnimationStyle = 5; - /** Attributes that can be used with a SherlockSpinner. -

Includes the following attributes:

- - - - - - - - - - - - -
AttributeDescription
{@link #SherlockSpinner_android_dropDownHorizontalOffset com.actionbarsherlock:android_dropDownHorizontalOffset} Horizontal offset from the spinner widget for positioning the dropdown - in spinnerMode="dropdown".
{@link #SherlockSpinner_android_dropDownSelector com.actionbarsherlock:android_dropDownSelector} List selector to use for spinnerMode="dropdown" display.
{@link #SherlockSpinner_android_dropDownVerticalOffset com.actionbarsherlock:android_dropDownVerticalOffset} Vertical offset from the spinner widget for positioning the dropdown in - spinnerMode="dropdown".
{@link #SherlockSpinner_android_dropDownWidth com.actionbarsherlock:android_dropDownWidth} Width of the dropdown in spinnerMode="dropdown".
{@link #SherlockSpinner_android_gravity com.actionbarsherlock:android_gravity} Gravity setting for positioning the currently selected item.
{@link #SherlockSpinner_android_popupBackground com.actionbarsherlock:android_popupBackground} Background drawable to use for the dropdown in spinnerMode="dropdown".
{@link #SherlockSpinner_android_popupPromptView com.actionbarsherlock:android_popupPromptView} Reference to a layout to use for displaying a prompt in the dropdown for - spinnerMode="dropdown".
{@link #SherlockSpinner_android_prompt com.actionbarsherlock:android_prompt} The prompt to display when the spinner's dialog is shown.
- @see #SherlockSpinner_android_dropDownHorizontalOffset - @see #SherlockSpinner_android_dropDownSelector - @see #SherlockSpinner_android_dropDownVerticalOffset - @see #SherlockSpinner_android_dropDownWidth - @see #SherlockSpinner_android_gravity - @see #SherlockSpinner_android_popupBackground - @see #SherlockSpinner_android_popupPromptView - @see #SherlockSpinner_android_prompt - */ - public static final int[] SherlockSpinner = { - 0x010100af, 0x01010175, 0x01010176, 0x0101017b, - 0x01010262, 0x010102ac, 0x010102ad, 0x010103ef - }; - /** -

- @attr description - Horizontal offset from the spinner widget for positioning the dropdown - in spinnerMode="dropdown". -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_dropDownHorizontalOffset}. - @attr name android:android_dropDownHorizontalOffset - */ - public static final int SherlockSpinner_android_dropDownHorizontalOffset = 5; - /** -

- @attr description - List selector to use for spinnerMode="dropdown" display. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_dropDownSelector}. - @attr name android:android_dropDownSelector - */ - public static final int SherlockSpinner_android_dropDownSelector = 1; - /** -

- @attr description - Vertical offset from the spinner widget for positioning the dropdown in - spinnerMode="dropdown". -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_dropDownVerticalOffset}. - @attr name android:android_dropDownVerticalOffset - */ - public static final int SherlockSpinner_android_dropDownVerticalOffset = 6; - /** -

- @attr description - Width of the dropdown in spinnerMode="dropdown". -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_dropDownWidth}. - @attr name android:android_dropDownWidth - */ - public static final int SherlockSpinner_android_dropDownWidth = 4; - /** -

- @attr description - Gravity setting for positioning the currently selected item. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_gravity}. - @attr name android:android_gravity - */ - public static final int SherlockSpinner_android_gravity = 0; - /** -

- @attr description - Background drawable to use for the dropdown in spinnerMode="dropdown". -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_popupBackground}. - @attr name android:android_popupBackground - */ - public static final int SherlockSpinner_android_popupBackground = 2; - /** -

- @attr description - Reference to a layout to use for displaying a prompt in the dropdown for - spinnerMode="dropdown". This layout must contain a TextView with the id - @android:id/text1 to be populated with the prompt text. -

This is a private symbol. - @attr name android:android_popupPromptView - */ - public static final int SherlockSpinner_android_popupPromptView = 7; - /** -

- @attr description - The prompt to display when the spinner's dialog is shown. -

This corresponds to the global attribute resource symbol {@link com.actionbarsherlock.R.attr#android_prompt}. - @attr name android:android_prompt - */ - public static final int SherlockSpinner_android_prompt = 3; - /** Attributes that can be used with a SherlockTheme. -

Includes the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AttributeDescription
{@link #SherlockTheme_absForceOverflow com.actionbarsherlock:absForceOverflow} Specified if we are forcing an action item overflow menu.
{@link #SherlockTheme_actionBarDivider com.actionbarsherlock:actionBarDivider} Custom divider drawable to use for elements in the action bar.
{@link #SherlockTheme_actionBarItemBackground com.actionbarsherlock:actionBarItemBackground} Custom item state list drawable background for action bar items.
{@link #SherlockTheme_actionBarSize com.actionbarsherlock:actionBarSize} Size of the Action Bar, including the contextual - bar used to present Action Modes.
{@link #SherlockTheme_actionBarSplitStyle com.actionbarsherlock:actionBarSplitStyle} Reference to a style for the split Action Bar.
{@link #SherlockTheme_actionBarStyle com.actionbarsherlock:actionBarStyle} Reference to a style for the Action Bar
{@link #SherlockTheme_actionBarTabBarStyle com.actionbarsherlock:actionBarTabBarStyle}
{@link #SherlockTheme_actionBarTabStyle com.actionbarsherlock:actionBarTabStyle} Default style for tabs within an action bar
{@link #SherlockTheme_actionBarTabTextStyle com.actionbarsherlock:actionBarTabTextStyle}
{@link #SherlockTheme_actionBarWidgetTheme com.actionbarsherlock:actionBarWidgetTheme} Reference to a theme that should be used to inflate widgets - and layouts destined for the action bar.
{@link #SherlockTheme_actionButtonStyle com.actionbarsherlock:actionButtonStyle}
{@link #SherlockTheme_actionDropDownStyle com.actionbarsherlock:actionDropDownStyle}
{@link #SherlockTheme_actionMenuTextAppearance com.actionbarsherlock:actionMenuTextAppearance} TextAppearance style that will be applied to text that - appears within action menu items.
{@link #SherlockTheme_actionMenuTextColor com.actionbarsherlock:actionMenuTextColor} Color for text that appears within action menu items.
{@link #SherlockTheme_actionModeBackground com.actionbarsherlock:actionModeBackground} Background drawable to use for action mode UI
{@link #SherlockTheme_actionModeCloseButtonStyle com.actionbarsherlock:actionModeCloseButtonStyle}
{@link #SherlockTheme_actionModeCloseDrawable com.actionbarsherlock:actionModeCloseDrawable} Drawable to use for the close action mode button
{@link #SherlockTheme_actionModePopupWindowStyle com.actionbarsherlock:actionModePopupWindowStyle} PopupWindow style to use for action modes when showing as a window overlay.
{@link #SherlockTheme_actionModeShareDrawable com.actionbarsherlock:actionModeShareDrawable} Drawable to use for the Share action button in WebView selection action modes
{@link #SherlockTheme_actionModeSplitBackground com.actionbarsherlock:actionModeSplitBackground} Background drawable to use for action mode UI in the lower split bar
{@link #SherlockTheme_actionModeStyle com.actionbarsherlock:actionModeStyle}
{@link #SherlockTheme_actionOverflowButtonStyle com.actionbarsherlock:actionOverflowButtonStyle}
{@link #SherlockTheme_actionSpinnerItemStyle com.actionbarsherlock:actionSpinnerItemStyle}
{@link #SherlockTheme_activatedBackgroundIndicator com.actionbarsherlock:activatedBackgroundIndicator} Drawable used as a background for activated items.
{@link #SherlockTheme_activityChooserViewStyle com.actionbarsherlock:activityChooserViewStyle} Default ActivityChooserView style.
{@link #SherlockTheme_android_windowIsFloating com.actionbarsherlock:android_windowIsFloating}
{@link #SherlockTheme_buttonStyleSmall com.actionbarsherlock:buttonStyleSmall} Small Button style.
{@link #SherlockTheme_dividerVertical com.actionbarsherlock:dividerVertical} Drawable to use for generic vertical dividers.
{@link #SherlockTheme_dropDownListViewStyle com.actionbarsherlock:dropDownListViewStyle}
{@link #SherlockTheme_dropdownListPreferredItemHeight com.actionbarsherlock:dropdownListPreferredItemHeight}
{@link #SherlockTheme_homeAsUpIndicator com.actionbarsherlock:homeAsUpIndicator}
{@link #SherlockTheme_listPopupWindowStyle com.actionbarsherlock:listPopupWindowStyle}
{@link #SherlockTheme_listPreferredItemHeightSmall com.actionbarsherlock:listPreferredItemHeightSmall} A smaller, sleeker list item height.
{@link #SherlockTheme_listPreferredItemPaddingLeft com.actionbarsherlock:listPreferredItemPaddingLeft} The preferred padding along the left edge of list items.
{@link #SherlockTheme_listPreferredItemPaddingRight com.actionbarsherlock:listPreferredItemPaddingRight} The preferred padding along the right edge of list items.
{@link #SherlockTheme_popupMenuStyle com.actionbarsherlock:popupMenuStyle}
{@link #SherlockTheme_spinnerDropDownItemStyle com.actionbarsherlock:spinnerDropDownItemStyle}
{@link #SherlockTheme_spinnerItemStyle com.actionbarsherlock:spinnerItemStyle}
{@link #SherlockTheme_textAppearanceLargePopupMenu com.actionbarsherlock:textAppearanceLargePopupMenu} Text color, typeface, size, and style for the text inside of a popup menu.
{@link #SherlockTheme_textAppearanceListItemSmall com.actionbarsherlock:textAppearanceListItemSmall} The preferred TextAppearance for the primary text of small list items.
{@link #SherlockTheme_textAppearanceSmall com.actionbarsherlock:textAppearanceSmall} Text color, typeface, size, and style for "small" text.
{@link #SherlockTheme_textAppearanceSmallPopupMenu com.actionbarsherlock:textAppearanceSmallPopupMenu} Text color, typeface, size, and style for small text inside of a popup menu.
{@link #SherlockTheme_textColorPrimary com.actionbarsherlock:textColorPrimary}
{@link #SherlockTheme_textColorPrimaryDisableOnly com.actionbarsherlock:textColorPrimaryDisableOnly}
{@link #SherlockTheme_textColorPrimaryInverse com.actionbarsherlock:textColorPrimaryInverse}
{@link #SherlockTheme_windowActionBar com.actionbarsherlock:windowActionBar}
{@link #SherlockTheme_windowActionBarOverlay com.actionbarsherlock:windowActionBarOverlay}
{@link #SherlockTheme_windowActionModeOverlay com.actionbarsherlock:windowActionModeOverlay}
{@link #SherlockTheme_windowContentOverlay com.actionbarsherlock:windowContentOverlay} This Drawable is overlaid over the foreground of the Window's content area, usually - to place a shadow below the title.
{@link #SherlockTheme_windowMinWidthMajor com.actionbarsherlock:windowMinWidthMajor}
{@link #SherlockTheme_windowMinWidthMinor com.actionbarsherlock:windowMinWidthMinor}
{@link #SherlockTheme_windowNoTitle com.actionbarsherlock:windowNoTitle}
{@link #SherlockTheme_windowSplitActionBar com.actionbarsherlock:windowSplitActionBar}
- @see #SherlockTheme_absForceOverflow - @see #SherlockTheme_actionBarDivider - @see #SherlockTheme_actionBarItemBackground - @see #SherlockTheme_actionBarSize - @see #SherlockTheme_actionBarSplitStyle - @see #SherlockTheme_actionBarStyle - @see #SherlockTheme_actionBarTabBarStyle - @see #SherlockTheme_actionBarTabStyle - @see #SherlockTheme_actionBarTabTextStyle - @see #SherlockTheme_actionBarWidgetTheme - @see #SherlockTheme_actionButtonStyle - @see #SherlockTheme_actionDropDownStyle - @see #SherlockTheme_actionMenuTextAppearance - @see #SherlockTheme_actionMenuTextColor - @see #SherlockTheme_actionModeBackground - @see #SherlockTheme_actionModeCloseButtonStyle - @see #SherlockTheme_actionModeCloseDrawable - @see #SherlockTheme_actionModePopupWindowStyle - @see #SherlockTheme_actionModeShareDrawable - @see #SherlockTheme_actionModeSplitBackground - @see #SherlockTheme_actionModeStyle - @see #SherlockTheme_actionOverflowButtonStyle - @see #SherlockTheme_actionSpinnerItemStyle - @see #SherlockTheme_activatedBackgroundIndicator - @see #SherlockTheme_activityChooserViewStyle - @see #SherlockTheme_android_windowIsFloating - @see #SherlockTheme_buttonStyleSmall - @see #SherlockTheme_dividerVertical - @see #SherlockTheme_dropDownListViewStyle - @see #SherlockTheme_dropdownListPreferredItemHeight - @see #SherlockTheme_homeAsUpIndicator - @see #SherlockTheme_listPopupWindowStyle - @see #SherlockTheme_listPreferredItemHeightSmall - @see #SherlockTheme_listPreferredItemPaddingLeft - @see #SherlockTheme_listPreferredItemPaddingRight - @see #SherlockTheme_popupMenuStyle - @see #SherlockTheme_spinnerDropDownItemStyle - @see #SherlockTheme_spinnerItemStyle - @see #SherlockTheme_textAppearanceLargePopupMenu - @see #SherlockTheme_textAppearanceListItemSmall - @see #SherlockTheme_textAppearanceSmall - @see #SherlockTheme_textAppearanceSmallPopupMenu - @see #SherlockTheme_textColorPrimary - @see #SherlockTheme_textColorPrimaryDisableOnly - @see #SherlockTheme_textColorPrimaryInverse - @see #SherlockTheme_windowActionBar - @see #SherlockTheme_windowActionBarOverlay - @see #SherlockTheme_windowActionModeOverlay - @see #SherlockTheme_windowContentOverlay - @see #SherlockTheme_windowMinWidthMajor - @see #SherlockTheme_windowMinWidthMinor - @see #SherlockTheme_windowNoTitle - @see #SherlockTheme_windowSplitActionBar - */ - public static final int[] SherlockTheme = { - 0x01010057, 0x7f010006, 0x7f010007, 0x7f010008, - 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, - 0x7f01000d, 0x7f01000e, 0x7f01000f, 0x7f010010, - 0x7f010011, 0x7f010012, 0x7f010013, 0x7f010014, - 0x7f010015, 0x7f010016, 0x7f010017, 0x7f010018, - 0x7f010019, 0x7f01001a, 0x7f01001b, 0x7f01001c, - 0x7f01001d, 0x7f01001e, 0x7f01001f, 0x7f010020, - 0x7f010021, 0x7f010022, 0x7f010023, 0x7f010024, - 0x7f010025, 0x7f010026, 0x7f010027, 0x7f010028, - 0x7f010029, 0x7f01002a, 0x7f01002b, 0x7f01002c, - 0x7f01002d, 0x7f01002e, 0x7f01002f, 0x7f010030, - 0x7f010031, 0x7f010032, 0x7f010033, 0x7f010034, - 0x7f010035, 0x7f010036, 0x7f010037, 0x7f010038, - 0x7f010039 - }; - /** -

- @attr description - Specified if we are forcing an action item overflow menu. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:absForceOverflow - */ - public static final int SherlockTheme_absForceOverflow = 52; - /** -

- @attr description - Custom divider drawable to use for elements in the action bar. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionBarDivider - */ - public static final int SherlockTheme_actionBarDivider = 9; - /** -

- @attr description - Custom item state list drawable background for action bar items. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionBarItemBackground - */ - public static final int SherlockTheme_actionBarItemBackground = 10; - /** -

- @attr description - Size of the Action Bar, including the contextual - bar used to present Action Modes. - - -

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

May be one of the following constant values.

- ---- - -
ConstantValueDescription
wrap_content0
-

This is a private symbol. - @attr name android:actionBarSize - */ - public static final int SherlockTheme_actionBarSize = 8; - /** -

- @attr description - Reference to a style for the split Action Bar. This style - controls the split component that holds the menu/action - buttons. actionBarStyle is still used for the primary - bar. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionBarSplitStyle - */ - public static final int SherlockTheme_actionBarSplitStyle = 6; - /** -

- @attr description - Reference to a style for the Action Bar - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionBarStyle - */ - public static final int SherlockTheme_actionBarStyle = 5; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionBarTabBarStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionBarTabBarStyle - */ - public static final int SherlockTheme_actionBarTabBarStyle = 2; - /** -

- @attr description - Default style for tabs within an action bar - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionBarTabStyle - */ - public static final int SherlockTheme_actionBarTabStyle = 1; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionBarTabTextStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionBarTabTextStyle - */ - public static final int SherlockTheme_actionBarTabTextStyle = 3; - /** -

- @attr description - Reference to a theme that should be used to inflate widgets - and layouts destined for the action bar. Most of the time - this will be a reference to the current theme, but when - the action bar has a significantly different contrast - profile than the rest of the activity the difference - can become important. If this is set to @null the current - theme will be used. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionBarWidgetTheme - */ - public static final int SherlockTheme_actionBarWidgetTheme = 7; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionButtonStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionButtonStyle - */ - public static final int SherlockTheme_actionButtonStyle = 38; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionDropDownStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionDropDownStyle - */ - public static final int SherlockTheme_actionDropDownStyle = 37; - /** -

- @attr description - TextAppearance style that will be applied to text that - appears within action menu items. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionMenuTextAppearance - */ - public static final int SherlockTheme_actionMenuTextAppearance = 11; - /** -

- @attr description - Color for text that appears within action menu items. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This is a private symbol. - @attr name android:actionMenuTextColor - */ - public static final int SherlockTheme_actionMenuTextColor = 12; - /** -

- @attr description - Background drawable to use for action mode UI - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionModeBackground - */ - public static final int SherlockTheme_actionModeBackground = 15; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionModeCloseButtonStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionModeCloseButtonStyle - */ - public static final int SherlockTheme_actionModeCloseButtonStyle = 14; - /** -

- @attr description - Drawable to use for the close action mode button - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionModeCloseDrawable - */ - public static final int SherlockTheme_actionModeCloseDrawable = 17; - /** -

- @attr description - PopupWindow style to use for action modes when showing as a window overlay. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionModePopupWindowStyle - */ - public static final int SherlockTheme_actionModePopupWindowStyle = 19; - /** -

- @attr description - Drawable to use for the Share action button in WebView selection action modes - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionModeShareDrawable - */ - public static final int SherlockTheme_actionModeShareDrawable = 18; - /** -

- @attr description - Background drawable to use for action mode UI in the lower split bar - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:actionModeSplitBackground - */ - public static final int SherlockTheme_actionModeSplitBackground = 16; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionModeStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionModeStyle - */ - public static final int SherlockTheme_actionModeStyle = 13; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionOverflowButtonStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionOverflowButtonStyle - */ - public static final int SherlockTheme_actionOverflowButtonStyle = 4; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#actionSpinnerItemStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:actionSpinnerItemStyle - */ - public static final int SherlockTheme_actionSpinnerItemStyle = 43; - /** -

- @attr description - Drawable used as a background for activated items. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:activatedBackgroundIndicator - */ - public static final int SherlockTheme_activatedBackgroundIndicator = 51; - /** -

- @attr description - Default ActivityChooserView style. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:activityChooserViewStyle - */ - public static final int SherlockTheme_activityChooserViewStyle = 50; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#android_windowIsFloating} - attribute's value can be found in the {@link #SherlockTheme} array. - @attr name android:android_windowIsFloating - */ - public static final int SherlockTheme_android_windowIsFloating = 0; - /** -

- @attr description - Small Button style. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:buttonStyleSmall - */ - public static final int SherlockTheme_buttonStyleSmall = 20; - /** -

- @attr description - Drawable to use for generic vertical dividers. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:dividerVertical - */ - public static final int SherlockTheme_dividerVertical = 36; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#dropDownListViewStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:dropDownListViewStyle - */ - public static final int SherlockTheme_dropDownListViewStyle = 40; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#dropdownListPreferredItemHeight} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:dropdownListPreferredItemHeight - */ - public static final int SherlockTheme_dropdownListPreferredItemHeight = 42; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#homeAsUpIndicator} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:homeAsUpIndicator - */ - public static final int SherlockTheme_homeAsUpIndicator = 39; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#listPopupWindowStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:listPopupWindowStyle - */ - public static final int SherlockTheme_listPopupWindowStyle = 49; - /** -

- @attr description - A smaller, sleeker list item height. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:listPreferredItemHeightSmall - */ - public static final int SherlockTheme_listPreferredItemHeightSmall = 30; - /** -

- @attr description - The preferred padding along the left edge of list items. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:listPreferredItemPaddingLeft - */ - public static final int SherlockTheme_listPreferredItemPaddingLeft = 31; - /** -

- @attr description - The preferred padding along the right edge of list items. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. -

This is a private symbol. - @attr name android:listPreferredItemPaddingRight - */ - public static final int SherlockTheme_listPreferredItemPaddingRight = 32; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#popupMenuStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:popupMenuStyle - */ - public static final int SherlockTheme_popupMenuStyle = 41; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#spinnerDropDownItemStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:spinnerDropDownItemStyle - */ - public static final int SherlockTheme_spinnerDropDownItemStyle = 29; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#spinnerItemStyle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". - @attr name android:spinnerItemStyle - */ - public static final int SherlockTheme_spinnerItemStyle = 28; - /** -

- @attr description - Text color, typeface, size, and style for the text inside of a popup menu. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:textAppearanceLargePopupMenu - */ - public static final int SherlockTheme_textAppearanceLargePopupMenu = 22; - /** -

- @attr description - The preferred TextAppearance for the primary text of small list items. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:textAppearanceListItemSmall - */ - public static final int SherlockTheme_textAppearanceListItemSmall = 33; - /** -

- @attr description - Text color, typeface, size, and style for "small" text. Defaults to secondary text color. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:textAppearanceSmall - */ - public static final int SherlockTheme_textAppearanceSmall = 24; - /** -

- @attr description - Text color, typeface, size, and style for small text inside of a popup menu. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:textAppearanceSmallPopupMenu - */ - public static final int SherlockTheme_textAppearanceSmallPopupMenu = 23; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#textColorPrimary} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:textColorPrimary - */ - public static final int SherlockTheme_textColorPrimary = 25; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#textColorPrimaryDisableOnly} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:textColorPrimaryDisableOnly - */ - public static final int SherlockTheme_textColorPrimaryDisableOnly = 26; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#textColorPrimaryInverse} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:textColorPrimaryInverse - */ - public static final int SherlockTheme_textColorPrimaryInverse = 27; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowActionBar} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowActionBar - */ - public static final int SherlockTheme_windowActionBar = 45; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowActionBarOverlay} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowActionBarOverlay - */ - public static final int SherlockTheme_windowActionBarOverlay = 46; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowActionModeOverlay} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowActionModeOverlay - */ - public static final int SherlockTheme_windowActionModeOverlay = 47; - /** -

- @attr description - This Drawable is overlaid over the foreground of the Window's content area, usually - to place a shadow below the title. - - -

Must be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

This is a private symbol. - @attr name android:windowContentOverlay - */ - public static final int SherlockTheme_windowContentOverlay = 21; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowMinWidthMajor} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowMinWidthMajor - */ - public static final int SherlockTheme_windowMinWidthMajor = 34; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowMinWidthMinor} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowMinWidthMinor - */ - public static final int SherlockTheme_windowMinWidthMinor = 35; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowNoTitle} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowNoTitle - */ - public static final int SherlockTheme_windowNoTitle = 44; - /** -

This symbol is the offset where the {@link com.actionbarsherlock.R.attr#windowSplitActionBar} - attribute's value can be found in the {@link #SherlockTheme} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:windowSplitActionBar - */ - public static final int SherlockTheme_windowSplitActionBar = 48; - }; -} diff --git a/android-libraries/ActionBarSherlock/libs/android-support-v4.jar b/android-libraries/ActionBarSherlock/libs/android-support-v4.jar deleted file mode 100644 index 1fbeba09..00000000 Binary files a/android-libraries/ActionBarSherlock/libs/android-support-v4.jar and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/proguard-project.txt b/android-libraries/ActionBarSherlock/proguard-project.txt deleted file mode 100644 index f2fe1559..00000000 --- a/android-libraries/ActionBarSherlock/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/android-libraries/ActionBarSherlock/project.properties b/android-libraries/ActionBarSherlock/project.properties deleted file mode 100644 index f28bc833..00000000 --- a/android-libraries/ActionBarSherlock/project.properties +++ /dev/null @@ -1,12 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -android.library=true -# Project target. -target=android-15 diff --git a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_dark.xml b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_dark.xml deleted file mode 100644 index ea7459aa..00000000 --- a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_dark.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_light.xml b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_light.xml deleted file mode 100644 index 0edb33b4..00000000 --- a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_light.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_dark.xml b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_dark.xml deleted file mode 100644 index 2bcfd0b6..00000000 --- a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_dark.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_light.xml b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_light.xml deleted file mode 100644 index 198384fe..00000000 --- a/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_light.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png deleted file mode 100644 index 769463b3..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png deleted file mode 100644 index 88f11dcb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png deleted file mode 100644 index 73050476..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png deleted file mode 100644 index 712a551e..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png deleted file mode 100644 index bf3b9438..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png deleted file mode 100644 index 6c141577..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png deleted file mode 100644 index f4ff16be..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png deleted file mode 100644 index cbbaec58..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_light_holo.9.png deleted file mode 100644 index af917e5b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png deleted file mode 100644 index 2d59f354..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png deleted file mode 100644 index 0520e5a2..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png deleted file mode 100644 index e3e3f93b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png deleted file mode 100644 index 1e395722..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png deleted file mode 100644 index a16db853..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png deleted file mode 100644 index 0eff695d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png deleted file mode 100644 index 219b170f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png deleted file mode 100644 index b0dc31fb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png deleted file mode 100644 index 4bc2683b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png deleted file mode 100644 index 4af38fb7..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png deleted file mode 100644 index d32f74cf..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png deleted file mode 100644 index 66adffed..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png deleted file mode 100644 index caeff9c3..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png deleted file mode 100644 index 1d836f65..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png deleted file mode 100644 index 5818666d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png deleted file mode 100644 index 564fb34b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png deleted file mode 100644 index ae21b760..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png deleted file mode 100644 index 79e56f52..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_light.9.png deleted file mode 100644 index e029f210..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png deleted file mode 100644 index 897a1c11..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_light.png deleted file mode 100644 index 0c89f714..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png deleted file mode 100644 index d8662e3f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_light.png deleted file mode 100644 index ed03f620..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png deleted file mode 100644 index 2abc4580..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png deleted file mode 100644 index bb6aef1d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png deleted file mode 100644 index 6f747c8f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_light.png deleted file mode 100644 index 682b2fde..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_activated_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_activated_holo.9.png deleted file mode 100644 index 4ea7afa0..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_activated_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_dark.9.png deleted file mode 100644 index 986ab0b9..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_light.9.png deleted file mode 100644 index 0279e17a..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_focused_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_focused_holo.9.png deleted file mode 100644 index 516f5c73..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_longpressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_longpressed_holo.9.png deleted file mode 100644 index 4ea7afa0..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_longpressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png deleted file mode 100644 index 5654cd69..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_light.9.png deleted file mode 100644 index 5654cd69..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png deleted file mode 100644 index f6fd30dc..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png deleted file mode 100644 index ca8e9a27..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png deleted file mode 100644 index 4d3d2085..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png deleted file mode 100644 index 924a99d1..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png deleted file mode 100644 index 310c368e..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_light.9.png deleted file mode 100644 index 70cb7fc7..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png deleted file mode 100644 index 1c269205..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_light.9.png deleted file mode 100644 index 1c269205..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png deleted file mode 100644 index 40d0d164..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png deleted file mode 100644 index 40d0d164..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_inner_holo.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_inner_holo.png deleted file mode 100644 index c8358e9c..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_inner_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_outer_holo.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_outer_holo.png deleted file mode 100644 index f62f74bb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_outer_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png deleted file mode 100644 index eb28ff9a..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png deleted file mode 100644 index d281adb5..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png deleted file mode 100644 index b2985860..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png deleted file mode 100644 index 4215396d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png deleted file mode 100644 index a280eabf..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png deleted file mode 100644 index f8d619b4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png deleted file mode 100644 index 955a2f34..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png deleted file mode 100644 index 6c22e223..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png deleted file mode 100644 index 673e3bf1..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_holo.9.png deleted file mode 100644 index d57df98b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png deleted file mode 100644 index 6278eef4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png deleted file mode 100644 index aadc6f87..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/ic_launcher.png deleted file mode 100644 index 96a442e5..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-ldpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-ldpi/ic_launcher.png deleted file mode 100644 index 99238729..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png deleted file mode 100644 index b2293670..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png deleted file mode 100644 index c65f443e..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png deleted file mode 100644 index 0706c8af..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png deleted file mode 100644 index d814d02d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png deleted file mode 100644 index b139c8e4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png deleted file mode 100644 index ed4ba34e..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png deleted file mode 100644 index 8f10bd52..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png deleted file mode 100644 index 743d00b6..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_light_holo.9.png deleted file mode 100644 index 17c1fb92..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png deleted file mode 100644 index ddfc8e3d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png deleted file mode 100644 index 007a4b23..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png deleted file mode 100644 index ad6e1a4d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png deleted file mode 100644 index 0ad6c888..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png deleted file mode 100644 index 19b50abc..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png deleted file mode 100644 index ad980b13..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png deleted file mode 100644 index 60e6c527..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png deleted file mode 100644 index 5461b9c0..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png deleted file mode 100644 index 5dc6f804..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png deleted file mode 100644 index a70b53c5..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png deleted file mode 100644 index c7a9896b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png deleted file mode 100644 index 85d7aadd..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png deleted file mode 100644 index f7b01e01..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png deleted file mode 100644 index d8f1c8bd..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png deleted file mode 100644 index 31e49894..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png deleted file mode 100644 index 7c2cbe53..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png deleted file mode 100644 index 30cbdc17..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png deleted file mode 100644 index fb3660ea..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_light.9.png deleted file mode 100644 index f18050ea..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png deleted file mode 100644 index df2d3d15..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_light.png deleted file mode 100644 index b2aa9c26..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png deleted file mode 100644 index a17b6a78..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_light.png deleted file mode 100644 index b28b3b54..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png deleted file mode 100644 index ba704b67..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png deleted file mode 100644 index 01d68169..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png deleted file mode 100644 index 6bf21e30..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_light.png deleted file mode 100644 index 70fe31aa..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_activated_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_activated_holo.9.png deleted file mode 100644 index 3bf8e036..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_activated_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_dark.9.png deleted file mode 100644 index 986ab0b9..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_light.9.png deleted file mode 100644 index 0279e17a..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_focused_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_focused_holo.9.png deleted file mode 100644 index 7c0599e3..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_longpressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_longpressed_holo.9.png deleted file mode 100644 index 3bf8e036..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_longpressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png deleted file mode 100644 index 6e77525d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_light.9.png deleted file mode 100644 index 6e77525d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png deleted file mode 100644 index 92da2f0d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png deleted file mode 100644 index 42cb6463..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png deleted file mode 100644 index 460ec46e..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png deleted file mode 100644 index e84adf2d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png deleted file mode 100644 index 3d946e54..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_light.9.png deleted file mode 100644 index 4bb22f0e..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png deleted file mode 100644 index ab8ec698..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_light.9.png deleted file mode 100644 index ab8ec698..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png deleted file mode 100644 index 7274274b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png deleted file mode 100644 index 7274274b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_inner_holo.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_inner_holo.png deleted file mode 100644 index 9458668f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_inner_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_outer_holo.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_outer_holo.png deleted file mode 100644 index 4ce73edc..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_outer_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png deleted file mode 100644 index 29aff4d4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png deleted file mode 100644 index 4055f705..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png deleted file mode 100644 index ea4ee042..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png deleted file mode 100644 index f74c02b9..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png deleted file mode 100644 index 09a2992c..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png deleted file mode 100644 index 6536ee63..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png deleted file mode 100644 index 202b5b72..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png deleted file mode 100644 index 6de0ba88..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png deleted file mode 100644 index c9972e74..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_holo.9.png deleted file mode 100644 index 587337ca..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png deleted file mode 100644 index 155c4fc7..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png deleted file mode 100644 index b1223fe3..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/ic_launcher.png deleted file mode 100644 index 359047df..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-v11/abs__progress_medium_holo.xml b/android-libraries/ActionBarSherlock/res/drawable-v11/abs__progress_medium_holo.xml deleted file mode 100644 index 6bcbdb83..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable-v11/abs__progress_medium_holo.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png deleted file mode 100644 index 57533469..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png deleted file mode 100644 index 7e6c047d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png deleted file mode 100644 index 8155fe84..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png deleted file mode 100644 index 6cee9a12..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png deleted file mode 100644 index fa4d76af..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png deleted file mode 100644 index 55099d49..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png deleted file mode 100644 index 3c4701fc..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png deleted file mode 100644 index 6622cbad..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png deleted file mode 100644 index c4272978..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png deleted file mode 100644 index d0df29d8..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png deleted file mode 100644 index a0d9c1b9..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png deleted file mode 100644 index d36f99fe..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png deleted file mode 100644 index 5ad475dc..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png deleted file mode 100644 index 6ade5eeb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png deleted file mode 100644 index 719b9234..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png deleted file mode 100644 index 6da264db..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png deleted file mode 100644 index 7ef2db75..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png deleted file mode 100644 index 2283b4c0..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png deleted file mode 100644 index 6d2039e2..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png deleted file mode 100644 index 3c909b51..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png deleted file mode 100644 index 131d1030..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png deleted file mode 100644 index 3e7dcdfd..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png deleted file mode 100644 index 0bd09806..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png deleted file mode 100644 index 43ed26d4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png deleted file mode 100644 index 6b315798..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png deleted file mode 100644 index df0121bb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png deleted file mode 100644 index f4970ad1..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png deleted file mode 100644 index 172fc3b5..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png deleted file mode 100644 index 8ded62fb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png deleted file mode 100644 index 517e9f72..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png deleted file mode 100644 index 2e06dd01..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png deleted file mode 100644 index bb19810b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png deleted file mode 100644 index a92fb1d4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png deleted file mode 100644 index 930ca8d9..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png deleted file mode 100644 index 45a0f1da..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png deleted file mode 100644 index 528e554a..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_activated_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_activated_holo.9.png deleted file mode 100644 index eda10e61..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_activated_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png deleted file mode 100644 index e62f011d..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_light.9.png deleted file mode 100644 index 65061c0f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_focused_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_focused_holo.9.png deleted file mode 100644 index 690cb1eb..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_longpressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_longpressed_holo.9.png deleted file mode 100644 index eda10e61..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_longpressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png deleted file mode 100644 index e4b33935..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png deleted file mode 100644 index e4b33935..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png deleted file mode 100644 index 88726b69..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png deleted file mode 100644 index c6a7d4d8..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png deleted file mode 100644 index e2aff72f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png deleted file mode 100644 index 93066c84..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png deleted file mode 100644 index 345f5d30..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png deleted file mode 100644 index c843ef3a..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png deleted file mode 100644 index c6c3f1ec..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png deleted file mode 100644 index c6c3f1ec..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png deleted file mode 100644 index 205b66e2..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png deleted file mode 100644 index 205b66e2..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_inner_holo.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_inner_holo.png deleted file mode 100644 index 19517c4b..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_inner_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_outer_holo.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_outer_holo.png deleted file mode 100644 index 14143c51..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_outer_holo.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png deleted file mode 100644 index d8929fcd..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png deleted file mode 100644 index 9174c4e4..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png deleted file mode 100644 index 3015d307..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png deleted file mode 100644 index 126637d1..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png deleted file mode 100644 index d45c7a86..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png deleted file mode 100644 index 29036b90..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png deleted file mode 100644 index 2cb34d7f..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png deleted file mode 100644 index 82f752fd..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png deleted file mode 100644 index 03cfb094..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_holo.9.png deleted file mode 100644 index e4229f26..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png deleted file mode 100644 index e862cb12..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png deleted file mode 100644 index f1eb6732..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/ic_launcher.png deleted file mode 100644 index 71c6d760..00000000 Binary files a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_dark.xml deleted file mode 100644 index 85c2c021..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_dark.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_light.xml deleted file mode 100644 index 85c2c021..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_light.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_dark.xml deleted file mode 100644 index cab89628..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_dark.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_light.xml deleted file mode 100644 index 42ba8a0d..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_light.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_dark.xml deleted file mode 100644 index 2588a492..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_dark.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_light.xml deleted file mode 100644 index e2078c96..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_light.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_dark.xml deleted file mode 100644 index d99b7a42..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_dark.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_light.xml deleted file mode 100644 index da5fb2e8..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_light.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_dark.xml deleted file mode 100644 index b2ce4f0f..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_dark.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_light.xml deleted file mode 100644 index d7e31b1d..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_light.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_dark.xml deleted file mode 100644 index 08b8b12f..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_dark.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_light.xml deleted file mode 100644 index ada490bf..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_light.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_dark.xml deleted file mode 100644 index bd19140a..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_dark.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_light.xml deleted file mode 100644 index 321f07c8..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_light.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_medium_holo.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_medium_holo.xml deleted file mode 100644 index 6d4814f8..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_medium_holo.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_dark.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_dark.xml deleted file mode 100644 index 4af5e22a..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_dark.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_light.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_light.xml deleted file mode 100644 index b7850847..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_light.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__tab_indicator_ab_holo.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__tab_indicator_ab_holo.xml deleted file mode 100644 index d34e2081..00000000 --- a/android-libraries/ActionBarSherlock/res/drawable/abs__tab_indicator_ab_holo.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout-large/abs__action_mode_close_item.xml b/android-libraries/ActionBarSherlock/res/layout-large/abs__action_mode_close_item.xml deleted file mode 100644 index 8811dad8..00000000 --- a/android-libraries/ActionBarSherlock/res/layout-large/abs__action_mode_close_item.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_dropdown_item.xml b/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_dropdown_item.xml deleted file mode 100644 index 6c183c05..00000000 --- a/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_dropdown_item.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - diff --git a/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_item.xml b/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_item.xml deleted file mode 100644 index 61dc0252..00000000 --- a/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_item.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - diff --git a/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar.xml b/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar.xml deleted file mode 100644 index 040df44a..00000000 --- a/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar_overlay.xml b/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar_overlay.xml deleted file mode 100644 index c64ef141..00000000 --- a/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar_overlay.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_home.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_home.xml deleted file mode 100644 index 5c1e9ec4..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_home.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab.xml deleted file mode 100644 index f46f7a04..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab_bar_view.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab_bar_view.xml deleted file mode 100644 index 0d51220c..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab_bar_view.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_title_item.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_title_item.xml deleted file mode 100644 index dd69acad..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_title_item.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_item_layout.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_item_layout.xml deleted file mode 100644 index 13149fd6..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_item_layout.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_layout.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_layout.xml deleted file mode 100644 index a6f8e53f..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_layout.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_bar.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_bar.xml deleted file mode 100644 index 7168dc77..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_bar.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_close_item.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_close_item.xml deleted file mode 100644 index 875ec3e1..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_close_item.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view.xml b/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view.xml deleted file mode 100644 index 019d14ef..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view_list_item.xml b/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view_list_item.xml deleted file mode 100644 index b430032a..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view_list_item.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__dialog_title_holo.xml b/android-libraries/ActionBarSherlock/res/layout/abs__dialog_title_holo.xml deleted file mode 100644 index 6402f28b..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__dialog_title_holo.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_checkbox.xml b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_checkbox.xml deleted file mode 100644 index 39aca3a8..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_checkbox.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_icon.xml b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_icon.xml deleted file mode 100644 index 55ab28a2..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_icon.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_layout.xml b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_layout.xml deleted file mode 100644 index 147f36fe..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_layout.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_radio.xml b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_radio.xml deleted file mode 100644 index ff54bbec..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_radio.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__popup_menu_item_layout.xml b/android-libraries/ActionBarSherlock/res/layout/abs__popup_menu_item_layout.xml deleted file mode 100644 index d42425ad..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__popup_menu_item_layout.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar.xml b/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar.xml deleted file mode 100644 index 1fb82fe9..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar_overlay.xml b/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar_overlay.xml deleted file mode 100644 index 0961ef56..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar_overlay.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple.xml b/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple.xml deleted file mode 100644 index 33e2dea0..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple_overlay_action_mode.xml b/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple_overlay_action_mode.xml deleted file mode 100644 index f8b9fb18..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple_overlay_action_mode.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/main.xml b/android-libraries/ActionBarSherlock/res/layout/main.xml deleted file mode 100644 index ac9c0aba..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/main.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_dropdown_item.xml b/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_dropdown_item.xml deleted file mode 100644 index a6c6252d..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_dropdown_item.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - diff --git a/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_item.xml b/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_item.xml deleted file mode 100644 index bea74017..00000000 --- a/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_item.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - diff --git a/android-libraries/ActionBarSherlock/res/values-land/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-land/abs__dimens.xml deleted file mode 100644 index 502cc16a..00000000 --- a/android-libraries/ActionBarSherlock/res/values-land/abs__dimens.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - 40dip - - 4dip - - 16dp - - 12dp - - -2dp - - 4dip - diff --git a/android-libraries/ActionBarSherlock/res/values-large-hdpi-1024x600/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-large-hdpi-1024x600/abs__dimens.xml deleted file mode 100644 index 3312cfa7..00000000 --- a/android-libraries/ActionBarSherlock/res/values-large-hdpi-1024x600/abs__dimens.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - 48dip - - 8dip - - 18dp - - 14dp - - -3dp - - 5dip - diff --git a/android-libraries/ActionBarSherlock/res/values-large-land-hdpi-1024x600/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-large-land-hdpi-1024x600/abs__dimens.xml deleted file mode 100644 index 502cc16a..00000000 --- a/android-libraries/ActionBarSherlock/res/values-large-land-hdpi-1024x600/abs__dimens.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - 40dip - - 4dip - - 16dp - - 12dp - - -2dp - - 4dip - diff --git a/android-libraries/ActionBarSherlock/res/values-large-land-mdpi-1024x600/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-large-land-mdpi-1024x600/abs__dimens.xml deleted file mode 100644 index 3312cfa7..00000000 --- a/android-libraries/ActionBarSherlock/res/values-large-land-mdpi-1024x600/abs__dimens.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - 48dip - - 8dip - - 18dp - - 14dp - - -3dp - - 5dip - diff --git a/android-libraries/ActionBarSherlock/res/values-large-mdpi-1024x600/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-large-mdpi-1024x600/abs__dimens.xml deleted file mode 100644 index 35910333..00000000 --- a/android-libraries/ActionBarSherlock/res/values-large-mdpi-1024x600/abs__dimens.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - 56dip - - 4dip - - 18dp - - 14dp - - -3dp - - 9dip - - - 64dip - diff --git a/android-libraries/ActionBarSherlock/res/values-large/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-large/abs__dimens.xml deleted file mode 100644 index 63b12f7f..00000000 --- a/android-libraries/ActionBarSherlock/res/values-large/abs__dimens.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - 55% - - 80% - diff --git a/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__bools.xml b/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__bools.xml deleted file mode 100644 index 7a48e154..00000000 --- a/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__bools.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - false - diff --git a/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__dimens.xml deleted file mode 100644 index f6785381..00000000 --- a/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__dimens.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - 56dip - - 4dip - - 18dp - - 14dp - - -3dp - - 9dip - - 5 - - - 64dip - diff --git a/android-libraries/ActionBarSherlock/res/values-v11/abs__themes.xml b/android-libraries/ActionBarSherlock/res/values-v11/abs__themes.xml deleted file mode 100644 index 03473572..00000000 --- a/android-libraries/ActionBarSherlock/res/values-v11/abs__themes.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values-v14/abs__styles.xml b/android-libraries/ActionBarSherlock/res/values-v14/abs__styles.xml deleted file mode 100644 index f2aa64d2..00000000 --- a/android-libraries/ActionBarSherlock/res/values-v14/abs__styles.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values-v14/abs__themes.xml b/android-libraries/ActionBarSherlock/res/values-v14/abs__themes.xml deleted file mode 100644 index ceb96073..00000000 --- a/android-libraries/ActionBarSherlock/res/values-v14/abs__themes.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values-w360dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-w360dp/abs__dimens.xml deleted file mode 100644 index 6f49d7e4..00000000 --- a/android-libraries/ActionBarSherlock/res/values-w360dp/abs__dimens.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - 3 - diff --git a/android-libraries/ActionBarSherlock/res/values-w480dp/abs__bools.xml b/android-libraries/ActionBarSherlock/res/values-w480dp/abs__bools.xml deleted file mode 100644 index 3eaf4aee..00000000 --- a/android-libraries/ActionBarSherlock/res/values-w480dp/abs__bools.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - true - false - diff --git a/android-libraries/ActionBarSherlock/res/values-w480dp/abs__config.xml b/android-libraries/ActionBarSherlock/res/values-w480dp/abs__config.xml deleted file mode 100644 index 88357b0a..00000000 --- a/android-libraries/ActionBarSherlock/res/values-w480dp/abs__config.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - true - - diff --git a/android-libraries/ActionBarSherlock/res/values-w500dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-w500dp/abs__dimens.xml deleted file mode 100644 index 2fd4deea..00000000 --- a/android-libraries/ActionBarSherlock/res/values-w500dp/abs__dimens.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - 4 - diff --git a/android-libraries/ActionBarSherlock/res/values-w600dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-w600dp/abs__dimens.xml deleted file mode 100644 index b085952d..00000000 --- a/android-libraries/ActionBarSherlock/res/values-w600dp/abs__dimens.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - 5 - diff --git a/android-libraries/ActionBarSherlock/res/values-xlarge/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-xlarge/abs__dimens.xml deleted file mode 100644 index bfc535de..00000000 --- a/android-libraries/ActionBarSherlock/res/values-xlarge/abs__dimens.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - 56dip - - 4dip - - 18dp - - 14dp - - -3dp - - 9dip - - - 64dip - - - 45% - - 72% - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__attrs.xml b/android-libraries/ActionBarSherlock/res/values/abs__attrs.xml deleted file mode 100644 index 81c34710..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__attrs.xml +++ /dev/null @@ -1,380 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__bools.xml b/android-libraries/ActionBarSherlock/res/values/abs__bools.xml deleted file mode 100644 index 0b432448..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__bools.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - false - true - true - - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__colors.xml b/android-libraries/ActionBarSherlock/res/values/abs__colors.xml deleted file mode 100644 index 625c632f..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__colors.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - #ff000000 - #fff3f3f3 - @color/abs__background_holo_light - @color/abs__background_holo_dark - #ff4c4c4c - #ffb2b2b2 - @color/abs__bright_foreground_holo_light - @color/abs__bright_foreground_holo_dark - #ff33b5e5 - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__config.xml b/android-libraries/ActionBarSherlock/res/values/abs__config.xml deleted file mode 100644 index 4c7b5d45..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__config.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - 320dp - - - false - - - true - - - false - - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values/abs__dimens.xml deleted file mode 100644 index 0a409756..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__dimens.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - 48dip - - 8dip - - 18dp - - 14dp - - -3dp - - 5dip - - 2 - - - 56dip - - - 64dip - - - 65% - - 95% - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__ids.xml b/android-libraries/ActionBarSherlock/res/values/abs__ids.xml deleted file mode 100644 index f9f56045..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__ids.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__strings.xml b/android-libraries/ActionBarSherlock/res/values/abs__strings.xml deleted file mode 100644 index 1e1c7022..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__strings.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - Navigate home - - Navigate up - - More options - - - Done - - - See all... - - Select activity - - Share with... - - Choose an application - - Share with - - Share with %s - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__styles.xml b/android-libraries/ActionBarSherlock/res/values/abs__styles.xml deleted file mode 100644 index 8cbd3648..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__styles.xml +++ /dev/null @@ -1,384 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values/abs__themes.xml b/android-libraries/ActionBarSherlock/res/values/abs__themes.xml deleted file mode 100644 index 5300dedd..00000000 --- a/android-libraries/ActionBarSherlock/res/values/abs__themes.xml +++ /dev/null @@ -1,226 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/android-libraries/ActionBarSherlock/res/values/strings.xml b/android-libraries/ActionBarSherlock/res/values/strings.xml deleted file mode 100644 index 43d1652c..00000000 --- a/android-libraries/ActionBarSherlock/res/values/strings.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - Hello World! - ActionBarSherlock - - \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/src/android/support/v4/app/_ActionBarSherlockTrojanHorse.java b/android-libraries/ActionBarSherlock/src/android/support/v4/app/_ActionBarSherlockTrojanHorse.java deleted file mode 100644 index 3e3db62b..00000000 --- a/android-libraries/ActionBarSherlock/src/android/support/v4/app/_ActionBarSherlockTrojanHorse.java +++ /dev/null @@ -1,144 +0,0 @@ -package android.support.v4.app; - -import android.util.Log; -import android.view.View; -import android.view.Window; -import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; -import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; -import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -import java.util.ArrayList; - -/** I'm in ur package. Stealing ur variables. */ -public abstract class _ActionBarSherlockTrojanHorse extends FragmentActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener { - private static final boolean DEBUG = false; - private static final String TAG = "_ActionBarSherlockTrojanHorse"; - - /** Fragment interface for menu creation callback. */ - public interface OnCreateOptionsMenuListener { - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater); - } - /** Fragment interface for menu preparation callback. */ - public interface OnPrepareOptionsMenuListener { - public void onPrepareOptionsMenu(Menu menu); - } - /** Fragment interface for menu item selection callback. */ - public interface OnOptionsItemSelectedListener { - public boolean onOptionsItemSelected(MenuItem item); - } - - private ArrayList mCreatedMenus; - - - /////////////////////////////////////////////////////////////////////////// - // Sherlock menu handling - /////////////////////////////////////////////////////////////////////////// - - @Override - public boolean onCreatePanelMenu(int featureId, Menu menu) { - if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu); - - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - boolean result = onCreateOptionsMenu(menu); - if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] activity create result: " + result); - - MenuInflater inflater = getSupportMenuInflater(); - boolean show = false; - ArrayList newMenus = null; - if (mFragments.mActive != null) { - for (int i = 0; i < mFragments.mAdded.size(); i++) { - Fragment f = mFragments.mAdded.get(i); - if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnCreateOptionsMenuListener) { - show = true; - ((OnCreateOptionsMenuListener)f).onCreateOptionsMenu(menu, inflater); - if (newMenus == null) { - newMenus = new ArrayList(); - } - newMenus.add(f); - } - } - } - - if (mCreatedMenus != null) { - for (int i = 0; i < mCreatedMenus.size(); i++) { - Fragment f = mCreatedMenus.get(i); - if (newMenus == null || !newMenus.contains(f)) { - f.onDestroyOptionsMenu(); - } - } - } - - mCreatedMenus = newMenus; - - if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] fragments create result: " + show); - result |= show; - - if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result); - return result; - } - return false; - } - - @Override - public boolean onPreparePanel(int featureId, View view, Menu menu) { - if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + " menu: " + menu); - - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - boolean result = onPrepareOptionsMenu(menu); - if (DEBUG) Log.d(TAG, "[onPreparePanel] activity prepare result: " + result); - - boolean show = false; - if (mFragments.mActive != null) { - for (int i = 0; i < mFragments.mAdded.size(); i++) { - Fragment f = mFragments.mAdded.get(i); - if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnPrepareOptionsMenuListener) { - show = true; - ((OnPrepareOptionsMenuListener)f).onPrepareOptionsMenu(menu); - } - } - } - - if (DEBUG) Log.d(TAG, "[onPreparePanel] fragments prepare result: " + show); - result |= show; - - result &= menu.hasVisibleItems(); - if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result); - return result; - } - return false; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item); - - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - if (onOptionsItemSelected(item)) { - return true; - } - - if (mFragments.mActive != null) { - for (int i = 0; i < mFragments.mAdded.size(); i++) { - Fragment f = mFragments.mAdded.get(i); - if (f != null && !f.mHidden && f.mHasMenu && f.mMenuVisible && f instanceof OnOptionsItemSelectedListener) { - if (((OnOptionsItemSelectedListener)f).onOptionsItemSelected(item)) { - return true; - } - } - } - } - } - return false; - } - - public abstract boolean onCreateOptionsMenu(Menu menu); - - public abstract boolean onPrepareOptionsMenu(Menu menu); - - public abstract boolean onOptionsItemSelected(MenuItem item); - - public abstract MenuInflater getSupportMenuInflater(); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/ActionBarSherlock.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/ActionBarSherlock.java deleted file mode 100644 index 8340fb59..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/ActionBarSherlock.java +++ /dev/null @@ -1,791 +0,0 @@ -package com.actionbarsherlock; - -import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Iterator; -import android.app.Activity; -import android.content.Context; -import android.content.res.Configuration; -import android.os.Build; -import android.os.Bundle; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.internal.ActionBarSherlockCompat; -import com.actionbarsherlock.internal.ActionBarSherlockNative; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -/** - *

Helper for implementing the action bar design pattern across all versions - * of Android.

- * - *

This class will manage interaction with a custom action bar based on the - * Android 4.0 source code. The exposed API mirrors that of its native - * counterpart and you should refer to its documentation for instruction.

- * - * @author Jake Wharton - */ -public abstract class ActionBarSherlock { - protected static final String TAG = "ActionBarSherlock"; - protected static final boolean DEBUG = false; - - private static final Class[] CONSTRUCTOR_ARGS = new Class[] { Activity.class, int.class }; - private static final HashMap> IMPLEMENTATIONS = - new HashMap>(); - - static { - //Register our two built-in implementations - registerImplementation(ActionBarSherlockCompat.class); - registerImplementation(ActionBarSherlockNative.class); - } - - - /** - *

Denotes an implementation of ActionBarSherlock which provides an - * action bar-enhanced experience.

- */ - @Target(ElementType.TYPE) - @Retention(RetentionPolicy.RUNTIME) - public @interface Implementation { - static final int DEFAULT_API = -1; - static final int DEFAULT_DPI = -1; - - int api() default DEFAULT_API; - int dpi() default DEFAULT_DPI; - } - - - /** Activity interface for menu creation callback. */ - public interface OnCreatePanelMenuListener { - public boolean onCreatePanelMenu(int featureId, Menu menu); - } - /** Activity interface for menu creation callback. */ - public interface OnCreateOptionsMenuListener { - public boolean onCreateOptionsMenu(Menu menu); - } - /** Activity interface for menu item selection callback. */ - public interface OnMenuItemSelectedListener { - public boolean onMenuItemSelected(int featureId, MenuItem item); - } - /** Activity interface for menu item selection callback. */ - public interface OnOptionsItemSelectedListener { - public boolean onOptionsItemSelected(MenuItem item); - } - /** Activity interface for menu preparation callback. */ - public interface OnPreparePanelListener { - public boolean onPreparePanel(int featureId, View view, Menu menu); - } - /** Activity interface for menu preparation callback. */ - public interface OnPrepareOptionsMenuListener { - public boolean onPrepareOptionsMenu(Menu menu); - } - /** Activity interface for action mode finished callback. */ - public interface OnActionModeFinishedListener { - public void onActionModeFinished(ActionMode mode); - } - /** Activity interface for action mode started callback. */ - public interface OnActionModeStartedListener { - public void onActionModeStarted(ActionMode mode); - } - - - /** - * If set, the logic in these classes will assume that an {@link Activity} - * is dispatching all of the required events to the class. This flag should - * only be used internally or if you are creating your own base activity - * modeled after one of the included types (e.g., {@code SherlockActivity}). - */ - public static final int FLAG_DELEGATE = 1; - - - /** - * Register an ActionBarSherlock implementation. - * - * @param implementationClass Target implementation class which extends - * {@link ActionBarSherlock}. This class must also be annotated with - * {@link Implementation}. - */ - public static void registerImplementation(Class implementationClass) { - if (!implementationClass.isAnnotationPresent(Implementation.class)) { - throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation"); - } else if (IMPLEMENTATIONS.containsValue(implementationClass)) { - if (DEBUG) Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered"); - return; - } - - Implementation impl = implementationClass.getAnnotation(Implementation.class); - if (DEBUG) Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl); - IMPLEMENTATIONS.put(impl, implementationClass); - } - - /** - * Unregister an ActionBarSherlock implementation. This should be - * considered very volatile and you should only use it if you know what - * you are doing. You have been warned. - * - * @param implementationClass Target implementation class. - * @return Boolean indicating whether the class was removed. - */ - public static boolean unregisterImplementation(Class implementationClass) { - return IMPLEMENTATIONS.values().remove(implementationClass); - } - - /** - * Wrap an activity with an action bar abstraction which will enable the - * use of a custom implementation on platforms where a native version does - * not exist. - * - * @param activity Activity to wrap. - * @return Instance to interact with the action bar. - */ - public static ActionBarSherlock wrap(Activity activity) { - return wrap(activity, 0); - } - - /** - * Wrap an activity with an action bar abstraction which will enable the - * use of a custom implementation on platforms where a native version does - * not exist. - * - * @param activity Owning activity. - * @param flags Option flags to control behavior. - * @return Instance to interact with the action bar. - */ - public static ActionBarSherlock wrap(Activity activity, int flags) { - //Create a local implementation map we can modify - HashMap> impls = - new HashMap>(IMPLEMENTATIONS); - boolean hasQualfier; - - /* DPI FILTERING */ - hasQualfier = false; - for (Implementation key : impls.keySet()) { - //Only honor TVDPI as a specific qualifier - if (key.dpi() == DisplayMetrics.DENSITY_TV) { - hasQualfier = true; - break; - } - } - if (hasQualfier) { - final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV; - for (Iterator keys = impls.keySet().iterator(); keys.hasNext(); ) { - int keyDpi = keys.next().dpi(); - if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV) - || (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) { - keys.remove(); - } - } - } - - /* API FILTERING */ - hasQualfier = false; - for (Implementation key : impls.keySet()) { - if (key.api() != Implementation.DEFAULT_API) { - hasQualfier = true; - break; - } - } - if (hasQualfier) { - final int runtimeApi = Build.VERSION.SDK_INT; - int bestApi = 0; - for (Iterator keys = impls.keySet().iterator(); keys.hasNext(); ) { - int keyApi = keys.next().api(); - if (keyApi > runtimeApi) { - keys.remove(); - } else if (keyApi > bestApi) { - bestApi = keyApi; - } - } - for (Iterator keys = impls.keySet().iterator(); keys.hasNext(); ) { - if (keys.next().api() != bestApi) { - keys.remove(); - } - } - } - - if (impls.size() > 1) { - throw new IllegalStateException("More than one implementation matches configuration."); - } - if (impls.isEmpty()) { - throw new IllegalStateException("No implementations match configuration."); - } - Class impl = impls.values().iterator().next(); - if (DEBUG) Log.i(TAG, "Using implementation: " + impl.getSimpleName()); - - try { - Constructor ctor = impl.getConstructor(CONSTRUCTOR_ARGS); - return ctor.newInstance(activity, flags); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - - /** Activity which is displaying the action bar. Also used for context. */ - protected final Activity mActivity; - /** Whether delegating actions for the activity or managing ourselves. */ - protected final boolean mIsDelegate; - - /** Reference to our custom menu inflater which supports action items. */ - protected MenuInflater mMenuInflater; - - - - protected ActionBarSherlock(Activity activity, int flags) { - if (DEBUG) Log.d(TAG, "[] activity: " + activity + ", flags: " + flags); - - mActivity = activity; - mIsDelegate = (flags & FLAG_DELEGATE) != 0; - } - - - /** - * Get the current action bar instance. - * - * @return Action bar instance. - */ - public abstract ActionBar getActionBar(); - - - /////////////////////////////////////////////////////////////////////////// - // Lifecycle and interaction callbacks when delegating - /////////////////////////////////////////////////////////////////////////// - - /** - * Notify action bar of a configuration change event. Should be dispatched - * after the call to the superclass implementation. - * - *
-     * @Override
-     * public void onConfigurationChanged(Configuration newConfig) {
-     *     super.onConfigurationChanged(newConfig);
-     *     mSherlock.dispatchConfigurationChanged(newConfig);
-     * }
-     * 
- * - * @param newConfig The new device configuration. - */ - public void dispatchConfigurationChanged(Configuration newConfig) {} - - /** - * Notify the action bar that the activity has finished its resuming. This - * should be dispatched after the call to the superclass implementation. - * - *
-     * @Override
-     * protected void onPostResume() {
-     *     super.onPostResume();
-     *     mSherlock.dispatchPostResume();
-     * }
-     * 
- */ - public void dispatchPostResume() {} - - /** - * Notify the action bar that the activity is pausing. This should be - * dispatched before the call to the superclass implementation. - * - *
-     * @Override
-     * protected void onPause() {
-     *     mSherlock.dispatchPause();
-     *     super.onPause();
-     * }
-     * 
- */ - public void dispatchPause() {} - - /** - * Notify the action bar that the activity is stopping. This should be - * called before the superclass implementation. - * - *

- * @Override - * protected void onStop() { - * mSherlock.dispatchStop(); - * super.onStop(); - * } - *

- */ - public void dispatchStop() {} - - /** - * Indicate that the menu should be recreated by calling - * {@link OnCreateOptionsMenuListener#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)}. - */ - public abstract void dispatchInvalidateOptionsMenu(); - - /** - * Notify the action bar that it should display its overflow menu if it is - * appropriate for the device. The implementation should conditionally - * call the superclass method only if this method returns {@code false}. - * - *

- * @Override - * public void openOptionsMenu() { - * if (!mSherlock.dispatchOpenOptionsMenu()) { - * super.openOptionsMenu(); - * } - * } - *

- * - * @return {@code true} if the opening of the menu was handled internally. - */ - public boolean dispatchOpenOptionsMenu() { - return false; - } - - /** - * Notify the action bar that it should close its overflow menu if it is - * appropriate for the device. This implementation should conditionally - * call the superclass method only if this method returns {@code false}. - * - *
-     * @Override
-     * public void closeOptionsMenu() {
-     *     if (!mSherlock.dispatchCloseOptionsMenu()) {
-     *         super.closeOptionsMenu();
-     *     }
-     * }
-     * 
- * - * @return {@code true} if the closing of the menu was handled internally. - */ - public boolean dispatchCloseOptionsMenu() { - return false; - } - - /** - * Notify the class that the activity has finished its creation. This - * should be called after the superclass implementation. - * - *
-     * @Override
-     * protected void onPostCreate(Bundle savedInstanceState) {
-     *     mSherlock.dispatchPostCreate(savedInstanceState);
-     *     super.onPostCreate(savedInstanceState);
-     * }
-     * 
- * - * @param savedInstanceState If the activity is being re-initialized after - * previously being shut down then this Bundle - * contains the data it most recently supplied in - * {@link Activity#}onSaveInstanceState(Bundle)}. - * Note: Otherwise it is null. - */ - public void dispatchPostCreate(Bundle savedInstanceState) {} - - /** - * Notify the action bar that the title has changed and the action bar - * should be updated to reflect the change. This should be called before - * the superclass implementation. - * - *
-     *  @Override
-     *  protected void onTitleChanged(CharSequence title, int color) {
-     *      mSherlock.dispatchTitleChanged(title, color);
-     *      super.onTitleChanged(title, color);
-     *  }
-     * 
- * - * @param title New activity title. - * @param color New activity color. - */ - public void dispatchTitleChanged(CharSequence title, int color) {} - - /** - * Notify the action bar the user has created a key event. This is used to - * toggle the display of the overflow action item with the menu key and to - * close the action mode or expanded action item with the back key. - * - *
-     * @Override
-     * public boolean dispatchKeyEvent(KeyEvent event) {
-     *     if (mSherlock.dispatchKeyEvent(event)) {
-     *         return true;
-     *     }
-     *     return super.dispatchKeyEvent(event);
-     * }
-     * 
- * - * @param event Description of the key event. - * @return {@code true} if the event was handled. - */ - public boolean dispatchKeyEvent(KeyEvent event) { - return false; - } - - /** - * Notify the action bar that the Activity has triggered a menu creation - * which should happen on the conclusion of {@link Activity#onCreate}. This - * will be used to gain a reference to the native menu for native and - * overflow binding as well as to indicate when compatibility create should - * occur for the first time. - * - * @param menu Activity native menu. - * @return {@code true} since we always want to say that we have a native - */ - public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu); - - /** - * Notify the action bar that the Activity has triggered a menu preparation - * which usually means that the user has requested the overflow menu via a - * hardware menu key. You should return the result of this method call and - * not call the superclass implementation. - * - *

- * @Override - * public final boolean onPrepareOptionsMenu(android.view.Menu menu) { - * return mSherlock.dispatchPrepareOptionsMenu(menu); - * } - *

- * - * @param menu Activity native menu. - * @return {@code true} if menu display should proceed. - */ - public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu); - - /** - * Notify the action bar that a native options menu item has been selected. - * The implementation should return the result of this method call. - * - *

- * @Override - * public final boolean onOptionsItemSelected(android.view.MenuItem item) { - * return mSherlock.dispatchOptionsItemSelected(item); - * } - *

- * - * @param item Options menu item. - * @return @{code true} if the selection was handled. - */ - public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item); - - /** - * Notify the action bar that the overflow menu has been opened. The - * implementation should conditionally return {@code true} if this method - * returns {@code true}, otherwise return the result of the superclass - * method. - * - *

- * @Override - * public final boolean onMenuOpened(int featureId, android.view.Menu menu) { - * if (mSherlock.dispatchMenuOpened(featureId, menu)) { - * return true; - * } - * return super.onMenuOpened(featureId, menu); - * } - *

- * - * @param featureId Window feature which triggered the event. - * @param menu Activity native menu. - * @return {@code true} if the event was handled by this method. - */ - public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) { - return false; - } - - /** - * Notify the action bar that the overflow menu has been closed. This - * method should be called before the superclass implementation. - * - *

- * @Override - * public void onPanelClosed(int featureId, android.view.Menu menu) { - * mSherlock.dispatchPanelClosed(featureId, menu); - * super.onPanelClosed(featureId, menu); - * } - *

- * - * @param featureId - * @param menu - */ - public void dispatchPanelClosed(int featureId, android.view.Menu menu) {} - - /** - * Notify the action bar that the activity has been destroyed. This method - * should be called before the superclass implementation. - * - *

- * @Override - * public void onDestroy() { - * mSherlock.dispatchDestroy(); - * super.onDestroy(); - * } - *

- */ - public void dispatchDestroy() {} - - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - - /** - * Internal method to trigger the menu creation process. - * - * @return {@code true} if menu creation should proceed. - */ - protected final boolean callbackCreateOptionsMenu(Menu menu) { - if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu); - - boolean result = true; - if (mActivity instanceof OnCreatePanelMenuListener) { - OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity; - result = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); - } else if (mActivity instanceof OnCreateOptionsMenuListener) { - OnCreateOptionsMenuListener listener = (OnCreateOptionsMenuListener)mActivity; - result = listener.onCreateOptionsMenu(menu); - } - - if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] returning " + result); - return result; - } - - /** - * Internal method to trigger the menu preparation process. - * - * @return {@code true} if menu preparation should proceed. - */ - protected final boolean callbackPrepareOptionsMenu(Menu menu) { - if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] menu: " + menu); - - boolean result = true; - if (mActivity instanceof OnPreparePanelListener) { - OnPreparePanelListener listener = (OnPreparePanelListener)mActivity; - result = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, menu); - } else if (mActivity instanceof OnPrepareOptionsMenuListener) { - OnPrepareOptionsMenuListener listener = (OnPrepareOptionsMenuListener)mActivity; - result = listener.onPrepareOptionsMenu(menu); - } - - if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] returning " + result); - return result; - } - - /** - * Internal method for dispatching options menu selection to the owning - * activity callback. - * - * @param item Selected options menu item. - * @return {@code true} if the item selection was handled in the callback. - */ - protected final boolean callbackOptionsItemSelected(MenuItem item) { - if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed()); - - boolean result = false; - if (mActivity instanceof OnMenuItemSelectedListener) { - OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity; - result = listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); - } else if (mActivity instanceof OnOptionsItemSelectedListener) { - OnOptionsItemSelectedListener listener = (OnOptionsItemSelectedListener)mActivity; - result = listener.onOptionsItemSelected(item); - } - - if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] returning " + result); - return result; - } - - - /////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////// - - - /** - * Query for the availability of a certain feature. - * - * @param featureId The feature ID to check. - * @return {@code true} if feature is enabled, {@code false} otherwise. - */ - public abstract boolean hasFeature(int featureId); - - /** - * Enable extended screen features. This must be called before - * {@code setContentView()}. May be called as many times as desired as long - * as it is before {@code setContentView()}. If not called, no extended - * features will be available. You can not turn off a feature once it is - * requested. - * - * @param featureId The desired features, defined as constants by Window. - * @return Returns true if the requested feature is supported and now - * enabled. - */ - public abstract boolean requestFeature(int featureId); - - /** - * Set extra options that will influence the UI for this window. - * - * @param uiOptions Flags specifying extra options for this window. - */ - public abstract void setUiOptions(int uiOptions); - - /** - * Set extra options that will influence the UI for this window. Only the - * bits filtered by mask will be modified. - * - * @param uiOptions Flags specifying extra options for this window. - * @param mask Flags specifying which options should be modified. Others - * will remain unchanged. - */ - public abstract void setUiOptions(int uiOptions, int mask); - - /** - * Set the content of the activity inside the action bar. - * - * @param layoutResId Layout resource ID. - */ - public abstract void setContentView(int layoutResId); - - /** - * Set the content of the activity inside the action bar. - * - * @param view The desired content to display. - */ - public void setContentView(View view) { - if (DEBUG) Log.d(TAG, "[setContentView] view: " + view); - - setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); - } - - /** - * Set the content of the activity inside the action bar. - * - * @param view The desired content to display. - * @param params Layout parameters to apply to the view. - */ - public abstract void setContentView(View view, ViewGroup.LayoutParams params); - - /** - * Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} - * to add an additional content view to the screen. Added after any - * existing ones on the screen -- existing views are NOT removed. - * - * @param view The desired content to display. - * @param params Layout parameters for the view. - */ - public abstract void addContentView(View view, ViewGroup.LayoutParams params); - - /** - * Change the title associated with this activity. - */ - public abstract void setTitle(CharSequence title); - - /** - * Change the title associated with this activity. - */ - public void setTitle(int resId) { - if (DEBUG) Log.d(TAG, "[setTitle] resId: " + resId); - - setTitle(mActivity.getString(resId)); - } - - /** - * Sets the visibility of the progress bar in the title. - *

- * In order for the progress bar to be shown, the feature must be requested - * via {@link #requestWindowFeature(int)}. - * - * @param visible Whether to show the progress bars in the title. - */ - public abstract void setProgressBarVisibility(boolean visible); - - /** - * Sets the visibility of the indeterminate progress bar in the title. - *

- * In order for the progress bar to be shown, the feature must be requested - * via {@link #requestWindowFeature(int)}. - * - * @param visible Whether to show the progress bars in the title. - */ - public abstract void setProgressBarIndeterminateVisibility(boolean visible); - - /** - * Sets whether the horizontal progress bar in the title should be indeterminate (the circular - * is always indeterminate). - *

- * In order for the progress bar to be shown, the feature must be requested - * via {@link #requestWindowFeature(int)}. - * - * @param indeterminate Whether the horizontal progress bar should be indeterminate. - */ - public abstract void setProgressBarIndeterminate(boolean indeterminate); - - /** - * Sets the progress for the progress bars in the title. - *

- * In order for the progress bar to be shown, the feature must be requested - * via {@link #requestWindowFeature(int)}. - * - * @param progress The progress for the progress bar. Valid ranges are from - * 0 to 10000 (both inclusive). If 10000 is given, the progress - * bar will be completely filled and will fade out. - */ - public abstract void setProgress(int progress); - - /** - * Sets the secondary progress for the progress bar in the title. This - * progress is drawn between the primary progress (set via - * {@link #setProgress(int)} and the background. It can be ideal for media - * scenarios such as showing the buffering progress while the default - * progress shows the play progress. - *

- * In order for the progress bar to be shown, the feature must be requested - * via {@link #requestWindowFeature(int)}. - * - * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from - * 0 to 10000 (both inclusive). - */ - public abstract void setSecondaryProgress(int secondaryProgress); - - /** - * Get a menu inflater instance which supports the newer menu attributes. - * - * @return Menu inflater instance. - */ - public MenuInflater getMenuInflater() { - if (DEBUG) Log.d(TAG, "[getMenuInflater]"); - - // Make sure that action views can get an appropriate theme. - if (mMenuInflater == null) { - if (getActionBar() != null) { - mMenuInflater = new MenuInflater(getThemedContext()); - } else { - mMenuInflater = new MenuInflater(mActivity); - } - } - return mMenuInflater; - } - - protected abstract Context getThemedContext(); - - /** - * Start an action mode. - * - * @param callback Callback that will manage lifecycle events for this - * context mode. - * @return The ContextMode that was started, or null if it was canceled. - * @see ActionMode - */ - public abstract ActionMode startActionMode(ActionMode.Callback callback); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/ActionBar.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/ActionBar.java deleted file mode 100644 index 2497d24f..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/ActionBar.java +++ /dev/null @@ -1,947 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.app; - -import android.content.Context; -import android.graphics.drawable.Drawable; -import android.support.v4.app.FragmentTransaction; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.View; -import android.view.ViewDebug; -import android.view.ViewGroup; -import android.view.ViewGroup.MarginLayoutParams; -import android.widget.SpinnerAdapter; - -/** - * A window feature at the top of the activity that may display the activity title, navigation - * modes, and other interactive items. - *

Beginning with Android 3.0 (API level 11), the action bar appears at the top of an - * activity's window when the activity uses the system's {@link - * android.R.style#Theme_Holo Holo} theme (or one of its descendant themes), which is the default. - * You may otherwise add the action bar by calling {@link - * android.view.Window#requestFeature requestFeature(FEATURE_ACTION_BAR)} or by declaring it in a - * custom theme with the {@link android.R.styleable#Theme_windowActionBar windowActionBar} property. - *

By default, the action bar shows the application icon on - * the left, followed by the activity title. If your activity has an options menu, you can make - * select items accessible directly from the action bar as "action items". You can also - * modify various characteristics of the action bar or remove it completely.

- *

From your activity, you can retrieve an instance of {@link ActionBar} by calling {@link - * android.app.Activity#getActionBar getActionBar()}.

- *

In some cases, the action bar may be overlayed by another bar that enables contextual actions, - * using an {@link android.view.ActionMode}. For example, when the user selects one or more items in - * your activity, you can enable an action mode that offers actions specific to the selected - * items, with a UI that temporarily replaces the action bar. Although the UI may occupy the - * same space, the {@link android.view.ActionMode} APIs are distinct and independent from those for - * {@link ActionBar}. - *

- *

Developer Guides

- *

For information about how to use the action bar, including how to add action items, navigation - * modes and more, read the Action - * Bar developer guide.

- *
- */ -public abstract class ActionBar { - /** - * Standard navigation mode. Consists of either a logo or icon - * and title text with an optional subtitle. Clicking any of these elements - * will dispatch onOptionsItemSelected to the host Activity with - * a MenuItem with item ID android.R.id.home. - */ - public static final int NAVIGATION_MODE_STANDARD = android.app.ActionBar.NAVIGATION_MODE_STANDARD; - - /** - * List navigation mode. Instead of static title text this mode - * presents a list menu for navigation within the activity. - * e.g. this might be presented to the user as a dropdown list. - */ - public static final int NAVIGATION_MODE_LIST = android.app.ActionBar.NAVIGATION_MODE_LIST; - - /** - * Tab navigation mode. Instead of static title text this mode - * presents a series of tabs for navigation within the activity. - */ - public static final int NAVIGATION_MODE_TABS = android.app.ActionBar.NAVIGATION_MODE_TABS; - - /** - * Use logo instead of icon if available. This flag will cause appropriate - * navigation modes to use a wider logo in place of the standard icon. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public static final int DISPLAY_USE_LOGO = android.app.ActionBar.DISPLAY_USE_LOGO; - - /** - * Show 'home' elements in this action bar, leaving more space for other - * navigation elements. This includes logo and icon. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public static final int DISPLAY_SHOW_HOME = android.app.ActionBar.DISPLAY_SHOW_HOME; - - /** - * Display the 'home' element such that it appears as an 'up' affordance. - * e.g. show an arrow to the left indicating the action that will be taken. - * - * Set this flag if selecting the 'home' button in the action bar to return - * up by a single level in your UI rather than back to the top level or front page. - * - *

Setting this option will implicitly enable interaction with the home/up - * button. See {@link #setHomeButtonEnabled(boolean)}. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public static final int DISPLAY_HOME_AS_UP = android.app.ActionBar.DISPLAY_HOME_AS_UP; - - /** - * Show the activity title and subtitle, if present. - * - * @see #setTitle(CharSequence) - * @see #setTitle(int) - * @see #setSubtitle(CharSequence) - * @see #setSubtitle(int) - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public static final int DISPLAY_SHOW_TITLE = android.app.ActionBar.DISPLAY_SHOW_TITLE; - - /** - * Show the custom view if one has been set. - * @see #setCustomView(View) - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public static final int DISPLAY_SHOW_CUSTOM = android.app.ActionBar.DISPLAY_SHOW_CUSTOM; - - /** - * Set the action bar into custom navigation mode, supplying a view - * for custom navigation. - * - * Custom navigation views appear between the application icon and - * any action buttons and may use any space available there. Common - * use cases for custom navigation views might include an auto-suggesting - * address bar for a browser or other navigation mechanisms that do not - * translate well to provided navigation modes. - * - * @param view Custom navigation view to place in the ActionBar. - */ - public abstract void setCustomView(View view); - - /** - * Set the action bar into custom navigation mode, supplying a view - * for custom navigation. - * - *

Custom navigation views appear between the application icon and - * any action buttons and may use any space available there. Common - * use cases for custom navigation views might include an auto-suggesting - * address bar for a browser or other navigation mechanisms that do not - * translate well to provided navigation modes.

- * - *

The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for - * the custom view to be displayed.

- * - * @param view Custom navigation view to place in the ActionBar. - * @param layoutParams How this custom view should layout in the bar. - * - * @see #setDisplayOptions(int, int) - */ - public abstract void setCustomView(View view, LayoutParams layoutParams); - - /** - * Set the action bar into custom navigation mode, supplying a view - * for custom navigation. - * - *

Custom navigation views appear between the application icon and - * any action buttons and may use any space available there. Common - * use cases for custom navigation views might include an auto-suggesting - * address bar for a browser or other navigation mechanisms that do not - * translate well to provided navigation modes.

- * - *

The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for - * the custom view to be displayed.

- * - * @param resId Resource ID of a layout to inflate into the ActionBar. - * - * @see #setDisplayOptions(int, int) - */ - public abstract void setCustomView(int resId); - - /** - * Set the icon to display in the 'home' section of the action bar. - * The action bar will use an icon specified by its style or the - * activity icon by default. - * - * Whether the home section shows an icon or logo is controlled - * by the display option {@link #DISPLAY_USE_LOGO}. - * - * @param resId Resource ID of a drawable to show as an icon. - * - * @see #setDisplayUseLogoEnabled(boolean) - * @see #setDisplayShowHomeEnabled(boolean) - */ - public abstract void setIcon(int resId); - - /** - * Set the icon to display in the 'home' section of the action bar. - * The action bar will use an icon specified by its style or the - * activity icon by default. - * - * Whether the home section shows an icon or logo is controlled - * by the display option {@link #DISPLAY_USE_LOGO}. - * - * @param icon Drawable to show as an icon. - * - * @see #setDisplayUseLogoEnabled(boolean) - * @see #setDisplayShowHomeEnabled(boolean) - */ - public abstract void setIcon(Drawable icon); - - /** - * Set the logo to display in the 'home' section of the action bar. - * The action bar will use a logo specified by its style or the - * activity logo by default. - * - * Whether the home section shows an icon or logo is controlled - * by the display option {@link #DISPLAY_USE_LOGO}. - * - * @param resId Resource ID of a drawable to show as a logo. - * - * @see #setDisplayUseLogoEnabled(boolean) - * @see #setDisplayShowHomeEnabled(boolean) - */ - public abstract void setLogo(int resId); - - /** - * Set the logo to display in the 'home' section of the action bar. - * The action bar will use a logo specified by its style or the - * activity logo by default. - * - * Whether the home section shows an icon or logo is controlled - * by the display option {@link #DISPLAY_USE_LOGO}. - * - * @param logo Drawable to show as a logo. - * - * @see #setDisplayUseLogoEnabled(boolean) - * @see #setDisplayShowHomeEnabled(boolean) - */ - public abstract void setLogo(Drawable logo); - - /** - * Set the adapter and navigation callback for list navigation mode. - * - * The supplied adapter will provide views for the expanded list as well as - * the currently selected item. (These may be displayed differently.) - * - * The supplied OnNavigationListener will alert the application when the user - * changes the current list selection. - * - * @param adapter An adapter that will provide views both to display - * the current navigation selection and populate views - * within the dropdown navigation menu. - * @param callback An OnNavigationListener that will receive events when the user - * selects a navigation item. - */ - public abstract void setListNavigationCallbacks(SpinnerAdapter adapter, - OnNavigationListener callback); - - /** - * Set the selected navigation item in list or tabbed navigation modes. - * - * @param position Position of the item to select. - */ - public abstract void setSelectedNavigationItem(int position); - - /** - * Get the position of the selected navigation item in list or tabbed navigation modes. - * - * @return Position of the selected item. - */ - public abstract int getSelectedNavigationIndex(); - - /** - * Get the number of navigation items present in the current navigation mode. - * - * @return Number of navigation items. - */ - public abstract int getNavigationItemCount(); - - /** - * Set the action bar's title. This will only be displayed if - * {@link #DISPLAY_SHOW_TITLE} is set. - * - * @param title Title to set - * - * @see #setTitle(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setTitle(CharSequence title); - - /** - * Set the action bar's title. This will only be displayed if - * {@link #DISPLAY_SHOW_TITLE} is set. - * - * @param resId Resource ID of title string to set - * - * @see #setTitle(CharSequence) - * @see #setDisplayOptions(int, int) - */ - public abstract void setTitle(int resId); - - /** - * Set the action bar's subtitle. This will only be displayed if - * {@link #DISPLAY_SHOW_TITLE} is set. Set to null to disable the - * subtitle entirely. - * - * @param subtitle Subtitle to set - * - * @see #setSubtitle(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setSubtitle(CharSequence subtitle); - - /** - * Set the action bar's subtitle. This will only be displayed if - * {@link #DISPLAY_SHOW_TITLE} is set. - * - * @param resId Resource ID of subtitle string to set - * - * @see #setSubtitle(CharSequence) - * @see #setDisplayOptions(int, int) - */ - public abstract void setSubtitle(int resId); - - /** - * Set display options. This changes all display option bits at once. To change - * a limited subset of display options, see {@link #setDisplayOptions(int, int)}. - * - * @param options A combination of the bits defined by the DISPLAY_ constants - * defined in ActionBar. - */ - public abstract void setDisplayOptions(int options); - - /** - * Set selected display options. Only the options specified by mask will be changed. - * To change all display option bits at once, see {@link #setDisplayOptions(int)}. - * - *

Example: setDisplayOptions(0, DISPLAY_SHOW_HOME) will disable the - * {@link #DISPLAY_SHOW_HOME} option. - * setDisplayOptions(DISPLAY_SHOW_HOME, DISPLAY_SHOW_HOME | DISPLAY_USE_LOGO) - * will enable {@link #DISPLAY_SHOW_HOME} and disable {@link #DISPLAY_USE_LOGO}. - * - * @param options A combination of the bits defined by the DISPLAY_ constants - * defined in ActionBar. - * @param mask A bit mask declaring which display options should be changed. - */ - public abstract void setDisplayOptions(int options, int mask); - - /** - * Set whether to display the activity logo rather than the activity icon. - * A logo is often a wider, more detailed image. - * - *

To set several display options at once, see the setDisplayOptions methods. - * - * @param useLogo true to use the activity logo, false to use the activity icon. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setDisplayUseLogoEnabled(boolean useLogo); - - /** - * Set whether to include the application home affordance in the action bar. - * Home is presented as either an activity icon or logo. - * - *

To set several display options at once, see the setDisplayOptions methods. - * - * @param showHome true to show home, false otherwise. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setDisplayShowHomeEnabled(boolean showHome); - - /** - * Set whether home should be displayed as an "up" affordance. - * Set this to true if selecting "home" returns up by a single level in your UI - * rather than back to the top level or front page. - * - *

To set several display options at once, see the setDisplayOptions methods. - * - * @param showHomeAsUp true to show the user that selecting home will return one - * level up rather than to the top level of the app. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setDisplayHomeAsUpEnabled(boolean showHomeAsUp); - - /** - * Set whether an activity title/subtitle should be displayed. - * - *

To set several display options at once, see the setDisplayOptions methods. - * - * @param showTitle true to display a title/subtitle if present. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setDisplayShowTitleEnabled(boolean showTitle); - - /** - * Set whether a custom view should be displayed, if set. - * - *

To set several display options at once, see the setDisplayOptions methods. - * - * @param showCustom true if the currently set custom view should be displayed, false otherwise. - * - * @see #setDisplayOptions(int) - * @see #setDisplayOptions(int, int) - */ - public abstract void setDisplayShowCustomEnabled(boolean showCustom); - - /** - * Set the ActionBar's background. This will be used for the primary - * action bar. - * - * @param d Background drawable - * @see #setStackedBackgroundDrawable(Drawable) - * @see #setSplitBackgroundDrawable(Drawable) - */ - public abstract void setBackgroundDrawable(Drawable d); - - /** - * Set the ActionBar's stacked background. This will appear - * in the second row/stacked bar on some devices and configurations. - * - * @param d Background drawable for the stacked row - */ - public void setStackedBackgroundDrawable(Drawable d) { } - - /** - * Set the ActionBar's split background. This will appear in - * the split action bar containing menu-provided action buttons - * on some devices and configurations. - *

You can enable split action bar with {@link android.R.attr#uiOptions} - * - * @param d Background drawable for the split bar - */ - public void setSplitBackgroundDrawable(Drawable d) { } - - /** - * @return The current custom view. - */ - public abstract View getCustomView(); - - /** - * Returns the current ActionBar title in standard mode. - * Returns null if {@link #getNavigationMode()} would not return - * {@link #NAVIGATION_MODE_STANDARD}. - * - * @return The current ActionBar title or null. - */ - public abstract CharSequence getTitle(); - - /** - * Returns the current ActionBar subtitle in standard mode. - * Returns null if {@link #getNavigationMode()} would not return - * {@link #NAVIGATION_MODE_STANDARD}. - * - * @return The current ActionBar subtitle or null. - */ - public abstract CharSequence getSubtitle(); - - /** - * Returns the current navigation mode. The result will be one of: - *

    - *
  • {@link #NAVIGATION_MODE_STANDARD}
  • - *
  • {@link #NAVIGATION_MODE_LIST}
  • - *
  • {@link #NAVIGATION_MODE_TABS}
  • - *
- * - * @return The current navigation mode. - */ - public abstract int getNavigationMode(); - - /** - * Set the current navigation mode. - * - * @param mode The new mode to set. - * @see #NAVIGATION_MODE_STANDARD - * @see #NAVIGATION_MODE_LIST - * @see #NAVIGATION_MODE_TABS - */ - public abstract void setNavigationMode(int mode); - - /** - * @return The current set of display options. - */ - public abstract int getDisplayOptions(); - - /** - * Create and return a new {@link Tab}. - * This tab will not be included in the action bar until it is added. - * - *

Very often tabs will be used to switch between {@link Fragment} - * objects. Here is a typical implementation of such tabs:

- * - * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.java - * complete} - * - * @return A new Tab - * - * @see #addTab(Tab) - */ - public abstract Tab newTab(); - - /** - * Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list. - * If this is the first tab to be added it will become the selected tab. - * - * @param tab Tab to add - */ - public abstract void addTab(Tab tab); - - /** - * Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list. - * - * @param tab Tab to add - * @param setSelected True if the added tab should become the selected tab. - */ - public abstract void addTab(Tab tab, boolean setSelected); - - /** - * Add a tab for use in tabbed navigation mode. The tab will be inserted at - * position. If this is the first tab to be added it will become - * the selected tab. - * - * @param tab The tab to add - * @param position The new position of the tab - */ - public abstract void addTab(Tab tab, int position); - - /** - * Add a tab for use in tabbed navigation mode. The tab will be insterted at - * position. - * - * @param tab The tab to add - * @param position The new position of the tab - * @param setSelected True if the added tab should become the selected tab. - */ - public abstract void addTab(Tab tab, int position, boolean setSelected); - - /** - * Remove a tab from the action bar. If the removed tab was selected it will be deselected - * and another tab will be selected if present. - * - * @param tab The tab to remove - */ - public abstract void removeTab(Tab tab); - - /** - * Remove a tab from the action bar. If the removed tab was selected it will be deselected - * and another tab will be selected if present. - * - * @param position Position of the tab to remove - */ - public abstract void removeTabAt(int position); - - /** - * Remove all tabs from the action bar and deselect the current tab. - */ - public abstract void removeAllTabs(); - - /** - * Select the specified tab. If it is not a child of this action bar it will be added. - * - *

Note: If you want to select by index, use {@link #setSelectedNavigationItem(int)}.

- * - * @param tab Tab to select - */ - public abstract void selectTab(Tab tab); - - /** - * Returns the currently selected tab if in tabbed navigation mode and there is at least - * one tab present. - * - * @return The currently selected tab or null - */ - public abstract Tab getSelectedTab(); - - /** - * Returns the tab at the specified index. - * - * @param index Index value in the range 0-get - * @return - */ - public abstract Tab getTabAt(int index); - - /** - * Returns the number of tabs currently registered with the action bar. - * @return Tab count - */ - public abstract int getTabCount(); - - /** - * Retrieve the current height of the ActionBar. - * - * @return The ActionBar's height - */ - public abstract int getHeight(); - - /** - * Show the ActionBar if it is not currently showing. - * If the window hosting the ActionBar does not have the feature - * {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application - * content to fit the new space available. - */ - public abstract void show(); - - /** - * Hide the ActionBar if it is currently showing. - * If the window hosting the ActionBar does not have the feature - * {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application - * content to fit the new space available. - */ - public abstract void hide(); - - /** - * @return true if the ActionBar is showing, false otherwise. - */ - public abstract boolean isShowing(); - - /** - * Add a listener that will respond to menu visibility change events. - * - * @param listener The new listener to add - */ - public abstract void addOnMenuVisibilityListener(OnMenuVisibilityListener listener); - - /** - * Remove a menu visibility listener. This listener will no longer receive menu - * visibility change events. - * - * @param listener A listener to remove that was previously added - */ - public abstract void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener); - - /** - * Enable or disable the "home" button in the corner of the action bar. (Note that this - * is the application home/up affordance on the action bar, not the systemwide home - * button.) - * - *

This defaults to true for packages targeting < API 14. For packages targeting - * API 14 or greater, the application should call this method to enable interaction - * with the home/up affordance. - * - *

Setting the {@link #DISPLAY_HOME_AS_UP} display option will automatically enable - * the home button. - * - * @param enabled true to enable the home button, false to disable the home button. - */ - public void setHomeButtonEnabled(boolean enabled) { } - - /** - * Returns a {@link Context} with an appropriate theme for creating views that - * will appear in the action bar. If you are inflating or instantiating custom views - * that will appear in an action bar, you should use the Context returned by this method. - * (This includes adapters used for list navigation mode.) - * This will ensure that views contrast properly against the action bar. - * - * @return A themed Context for creating views - */ - public Context getThemedContext() { return null; } - - /** - * Listener interface for ActionBar navigation events. - */ - public interface OnNavigationListener { - /** - * This method is called whenever a navigation item in your action bar - * is selected. - * - * @param itemPosition Position of the item clicked. - * @param itemId ID of the item clicked. - * @return True if the event was handled, false otherwise. - */ - public boolean onNavigationItemSelected(int itemPosition, long itemId); - } - - /** - * Listener for receiving events when action bar menus are shown or hidden. - */ - public interface OnMenuVisibilityListener { - /** - * Called when an action bar menu is shown or hidden. Applications may want to use - * this to tune auto-hiding behavior for the action bar or pause/resume video playback, - * gameplay, or other activity within the main content area. - * - * @param isVisible True if an action bar menu is now visible, false if no action bar - * menus are visible. - */ - public void onMenuVisibilityChanged(boolean isVisible); - } - - /** - * A tab in the action bar. - * - *

Tabs manage the hiding and showing of {@link Fragment}s. - */ - public static abstract class Tab { - /** - * An invalid position for a tab. - * - * @see #getPosition() - */ - public static final int INVALID_POSITION = -1; - - /** - * Return the current position of this tab in the action bar. - * - * @return Current position, or {@link #INVALID_POSITION} if this tab is not currently in - * the action bar. - */ - public abstract int getPosition(); - - /** - * Return the icon associated with this tab. - * - * @return The tab's icon - */ - public abstract Drawable getIcon(); - - /** - * Return the text of this tab. - * - * @return The tab's text - */ - public abstract CharSequence getText(); - - /** - * Set the icon displayed on this tab. - * - * @param icon The drawable to use as an icon - * @return The current instance for call chaining - */ - public abstract Tab setIcon(Drawable icon); - - /** - * Set the icon displayed on this tab. - * - * @param resId Resource ID referring to the drawable to use as an icon - * @return The current instance for call chaining - */ - public abstract Tab setIcon(int resId); - - /** - * Set the text displayed on this tab. Text may be truncated if there is not - * room to display the entire string. - * - * @param text The text to display - * @return The current instance for call chaining - */ - public abstract Tab setText(CharSequence text); - - /** - * Set the text displayed on this tab. Text may be truncated if there is not - * room to display the entire string. - * - * @param resId A resource ID referring to the text that should be displayed - * @return The current instance for call chaining - */ - public abstract Tab setText(int resId); - - /** - * Set a custom view to be used for this tab. This overrides values set by - * {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}. - * - * @param view Custom view to be used as a tab. - * @return The current instance for call chaining - */ - public abstract Tab setCustomView(View view); - - /** - * Set a custom view to be used for this tab. This overrides values set by - * {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}. - * - * @param layoutResId A layout resource to inflate and use as a custom tab view - * @return The current instance for call chaining - */ - public abstract Tab setCustomView(int layoutResId); - - /** - * Retrieve a previously set custom view for this tab. - * - * @return The custom view set by {@link #setCustomView(View)}. - */ - public abstract View getCustomView(); - - /** - * Give this Tab an arbitrary object to hold for later use. - * - * @param obj Object to store - * @return The current instance for call chaining - */ - public abstract Tab setTag(Object obj); - - /** - * @return This Tab's tag object. - */ - public abstract Object getTag(); - - /** - * Set the {@link TabListener} that will handle switching to and from this tab. - * All tabs must have a TabListener set before being added to the ActionBar. - * - * @param listener Listener to handle tab selection events - * @return The current instance for call chaining - */ - public abstract Tab setTabListener(TabListener listener); - - /** - * Select this tab. Only valid if the tab has been added to the action bar. - */ - public abstract void select(); - - /** - * Set a description of this tab's content for use in accessibility support. - * If no content description is provided the title will be used. - * - * @param resId A resource ID referring to the description text - * @return The current instance for call chaining - * @see #setContentDescription(CharSequence) - * @see #getContentDescription() - */ - public abstract Tab setContentDescription(int resId); - - /** - * Set a description of this tab's content for use in accessibility support. - * If no content description is provided the title will be used. - * - * @param contentDesc Description of this tab's content - * @return The current instance for call chaining - * @see #setContentDescription(int) - * @see #getContentDescription() - */ - public abstract Tab setContentDescription(CharSequence contentDesc); - - /** - * Gets a brief description of this tab's content for use in accessibility support. - * - * @return Description of this tab's content - * @see #setContentDescription(CharSequence) - * @see #setContentDescription(int) - */ - public abstract CharSequence getContentDescription(); - } - - /** - * Callback interface invoked when a tab is focused, unfocused, added, or removed. - */ - public interface TabListener { - /** - * Called when a tab enters the selected state. - * - * @param tab The tab that was selected - * @param ft A {@link FragmentTransaction} for queuing fragment operations to execute - * during a tab switch. The previous tab's unselect and this tab's select will be - * executed in a single transaction. This FragmentTransaction does not support - * being added to the back stack. - */ - public void onTabSelected(Tab tab, FragmentTransaction ft); - - /** - * Called when a tab exits the selected state. - * - * @param tab The tab that was unselected - * @param ft A {@link FragmentTransaction} for queuing fragment operations to execute - * during a tab switch. This tab's unselect and the newly selected tab's select - * will be executed in a single transaction. This FragmentTransaction does not - * support being added to the back stack. - */ - public void onTabUnselected(Tab tab, FragmentTransaction ft); - - /** - * Called when a tab that is already selected is chosen again by the user. - * Some applications may use this action to return to the top level of a category. - * - * @param tab The tab that was reselected. - * @param ft A {@link FragmentTransaction} for queuing fragment operations to execute - * once this method returns. This FragmentTransaction does not support - * being added to the back stack. - */ - public void onTabReselected(Tab tab, FragmentTransaction ft); - } - - /** - * Per-child layout information associated with action bar custom views. - * - * @attr ref android.R.styleable#ActionBar_LayoutParams_layout_gravity - */ - public static class LayoutParams extends MarginLayoutParams { - /** - * Gravity for the view associated with these LayoutParams. - * - * @see android.view.Gravity - */ - @ViewDebug.ExportedProperty(mapping = { - @ViewDebug.IntToString(from = -1, to = "NONE"), - @ViewDebug.IntToString(from = Gravity.NO_GRAVITY, to = "NONE"), - @ViewDebug.IntToString(from = Gravity.TOP, to = "TOP"), - @ViewDebug.IntToString(from = Gravity.BOTTOM, to = "BOTTOM"), - @ViewDebug.IntToString(from = Gravity.LEFT, to = "LEFT"), - @ViewDebug.IntToString(from = Gravity.RIGHT, to = "RIGHT"), - @ViewDebug.IntToString(from = Gravity.CENTER_VERTICAL, to = "CENTER_VERTICAL"), - @ViewDebug.IntToString(from = Gravity.FILL_VERTICAL, to = "FILL_VERTICAL"), - @ViewDebug.IntToString(from = Gravity.CENTER_HORIZONTAL, to = "CENTER_HORIZONTAL"), - @ViewDebug.IntToString(from = Gravity.FILL_HORIZONTAL, to = "FILL_HORIZONTAL"), - @ViewDebug.IntToString(from = Gravity.CENTER, to = "CENTER"), - @ViewDebug.IntToString(from = Gravity.FILL, to = "FILL") - }) - public int gravity = -1; - - public LayoutParams(Context c, AttributeSet attrs) { - super(c, attrs); - } - - public LayoutParams(int width, int height) { - super(width, height); - this.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT; - } - - public LayoutParams(int width, int height, int gravity) { - super(width, height); - this.gravity = gravity; - } - - public LayoutParams(int gravity) { - this(WRAP_CONTENT, FILL_PARENT, gravity); - } - - public LayoutParams(LayoutParams source) { - super(source); - - this.gravity = source.gravity; - } - - public LayoutParams(ViewGroup.LayoutParams source) { - super(source); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockActivity.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockActivity.java deleted file mode 100644 index 9cb57e95..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockActivity.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.actionbarsherlock.app; - -import android.app.Activity; -import android.content.res.Configuration; -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.View; -import android.view.Window; -import android.view.ViewGroup.LayoutParams; -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; -import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; -import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; -import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -public abstract class SherlockActivity extends Activity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { - private ActionBarSherlock mSherlock; - - protected final ActionBarSherlock getSherlock() { - if (mSherlock == null) { - mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); - } - return mSherlock; - } - - - /////////////////////////////////////////////////////////////////////////// - // Action bar and mode - /////////////////////////////////////////////////////////////////////////// - - public ActionBar getSupportActionBar() { - return getSherlock().getActionBar(); - } - - public ActionMode startActionMode(ActionMode.Callback callback) { - return getSherlock().startActionMode(callback); - } - - @Override - public void onActionModeStarted(ActionMode mode) {} - - @Override - public void onActionModeFinished(ActionMode mode) {} - - - /////////////////////////////////////////////////////////////////////////// - // General lifecycle/callback dispatching - /////////////////////////////////////////////////////////////////////////// - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - getSherlock().dispatchConfigurationChanged(newConfig); - } - - @Override - protected void onPostResume() { - super.onPostResume(); - getSherlock().dispatchPostResume(); - } - - @Override - protected void onPause() { - getSherlock().dispatchPause(); - super.onPause(); - } - - @Override - protected void onStop() { - getSherlock().dispatchStop(); - super.onStop(); - } - - @Override - protected void onDestroy() { - getSherlock().dispatchDestroy(); - super.onDestroy(); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - getSherlock().dispatchPostCreate(savedInstanceState); - super.onPostCreate(savedInstanceState); - } - - @Override - protected void onTitleChanged(CharSequence title, int color) { - getSherlock().dispatchTitleChanged(title, color); - super.onTitleChanged(title, color); - } - - @Override - public final boolean onMenuOpened(int featureId, android.view.Menu menu) { - if (getSherlock().dispatchMenuOpened(featureId, menu)) { - return true; - } - return super.onMenuOpened(featureId, menu); - } - - @Override - public void onPanelClosed(int featureId, android.view.Menu menu) { - getSherlock().dispatchPanelClosed(featureId, menu); - super.onPanelClosed(featureId, menu); - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (getSherlock().dispatchKeyEvent(event)) { - return true; - } - return super.dispatchKeyEvent(event); - } - - - /////////////////////////////////////////////////////////////////////////// - // Native menu handling - /////////////////////////////////////////////////////////////////////////// - - public MenuInflater getSupportMenuInflater() { - return getSherlock().getMenuInflater(); - } - - public void invalidateOptionsMenu() { - getSherlock().dispatchInvalidateOptionsMenu(); - } - - public void supportInvalidateOptionsMenu() { - invalidateOptionsMenu(); - } - - @Override - public final boolean onCreateOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchCreateOptionsMenu(menu); - } - - @Override - public final boolean onPrepareOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchPrepareOptionsMenu(menu); - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return getSherlock().dispatchOptionsItemSelected(item); - } - - @Override - public void openOptionsMenu() { - if (!getSherlock().dispatchOpenOptionsMenu()) { - super.openOptionsMenu(); - } - } - - @Override - public void closeOptionsMenu() { - if (!getSherlock().dispatchCloseOptionsMenu()) { - super.closeOptionsMenu(); - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Sherlock menu handling - /////////////////////////////////////////////////////////////////////////// - - @Override - public boolean onCreatePanelMenu(int featureId, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onCreateOptionsMenu(menu); - } - return false; - } - - public boolean onCreateOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onPreparePanel(int featureId, View view, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onPrepareOptionsMenu(menu); - } - return false; - } - - public boolean onPrepareOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onOptionsItemSelected(item); - } - return false; - } - - public boolean onOptionsItemSelected(MenuItem item) { - return false; - } - - - /////////////////////////////////////////////////////////////////////////// - // Content - /////////////////////////////////////////////////////////////////////////// - - @Override - public void addContentView(View view, LayoutParams params) { - getSherlock().addContentView(view, params); - } - - @Override - public void setContentView(int layoutResId) { - getSherlock().setContentView(layoutResId); - } - - @Override - public void setContentView(View view, LayoutParams params) { - getSherlock().setContentView(view, params); - } - - @Override - public void setContentView(View view) { - getSherlock().setContentView(view); - } - - public void requestWindowFeature(long featureId) { - getSherlock().requestFeature((int)featureId); - } - - - /////////////////////////////////////////////////////////////////////////// - // Progress Indication - /////////////////////////////////////////////////////////////////////////// - - public void setSupportProgress(int progress) { - getSherlock().setProgress(progress); - } - - public void setSupportProgressBarIndeterminate(boolean indeterminate) { - getSherlock().setProgressBarIndeterminate(indeterminate); - } - - public void setSupportProgressBarIndeterminateVisibility(boolean visible) { - getSherlock().setProgressBarIndeterminateVisibility(visible); - } - - public void setSupportProgressBarVisibility(boolean visible) { - getSherlock().setProgressBarVisibility(visible); - } - - public void setSupportSecondaryProgress(int secondaryProgress) { - getSherlock().setSecondaryProgress(secondaryProgress); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockDialogFragment.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockDialogFragment.java deleted file mode 100644 index a7c856bf..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockDialogFragment.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.actionbarsherlock.app; - -import android.app.Activity; -import android.support.v4.app.DialogFragment; -import com.actionbarsherlock.internal.view.menu.MenuItemWrapper; -import com.actionbarsherlock.internal.view.menu.MenuWrapper; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener; -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener; -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener; - -public class SherlockDialogFragment extends DialogFragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener { - private SherlockFragmentActivity mActivity; - - public SherlockFragmentActivity getSherlockActivity() { - return mActivity; - } - - @Override - public void onAttach(Activity activity) { - if (!(activity instanceof SherlockFragmentActivity)) { - throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity."); - } - mActivity = (SherlockFragmentActivity)activity; - - super.onAttach(activity); - } - - @Override - public void onDetach() { - mActivity = null; - super.onDetach(); - } - - @Override - public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) { - onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater()); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - //Nothing to see here. - } - - @Override - public final void onPrepareOptionsMenu(android.view.Menu menu) { - onPrepareOptionsMenu(new MenuWrapper(menu)); - } - - @Override - public void onPrepareOptionsMenu(Menu menu) { - //Nothing to see here. - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return onOptionsItemSelected(new MenuItemWrapper(item)); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - //Nothing to see here. - return false; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockExpandableListActivity.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockExpandableListActivity.java deleted file mode 100644 index 078f9b0c..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockExpandableListActivity.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.actionbarsherlock.app; - -import android.app.ExpandableListActivity; -import android.content.res.Configuration; -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup.LayoutParams; -import android.view.Window; -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; -import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; -import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; -import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -public abstract class SherlockExpandableListActivity extends ExpandableListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { - private ActionBarSherlock mSherlock; - - protected final ActionBarSherlock getSherlock() { - if (mSherlock == null) { - mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); - } - return mSherlock; - } - - - /////////////////////////////////////////////////////////////////////////// - // Action bar and mode - /////////////////////////////////////////////////////////////////////////// - - public ActionBar getSupportActionBar() { - return getSherlock().getActionBar(); - } - - public ActionMode startActionMode(ActionMode.Callback callback) { - return getSherlock().startActionMode(callback); - } - - @Override - public void onActionModeStarted(ActionMode mode) {} - - @Override - public void onActionModeFinished(ActionMode mode) {} - - - /////////////////////////////////////////////////////////////////////////// - // General lifecycle/callback dispatching - /////////////////////////////////////////////////////////////////////////// - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - getSherlock().dispatchConfigurationChanged(newConfig); - } - - @Override - protected void onPostResume() { - super.onPostResume(); - getSherlock().dispatchPostResume(); - } - - @Override - protected void onPause() { - getSherlock().dispatchPause(); - super.onPause(); - } - - @Override - protected void onStop() { - getSherlock().dispatchStop(); - super.onStop(); - } - - @Override - protected void onDestroy() { - getSherlock().dispatchDestroy(); - super.onDestroy(); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - getSherlock().dispatchPostCreate(savedInstanceState); - super.onPostCreate(savedInstanceState); - } - - @Override - protected void onTitleChanged(CharSequence title, int color) { - getSherlock().dispatchTitleChanged(title, color); - super.onTitleChanged(title, color); - } - - @Override - public final boolean onMenuOpened(int featureId, android.view.Menu menu) { - if (getSherlock().dispatchMenuOpened(featureId, menu)) { - return true; - } - return super.onMenuOpened(featureId, menu); - } - - @Override - public void onPanelClosed(int featureId, android.view.Menu menu) { - getSherlock().dispatchPanelClosed(featureId, menu); - super.onPanelClosed(featureId, menu); - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (getSherlock().dispatchKeyEvent(event)) { - return true; - } - return super.dispatchKeyEvent(event); - } - - - /////////////////////////////////////////////////////////////////////////// - // Native menu handling - /////////////////////////////////////////////////////////////////////////// - - public MenuInflater getSupportMenuInflater() { - return getSherlock().getMenuInflater(); - } - - public void invalidateOptionsMenu() { - getSherlock().dispatchInvalidateOptionsMenu(); - } - - public void supportInvalidateOptionsMenu() { - invalidateOptionsMenu(); - } - - @Override - public final boolean onCreateOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchCreateOptionsMenu(menu); - } - - @Override - public final boolean onPrepareOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchPrepareOptionsMenu(menu); - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return getSherlock().dispatchOptionsItemSelected(item); - } - - @Override - public void openOptionsMenu() { - if (!getSherlock().dispatchOpenOptionsMenu()) { - super.openOptionsMenu(); - } - } - - @Override - public void closeOptionsMenu() { - if (!getSherlock().dispatchCloseOptionsMenu()) { - super.closeOptionsMenu(); - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Sherlock menu handling - /////////////////////////////////////////////////////////////////////////// - - @Override - public boolean onCreatePanelMenu(int featureId, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onCreateOptionsMenu(menu); - } - return false; - } - - public boolean onCreateOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onPreparePanel(int featureId, View view, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onPrepareOptionsMenu(menu); - } - return false; - } - - public boolean onPrepareOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onOptionsItemSelected(item); - } - return false; - } - - public boolean onOptionsItemSelected(MenuItem item) { - return false; - } - - - /////////////////////////////////////////////////////////////////////////// - // Content - /////////////////////////////////////////////////////////////////////////// - - @Override - public void addContentView(View view, LayoutParams params) { - getSherlock().addContentView(view, params); - } - - @Override - public void setContentView(int layoutResId) { - getSherlock().setContentView(layoutResId); - } - - @Override - public void setContentView(View view, LayoutParams params) { - getSherlock().setContentView(view, params); - } - - @Override - public void setContentView(View view) { - getSherlock().setContentView(view); - } - - public void requestWindowFeature(long featureId) { - getSherlock().requestFeature((int)featureId); - } - - - /////////////////////////////////////////////////////////////////////////// - // Progress Indication - /////////////////////////////////////////////////////////////////////////// - - public void setSupportProgress(int progress) { - getSherlock().setProgress(progress); - } - - public void setSupportProgressBarIndeterminate(boolean indeterminate) { - getSherlock().setProgressBarIndeterminate(indeterminate); - } - - public void setSupportProgressBarIndeterminateVisibility(boolean visible) { - getSherlock().setProgressBarIndeterminateVisibility(visible); - } - - public void setSupportProgressBarVisibility(boolean visible) { - getSherlock().setProgressBarVisibility(visible); - } - - public void setSupportSecondaryProgress(int secondaryProgress) { - getSherlock().setSecondaryProgress(secondaryProgress); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragment.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragment.java deleted file mode 100644 index 0f24e9c8..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragment.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.actionbarsherlock.app; - -import android.app.Activity; -import android.support.v4.app.Fragment; -import com.actionbarsherlock.internal.view.menu.MenuItemWrapper; -import com.actionbarsherlock.internal.view.menu.MenuWrapper; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener; -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener; -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener; - -public class SherlockFragment extends Fragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener { - private SherlockFragmentActivity mActivity; - - public SherlockFragmentActivity getSherlockActivity() { - return mActivity; - } - - @Override - public void onAttach(Activity activity) { - if (!(activity instanceof SherlockFragmentActivity)) { - throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity."); - } - mActivity = (SherlockFragmentActivity)activity; - - super.onAttach(activity); - } - - @Override - public void onDetach() { - mActivity = null; - super.onDetach(); - } - - @Override - public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) { - onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater()); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - //Nothing to see here. - } - - @Override - public final void onPrepareOptionsMenu(android.view.Menu menu) { - onPrepareOptionsMenu(new MenuWrapper(menu)); - } - - @Override - public void onPrepareOptionsMenu(Menu menu) { - //Nothing to see here. - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return onOptionsItemSelected(new MenuItemWrapper(item)); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - //Nothing to see here. - return false; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragmentActivity.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragmentActivity.java deleted file mode 100644 index 5cd13ba7..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragmentActivity.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.actionbarsherlock.app; - -import android.content.res.Configuration; -import android.os.Bundle; -import android.support.v4.app._ActionBarSherlockTrojanHorse; -import android.util.Log; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup.LayoutParams; -import android.view.Window; -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -import static com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; -import static com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; - -/** @see {@link _ActionBarSherlockTrojanHorse} */ -public class SherlockFragmentActivity extends _ActionBarSherlockTrojanHorse implements OnActionModeStartedListener, OnActionModeFinishedListener { - private static final boolean DEBUG = false; - private static final String TAG = "SherlockFragmentActivity"; - - private ActionBarSherlock mSherlock; - private boolean mIgnoreNativeCreate = false; - private boolean mIgnoreNativePrepare = false; - private boolean mIgnoreNativeSelected = false; - - protected final ActionBarSherlock getSherlock() { - if (mSherlock == null) { - mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); - } - return mSherlock; - } - - - /////////////////////////////////////////////////////////////////////////// - // Action bar and mode - /////////////////////////////////////////////////////////////////////////// - - public ActionBar getSupportActionBar() { - return getSherlock().getActionBar(); - } - - public ActionMode startActionMode(ActionMode.Callback callback) { - return getSherlock().startActionMode(callback); - } - - @Override - public void onActionModeStarted(ActionMode mode) {} - - @Override - public void onActionModeFinished(ActionMode mode) {} - - - /////////////////////////////////////////////////////////////////////////// - // General lifecycle/callback dispatching - /////////////////////////////////////////////////////////////////////////// - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - getSherlock().dispatchConfigurationChanged(newConfig); - } - - @Override - protected void onPostResume() { - super.onPostResume(); - getSherlock().dispatchPostResume(); - } - - @Override - protected void onPause() { - getSherlock().dispatchPause(); - super.onPause(); - } - - @Override - protected void onStop() { - getSherlock().dispatchStop(); - super.onStop(); - } - - @Override - protected void onDestroy() { - getSherlock().dispatchDestroy(); - super.onDestroy(); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - getSherlock().dispatchPostCreate(savedInstanceState); - super.onPostCreate(savedInstanceState); - } - - @Override - protected void onTitleChanged(CharSequence title, int color) { - getSherlock().dispatchTitleChanged(title, color); - super.onTitleChanged(title, color); - } - - @Override - public final boolean onMenuOpened(int featureId, android.view.Menu menu) { - if (getSherlock().dispatchMenuOpened(featureId, menu)) { - return true; - } - return super.onMenuOpened(featureId, menu); - } - - @Override - public void onPanelClosed(int featureId, android.view.Menu menu) { - getSherlock().dispatchPanelClosed(featureId, menu); - super.onPanelClosed(featureId, menu); - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (getSherlock().dispatchKeyEvent(event)) { - return true; - } - return super.dispatchKeyEvent(event); - } - - - /////////////////////////////////////////////////////////////////////////// - // Native menu handling - /////////////////////////////////////////////////////////////////////////// - - public MenuInflater getSupportMenuInflater() { - if (DEBUG) Log.d(TAG, "[getSupportMenuInflater]"); - - return getSherlock().getMenuInflater(); - } - - public void invalidateOptionsMenu() { - if (DEBUG) Log.d(TAG, "[invalidateOptionsMenu]"); - - getSherlock().dispatchInvalidateOptionsMenu(); - } - - public void supportInvalidateOptionsMenu() { - if (DEBUG) Log.d(TAG, "[supportInvalidateOptionsMenu]"); - - invalidateOptionsMenu(); - } - - @Override - public final boolean onCreatePanelMenu(int featureId, android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu); - - if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeCreate) { - mIgnoreNativeCreate = true; - boolean result = getSherlock().dispatchCreateOptionsMenu(menu); - mIgnoreNativeCreate = false; - - if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result); - return result; - } - return super.onCreatePanelMenu(featureId, menu); - } - - @Override - public final boolean onCreateOptionsMenu(android.view.Menu menu) { - return true; - } - - @Override - public final boolean onPreparePanel(int featureId, View view, android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + ", menu: " + menu); - - if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativePrepare) { - mIgnoreNativePrepare = true; - boolean result = getSherlock().dispatchPrepareOptionsMenu(menu); - mIgnoreNativePrepare = false; - - if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result); - return result; - } - return super.onPreparePanel(featureId, view, menu); - } - - @Override - public final boolean onPrepareOptionsMenu(android.view.Menu menu) { - return true; - } - - @Override - public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) { - if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item); - - if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeSelected) { - mIgnoreNativeSelected = true; - boolean result = getSherlock().dispatchOptionsItemSelected(item); - mIgnoreNativeSelected = false; - - if (DEBUG) Log.d(TAG, "[onMenuItemSelected] returning " + result); - return result; - } - return super.onMenuItemSelected(featureId, item); - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return false; - } - - @Override - public void openOptionsMenu() { - if (!getSherlock().dispatchOpenOptionsMenu()) { - super.openOptionsMenu(); - } - } - - @Override - public void closeOptionsMenu() { - if (!getSherlock().dispatchCloseOptionsMenu()) { - super.closeOptionsMenu(); - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Sherlock menu handling - /////////////////////////////////////////////////////////////////////////// - - public boolean onCreateOptionsMenu(Menu menu) { - return true; - } - - public boolean onPrepareOptionsMenu(Menu menu) { - return true; - } - - public boolean onOptionsItemSelected(MenuItem item) { - return false; - } - - - /////////////////////////////////////////////////////////////////////////// - // Content - /////////////////////////////////////////////////////////////////////////// - - @Override - public void addContentView(View view, LayoutParams params) { - getSherlock().addContentView(view, params); - } - - @Override - public void setContentView(int layoutResId) { - getSherlock().setContentView(layoutResId); - } - - @Override - public void setContentView(View view, LayoutParams params) { - getSherlock().setContentView(view, params); - } - - @Override - public void setContentView(View view) { - getSherlock().setContentView(view); - } - - public void requestWindowFeature(long featureId) { - getSherlock().requestFeature((int)featureId); - } - - - /////////////////////////////////////////////////////////////////////////// - // Progress Indication - /////////////////////////////////////////////////////////////////////////// - - public void setSupportProgress(int progress) { - getSherlock().setProgress(progress); - } - - public void setSupportProgressBarIndeterminate(boolean indeterminate) { - getSherlock().setProgressBarIndeterminate(indeterminate); - } - - public void setSupportProgressBarIndeterminateVisibility(boolean visible) { - getSherlock().setProgressBarIndeterminateVisibility(visible); - } - - public void setSupportProgressBarVisibility(boolean visible) { - getSherlock().setProgressBarVisibility(visible); - } - - public void setSupportSecondaryProgress(int secondaryProgress) { - getSherlock().setSecondaryProgress(secondaryProgress); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListActivity.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListActivity.java deleted file mode 100644 index 00c00fee..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListActivity.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.actionbarsherlock.app; - -import android.app.ListActivity; -import android.content.res.Configuration; -import android.os.Bundle; -import android.view.KeyEvent; -import android.view.View; -import android.view.Window; -import android.view.ViewGroup.LayoutParams; -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; -import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; -import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; -import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -public abstract class SherlockListActivity extends ListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { - private ActionBarSherlock mSherlock; - - protected final ActionBarSherlock getSherlock() { - if (mSherlock == null) { - mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); - } - return mSherlock; - } - - - /////////////////////////////////////////////////////////////////////////// - // Action bar and mode - /////////////////////////////////////////////////////////////////////////// - - public ActionBar getSupportActionBar() { - return getSherlock().getActionBar(); - } - - public ActionMode startActionMode(ActionMode.Callback callback) { - return getSherlock().startActionMode(callback); - } - - @Override - public void onActionModeStarted(ActionMode mode) {} - - @Override - public void onActionModeFinished(ActionMode mode) {} - - - /////////////////////////////////////////////////////////////////////////// - // General lifecycle/callback dispatching - /////////////////////////////////////////////////////////////////////////// - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - getSherlock().dispatchConfigurationChanged(newConfig); - } - - @Override - protected void onPostResume() { - super.onPostResume(); - getSherlock().dispatchPostResume(); - } - - @Override - protected void onPause() { - getSherlock().dispatchPause(); - super.onPause(); - } - - @Override - protected void onStop() { - getSherlock().dispatchStop(); - super.onStop(); - } - - @Override - protected void onDestroy() { - getSherlock().dispatchDestroy(); - super.onDestroy(); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - getSherlock().dispatchPostCreate(savedInstanceState); - super.onPostCreate(savedInstanceState); - } - - @Override - protected void onTitleChanged(CharSequence title, int color) { - getSherlock().dispatchTitleChanged(title, color); - super.onTitleChanged(title, color); - } - - @Override - public final boolean onMenuOpened(int featureId, android.view.Menu menu) { - if (getSherlock().dispatchMenuOpened(featureId, menu)) { - return true; - } - return super.onMenuOpened(featureId, menu); - } - - @Override - public void onPanelClosed(int featureId, android.view.Menu menu) { - getSherlock().dispatchPanelClosed(featureId, menu); - super.onPanelClosed(featureId, menu); - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (getSherlock().dispatchKeyEvent(event)) { - return true; - } - return super.dispatchKeyEvent(event); - } - - - /////////////////////////////////////////////////////////////////////////// - // Native menu handling - /////////////////////////////////////////////////////////////////////////// - - public MenuInflater getSupportMenuInflater() { - return getSherlock().getMenuInflater(); - } - - public void invalidateOptionsMenu() { - getSherlock().dispatchInvalidateOptionsMenu(); - } - - public void supportInvalidateOptionsMenu() { - invalidateOptionsMenu(); - } - - @Override - public final boolean onCreateOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchCreateOptionsMenu(menu); - } - - @Override - public final boolean onPrepareOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchPrepareOptionsMenu(menu); - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return getSherlock().dispatchOptionsItemSelected(item); - } - - @Override - public void openOptionsMenu() { - if (!getSherlock().dispatchOpenOptionsMenu()) { - super.openOptionsMenu(); - } - } - - @Override - public void closeOptionsMenu() { - if (!getSherlock().dispatchCloseOptionsMenu()) { - super.closeOptionsMenu(); - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Sherlock menu handling - /////////////////////////////////////////////////////////////////////////// - - @Override - public boolean onCreatePanelMenu(int featureId, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onCreateOptionsMenu(menu); - } - return false; - } - - public boolean onCreateOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onPreparePanel(int featureId, View view, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onPrepareOptionsMenu(menu); - } - return false; - } - - public boolean onPrepareOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onOptionsItemSelected(item); - } - return false; - } - - public boolean onOptionsItemSelected(MenuItem item) { - return false; - } - - - /////////////////////////////////////////////////////////////////////////// - // Content - /////////////////////////////////////////////////////////////////////////// - - @Override - public void addContentView(View view, LayoutParams params) { - getSherlock().addContentView(view, params); - } - - @Override - public void setContentView(int layoutResId) { - getSherlock().setContentView(layoutResId); - } - - @Override - public void setContentView(View view, LayoutParams params) { - getSherlock().setContentView(view, params); - } - - @Override - public void setContentView(View view) { - getSherlock().setContentView(view); - } - - public void requestWindowFeature(long featureId) { - getSherlock().requestFeature((int)featureId); - } - - - /////////////////////////////////////////////////////////////////////////// - // Progress Indication - /////////////////////////////////////////////////////////////////////////// - - public void setSupportProgress(int progress) { - getSherlock().setProgress(progress); - } - - public void setSupportProgressBarIndeterminate(boolean indeterminate) { - getSherlock().setProgressBarIndeterminate(indeterminate); - } - - public void setSupportProgressBarIndeterminateVisibility(boolean visible) { - getSherlock().setProgressBarIndeterminateVisibility(visible); - } - - public void setSupportProgressBarVisibility(boolean visible) { - getSherlock().setProgressBarVisibility(visible); - } - - public void setSupportSecondaryProgress(int secondaryProgress) { - getSherlock().setSecondaryProgress(secondaryProgress); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListFragment.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListFragment.java deleted file mode 100644 index 13ca3c49..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListFragment.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.actionbarsherlock.app; - -import android.app.Activity; -import android.support.v4.app.ListFragment; -import com.actionbarsherlock.internal.view.menu.MenuItemWrapper; -import com.actionbarsherlock.internal.view.menu.MenuWrapper; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener; -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener; -import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener; - -public class SherlockListFragment extends ListFragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener { - private SherlockFragmentActivity mActivity; - - public SherlockFragmentActivity getSherlockActivity() { - return mActivity; - } - - @Override - public void onAttach(Activity activity) { - if (!(activity instanceof SherlockFragmentActivity)) { - throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity."); - } - mActivity = (SherlockFragmentActivity)activity; - - super.onAttach(activity); - } - - @Override - public void onDetach() { - mActivity = null; - super.onDetach(); - } - - @Override - public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) { - onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater()); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - //Nothing to see here. - } - - @Override - public final void onPrepareOptionsMenu(android.view.Menu menu) { - onPrepareOptionsMenu(new MenuWrapper(menu)); - } - - @Override - public void onPrepareOptionsMenu(Menu menu) { - //Nothing to see here. - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return onOptionsItemSelected(new MenuItemWrapper(item)); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - //Nothing to see here. - return false; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockPreferenceActivity.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockPreferenceActivity.java deleted file mode 100644 index 4f80be51..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockPreferenceActivity.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.actionbarsherlock.app; - -import android.content.res.Configuration; -import android.os.Bundle; -import android.preference.PreferenceActivity; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup.LayoutParams; -import android.view.Window; -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; -import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; -import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; -import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; -import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -public abstract class SherlockPreferenceActivity extends PreferenceActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { - private ActionBarSherlock mSherlock; - - protected final ActionBarSherlock getSherlock() { - if (mSherlock == null) { - mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); - } - return mSherlock; - } - - - /////////////////////////////////////////////////////////////////////////// - // Action bar and mode - /////////////////////////////////////////////////////////////////////////// - - public ActionBar getSupportActionBar() { - return getSherlock().getActionBar(); - } - - public ActionMode startActionMode(ActionMode.Callback callback) { - return getSherlock().startActionMode(callback); - } - - @Override - public void onActionModeStarted(ActionMode mode) {} - - @Override - public void onActionModeFinished(ActionMode mode) {} - - - /////////////////////////////////////////////////////////////////////////// - // General lifecycle/callback dispatching - /////////////////////////////////////////////////////////////////////////// - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - getSherlock().dispatchConfigurationChanged(newConfig); - } - - @Override - protected void onPostResume() { - super.onPostResume(); - getSherlock().dispatchPostResume(); - } - - @Override - protected void onPause() { - getSherlock().dispatchPause(); - super.onPause(); - } - - @Override - protected void onStop() { - getSherlock().dispatchStop(); - super.onStop(); - } - - @Override - protected void onDestroy() { - getSherlock().dispatchDestroy(); - super.onDestroy(); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - getSherlock().dispatchPostCreate(savedInstanceState); - super.onPostCreate(savedInstanceState); - } - - @Override - protected void onTitleChanged(CharSequence title, int color) { - getSherlock().dispatchTitleChanged(title, color); - super.onTitleChanged(title, color); - } - - @Override - public final boolean onMenuOpened(int featureId, android.view.Menu menu) { - if (getSherlock().dispatchMenuOpened(featureId, menu)) { - return true; - } - return super.onMenuOpened(featureId, menu); - } - - @Override - public void onPanelClosed(int featureId, android.view.Menu menu) { - getSherlock().dispatchPanelClosed(featureId, menu); - super.onPanelClosed(featureId, menu); - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (getSherlock().dispatchKeyEvent(event)) { - return true; - } - return super.dispatchKeyEvent(event); - } - - - /////////////////////////////////////////////////////////////////////////// - // Native menu handling - /////////////////////////////////////////////////////////////////////////// - - public MenuInflater getSupportMenuInflater() { - return getSherlock().getMenuInflater(); - } - - public void invalidateOptionsMenu() { - getSherlock().dispatchInvalidateOptionsMenu(); - } - - public void supportInvalidateOptionsMenu() { - invalidateOptionsMenu(); - } - - @Override - public final boolean onCreateOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchCreateOptionsMenu(menu); - } - - @Override - public final boolean onPrepareOptionsMenu(android.view.Menu menu) { - return getSherlock().dispatchPrepareOptionsMenu(menu); - } - - @Override - public final boolean onOptionsItemSelected(android.view.MenuItem item) { - return getSherlock().dispatchOptionsItemSelected(item); - } - - @Override - public void openOptionsMenu() { - if (!getSherlock().dispatchOpenOptionsMenu()) { - super.openOptionsMenu(); - } - } - - @Override - public void closeOptionsMenu() { - if (!getSherlock().dispatchCloseOptionsMenu()) { - super.closeOptionsMenu(); - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Sherlock menu handling - /////////////////////////////////////////////////////////////////////////// - - @Override - public boolean onCreatePanelMenu(int featureId, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onCreateOptionsMenu(menu); - } - return false; - } - - public boolean onCreateOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onPreparePanel(int featureId, View view, Menu menu) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onPrepareOptionsMenu(menu); - } - return false; - } - - public boolean onPrepareOptionsMenu(Menu menu) { - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - if (featureId == Window.FEATURE_OPTIONS_PANEL) { - return onOptionsItemSelected(item); - } - return false; - } - - public boolean onOptionsItemSelected(MenuItem item) { - return false; - } - - - /////////////////////////////////////////////////////////////////////////// - // Content - /////////////////////////////////////////////////////////////////////////// - - @Override - public void addContentView(View view, LayoutParams params) { - getSherlock().addContentView(view, params); - } - - @Override - public void setContentView(int layoutResId) { - getSherlock().setContentView(layoutResId); - } - - @Override - public void setContentView(View view, LayoutParams params) { - getSherlock().setContentView(view, params); - } - - @Override - public void setContentView(View view) { - getSherlock().setContentView(view); - } - - public void requestWindowFeature(long featureId) { - getSherlock().requestFeature((int)featureId); - } - - - /////////////////////////////////////////////////////////////////////////// - // Progress Indication - /////////////////////////////////////////////////////////////////////////// - - public void setSupportProgress(int progress) { - getSherlock().setProgress(progress); - } - - public void setSupportProgressBarIndeterminate(boolean indeterminate) { - getSherlock().setProgressBarIndeterminate(indeterminate); - } - - public void setSupportProgressBarIndeterminateVisibility(boolean visible) { - getSherlock().setProgressBarIndeterminateVisibility(visible); - } - - public void setSupportProgressBarVisibility(boolean visible) { - getSherlock().setProgressBarVisibility(visible); - } - - public void setSupportSecondaryProgress(int secondaryProgress) { - getSherlock().setSecondaryProgress(secondaryProgress); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockCompat.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockCompat.java deleted file mode 100644 index 05353d28..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockCompat.java +++ /dev/null @@ -1,1207 +0,0 @@ -package com.actionbarsherlock.internal; - -import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; -import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import org.xmlpull.v1.XmlPullParser; -import android.app.Activity; -import android.content.Context; -import android.content.pm.ActivityInfo; -import android.content.res.AssetManager; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.content.res.XmlResourceParser; -import android.os.Bundle; -import android.util.AndroidRuntimeException; -import android.util.Log; -import android.util.TypedValue; -import android.view.ContextThemeWrapper; -import android.view.KeyCharacterMap; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewStub; -import android.view.Window; -import android.view.accessibility.AccessibilityEvent; -import android.view.animation.Animation; -import android.view.animation.AnimationUtils; -import android.widget.FrameLayout; -import android.widget.TextView; -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.R; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.internal.app.ActionBarImpl; -import com.actionbarsherlock.internal.view.StandaloneActionMode; -import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; -import com.actionbarsherlock.internal.view.menu.MenuBuilder; -import com.actionbarsherlock.internal.view.menu.MenuItemImpl; -import com.actionbarsherlock.internal.view.menu.MenuPresenter; -import com.actionbarsherlock.internal.widget.ActionBarContainer; -import com.actionbarsherlock.internal.widget.ActionBarContextView; -import com.actionbarsherlock.internal.widget.ActionBarView; -import com.actionbarsherlock.internal.widget.IcsProgressBar; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; - -@ActionBarSherlock.Implementation(api = 7) -public class ActionBarSherlockCompat extends ActionBarSherlock implements MenuBuilder.Callback, com.actionbarsherlock.view.Window.Callback, MenuPresenter.Callback, android.view.MenuItem.OnMenuItemClickListener { - /** Window features which are enabled by default. */ - protected static final int DEFAULT_FEATURES = 0; - - - public ActionBarSherlockCompat(Activity activity, int flags) { - super(activity, flags); - } - - - /////////////////////////////////////////////////////////////////////////// - // Properties - /////////////////////////////////////////////////////////////////////////// - - /** Whether or not the device has a dedicated menu key button. */ - private boolean mReserveOverflow; - /** Lazy-load indicator for {@link #mReserveOverflow}. */ - private boolean mReserveOverflowSet = false; - - /** Current menu instance for managing action items. */ - private MenuBuilder mMenu; - /** Map between native options items and sherlock items. */ - protected HashMap mNativeItemMap; - /** Indication of a long-press on the hardware menu key. */ - private boolean mMenuKeyIsLongPress = false; - - /** Parent view of the window decoration (action bar, mode, etc.). */ - private ViewGroup mDecor; - /** Parent view of the activity content. */ - private ViewGroup mContentParent; - - /** Whether or not the title is stable and can be displayed. */ - private boolean mIsTitleReady = false; - /** Whether or not the parent activity has been destroyed. */ - private boolean mIsDestroyed = false; - - /* Emulate PanelFeatureState */ - private boolean mClosingActionMenu; - private boolean mMenuIsPrepared; - private boolean mMenuRefreshContent; - private Bundle mMenuFrozenActionViewState; - - /** Implementation which backs the action bar interface API. */ - private ActionBarImpl aActionBar; - /** Main action bar view which displays the core content. */ - private ActionBarView wActionBar; - /** Relevant window and action bar features flags. */ - private int mFeatures = DEFAULT_FEATURES; - /** Relevant user interface option flags. */ - private int mUiOptions = 0; - - /** Decor indeterminate progress indicator. */ - private IcsProgressBar mCircularProgressBar; - /** Decor progress indicator. */ - private IcsProgressBar mHorizontalProgressBar; - - /** Current displayed context action bar, if any. */ - private ActionMode mActionMode; - /** Parent view in which the context action bar is displayed. */ - private ActionBarContextView mActionModeView; - - /** Title view used with dialogs. */ - private TextView mTitleView; - /** Current activity title. */ - private CharSequence mTitle = null; - /** Whether or not this "activity" is floating (i.e., a dialog) */ - private boolean mIsFloating; - - - - /////////////////////////////////////////////////////////////////////////// - // Instance methods - /////////////////////////////////////////////////////////////////////////// - - @Override - public ActionBar getActionBar() { - if (DEBUG) Log.d(TAG, "[getActionBar]"); - - initActionBar(); - return aActionBar; - } - - private void initActionBar() { - if (DEBUG) Log.d(TAG, "[initActionBar]"); - - // Initializing the window decor can change window feature flags. - // Make sure that we have the correct set before performing the test below. - if (mDecor == null) { - installDecor(); - } - - if ((aActionBar != null) || !hasFeature(Window.FEATURE_ACTION_BAR) || hasFeature(Window.FEATURE_NO_TITLE) || mActivity.isChild()) { - return; - } - - aActionBar = new ActionBarImpl(mActivity, mFeatures); - - if (!mIsDelegate) { - //We may never get another chance to set the title - wActionBar.setWindowTitle(mActivity.getTitle()); - } - } - - @Override - protected Context getThemedContext() { - return aActionBar.getThemedContext(); - } - - @Override - public void setTitle(CharSequence title) { - if (DEBUG) Log.d(TAG, "[setTitle] title: " + title); - - dispatchTitleChanged(title, 0); - } - - @Override - public ActionMode startActionMode(ActionMode.Callback callback) { - if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback); - - if (mActionMode != null) { - mActionMode.finish(); - } - - final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback); - ActionMode mode = null; - - //Emulate Activity's onWindowStartingActionMode: - initActionBar(); - if (aActionBar != null) { - mode = aActionBar.startActionMode(wrappedCallback); - } - - if (mode != null) { - mActionMode = mode; - } else { - if (mActionModeView == null) { - ViewStub stub = (ViewStub)mDecor.findViewById(R.id.abs__action_mode_bar_stub); - if (stub != null) { - mActionModeView = (ActionBarContextView)stub.inflate(); - } - } - if (mActionModeView != null) { - mActionModeView.killMode(); - mode = new StandaloneActionMode(mActivity, mActionModeView, wrappedCallback, true); - if (callback.onCreateActionMode(mode, mode.getMenu())) { - mode.invalidate(); - mActionModeView.initForMode(mode); - mActionModeView.setVisibility(View.VISIBLE); - mActionMode = mode; - mActionModeView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); - } else { - mActionMode = null; - } - } - } - if (mActionMode != null && mActivity instanceof OnActionModeStartedListener) { - ((OnActionModeStartedListener)mActivity).onActionModeStarted(mActionMode); - } - return mActionMode; - } - - - /////////////////////////////////////////////////////////////////////////// - // Lifecycle and interaction callbacks for delegation - /////////////////////////////////////////////////////////////////////////// - - @Override - public void dispatchConfigurationChanged(Configuration newConfig) { - if (DEBUG) Log.d(TAG, "[dispatchConfigurationChanged] newConfig: " + newConfig); - - if (aActionBar != null) { - aActionBar.onConfigurationChanged(newConfig); - } - } - - @Override - public void dispatchPostResume() { - if (DEBUG) Log.d(TAG, "[dispatchPostResume]"); - - if (aActionBar != null) { - aActionBar.setShowHideAnimationEnabled(true); - } - } - - @Override - public void dispatchPause() { - if (DEBUG) Log.d(TAG, "[dispatchPause]"); - - if (wActionBar != null && wActionBar.isOverflowMenuShowing()) { - wActionBar.hideOverflowMenu(); - } - } - - @Override - public void dispatchStop() { - if (DEBUG) Log.d(TAG, "[dispatchStop]"); - - if (aActionBar != null) { - aActionBar.setShowHideAnimationEnabled(false); - } - } - - @Override - public void dispatchInvalidateOptionsMenu() { - if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); - - Bundle savedActionViewStates = null; - if (mMenu != null) { - savedActionViewStates = new Bundle(); - mMenu.saveActionViewStates(savedActionViewStates); - if (savedActionViewStates.size() > 0) { - mMenuFrozenActionViewState = savedActionViewStates; - } - // This will be started again when the panel is prepared. - mMenu.stopDispatchingItemsChanged(); - mMenu.clear(); - } - mMenuRefreshContent = true; - - // Prepare the options panel if we have an action bar - if (wActionBar != null) { - mMenuIsPrepared = false; - preparePanel(); - } - } - - @Override - public boolean dispatchOpenOptionsMenu() { - if (DEBUG) Log.d(TAG, "[dispatchOpenOptionsMenu]"); - - if (!isReservingOverflow()) { - return false; - } - - return wActionBar.showOverflowMenu(); - } - - @Override - public boolean dispatchCloseOptionsMenu() { - if (DEBUG) Log.d(TAG, "[dispatchCloseOptionsMenu]"); - - if (!isReservingOverflow()) { - return false; - } - - return wActionBar.hideOverflowMenu(); - } - - @Override - public void dispatchPostCreate(Bundle savedInstanceState) { - if (DEBUG) Log.d(TAG, "[dispatchOnPostCreate]"); - - if (mIsDelegate) { - mIsTitleReady = true; - } - - if (mDecor == null) { - initActionBar(); - } - } - - @Override - public boolean dispatchCreateOptionsMenu(android.view.Menu menu) { - if (DEBUG) { - Log.d(TAG, "[dispatchCreateOptionsMenu] android.view.Menu: " + menu); - Log.d(TAG, "[dispatchCreateOptionsMenu] returning true"); - } - return true; - } - - @Override - public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] android.view.Menu: " + menu); - - if (mActionMode != null) { - return false; - } - - mMenuIsPrepared = false; - if (!preparePanel()) { - return false; - } - - if (isReservingOverflow()) { - return false; - } - - if (mNativeItemMap == null) { - mNativeItemMap = new HashMap(); - } else { - mNativeItemMap.clear(); - } - - if (mMenu == null) { - return false; - } - - boolean result = mMenu.bindNativeOverflow(menu, this, mNativeItemMap); - if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result); - return result; - } - - @Override - public boolean dispatchOptionsItemSelected(android.view.MenuItem item) { - throw new IllegalStateException("Native callback invoked. Create a test case and report!"); - } - - @Override - public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[dispatchMenuOpened] featureId: " + featureId + ", menu: " + menu); - - if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) { - if (aActionBar != null) { - aActionBar.dispatchMenuVisibilityChanged(true); - } - return true; - } - - return false; - } - - @Override - public void dispatchPanelClosed(int featureId, android.view.Menu menu){ - if (DEBUG) Log.d(TAG, "[dispatchPanelClosed] featureId: " + featureId + ", menu: " + menu); - - if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) { - if (aActionBar != null) { - aActionBar.dispatchMenuVisibilityChanged(false); - } - } - } - - @Override - public void dispatchTitleChanged(CharSequence title, int color) { - if (DEBUG) Log.d(TAG, "[dispatchTitleChanged] title: " + title + ", color: " + color); - - if (!mIsDelegate || mIsTitleReady) { - if (mTitleView != null) { - mTitleView.setText(title); - } else if (wActionBar != null) { - wActionBar.setWindowTitle(title); - } - } - - mTitle = title; - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] event: " + event); - - final int keyCode = event.getKeyCode(); - - // Not handled by the view hierarchy, does the action bar want it - // to cancel out of something special? - if (keyCode == KeyEvent.KEYCODE_BACK) { - final int action = event.getAction(); - // Back cancels action modes first. - if (mActionMode != null) { - if (action == KeyEvent.ACTION_UP) { - mActionMode.finish(); - } - if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning true"); - return true; - } - - // Next collapse any expanded action views. - if (wActionBar != null && wActionBar.hasExpandedActionView()) { - if (action == KeyEvent.ACTION_UP) { - wActionBar.collapseActionView(); - } - if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning true"); - return true; - } - } - - boolean result = false; - if (keyCode == KeyEvent.KEYCODE_MENU && isReservingOverflow()) { - if (event.getAction() == KeyEvent.ACTION_DOWN && event.isLongPress()) { - mMenuKeyIsLongPress = true; - } else if (event.getAction() == KeyEvent.ACTION_UP) { - if (!mMenuKeyIsLongPress) { - if (mActionMode == null && wActionBar != null) { - if (wActionBar.isOverflowMenuShowing()) { - wActionBar.hideOverflowMenu(); - } else { - wActionBar.showOverflowMenu(); - } - } - result = true; - } - mMenuKeyIsLongPress = false; - } - } - - if (DEBUG) Log.d(TAG, "[dispatchKeyEvent] returning " + result); - return result; - } - - @Override - public void dispatchDestroy() { - mIsDestroyed = true; - } - - - /////////////////////////////////////////////////////////////////////////// - // Menu callback lifecycle and creation - /////////////////////////////////////////////////////////////////////////// - - private boolean preparePanel() { - // Already prepared (isPrepared will be reset to false later) - if (mMenuIsPrepared) { - return true; - } - - // Init the panel state's menu--return false if init failed - if (mMenu == null || mMenuRefreshContent) { - if (mMenu == null) { - if (!initializePanelMenu() || (mMenu == null)) { - return false; - } - } - - if (wActionBar != null) { - wActionBar.setMenu(mMenu, this); - } - - // Call callback, and return if it doesn't want to display menu. - - // Creating the panel menu will involve a lot of manipulation; - // don't dispatch change events to presenters until we're done. - mMenu.stopDispatchingItemsChanged(); - if (!callbackCreateOptionsMenu(mMenu)) { - // Ditch the menu created above - mMenu = null; - - if (wActionBar != null) { - // Don't show it in the action bar either - wActionBar.setMenu(null, this); - } - - return false; - } - - mMenuRefreshContent = false; - } - - // Callback and return if the callback does not want to show the menu - - // Preparing the panel menu can involve a lot of manipulation; - // don't dispatch change events to presenters until we're done. - mMenu.stopDispatchingItemsChanged(); - - // Restore action view state before we prepare. This gives apps - // an opportunity to override frozen/restored state in onPrepare. - if (mMenuFrozenActionViewState != null) { - mMenu.restoreActionViewStates(mMenuFrozenActionViewState); - mMenuFrozenActionViewState = null; - } - - if (!callbackPrepareOptionsMenu(mMenu)) { - if (wActionBar != null) { - // The app didn't want to show the menu for now but it still exists. - // Clear it out of the action bar. - wActionBar.setMenu(null, this); - } - mMenu.startDispatchingItemsChanged(); - return false; - } - - // Set the proper keymap - KeyCharacterMap kmap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); - mMenu.setQwertyMode(kmap.getKeyboardType() != KeyCharacterMap.NUMERIC); - mMenu.startDispatchingItemsChanged(); - - // Set other state - mMenuIsPrepared = true; - - return true; - } - - public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { - return callbackOptionsItemSelected(item); - } - - public void onMenuModeChange(MenuBuilder menu) { - reopenMenu(true); - } - - private void reopenMenu(boolean toggleMenuMode) { - if (wActionBar != null && wActionBar.isOverflowReserved()) { - if (!wActionBar.isOverflowMenuShowing() || !toggleMenuMode) { - if (wActionBar.getVisibility() == View.VISIBLE) { - if (callbackPrepareOptionsMenu(mMenu)) { - wActionBar.showOverflowMenu(); - } - } - } else { - wActionBar.hideOverflowMenu(); - } - return; - } - } - - private boolean initializePanelMenu() { - Context context = mActivity;//getContext(); - - // If we have an action bar, initialize the menu with a context themed for it. - if (wActionBar != null) { - TypedValue outValue = new TypedValue(); - Resources.Theme currentTheme = context.getTheme(); - currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, - outValue, true); - final int targetThemeRes = outValue.resourceId; - - if (targetThemeRes != 0 /*&& context.getThemeResId() != targetThemeRes*/) { - context = new ContextThemeWrapper(context, targetThemeRes); - } - } - - mMenu = new MenuBuilder(context); - mMenu.setCallback(this); - - return true; - } - - void checkCloseActionMenu(Menu menu) { - if (mClosingActionMenu) { - return; - } - - mClosingActionMenu = true; - wActionBar.dismissPopupMenus(); - //Callback cb = getCallback(); - //if (cb != null && !isDestroyed()) { - // cb.onPanelClosed(FEATURE_ACTION_BAR, menu); - //} - mClosingActionMenu = false; - } - - @Override - public boolean onOpenSubMenu(MenuBuilder subMenu) { - return true; - } - - @Override - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - checkCloseActionMenu(menu); - } - - @Override - public boolean onMenuItemClick(android.view.MenuItem item) { - if (DEBUG) Log.d(TAG, "[mNativeItemListener.onMenuItemClick] item: " + item); - - final MenuItemImpl sherlockItem = mNativeItemMap.get(item); - if (sherlockItem != null) { - sherlockItem.invoke(); - } else { - Log.e(TAG, "Options item \"" + item + "\" not found in mapping"); - } - - return true; //Do not allow continuation of native handling - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - return callbackOptionsItemSelected(item); - } - - - /////////////////////////////////////////////////////////////////////////// - // Progress bar interaction and internal handling - /////////////////////////////////////////////////////////////////////////// - - @Override - public void setProgressBarVisibility(boolean visible) { - if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible); - - setFeatureInt(Window.FEATURE_PROGRESS, visible ? Window.PROGRESS_VISIBILITY_ON : - Window.PROGRESS_VISIBILITY_OFF); - } - - @Override - public void setProgressBarIndeterminateVisibility(boolean visible) { - if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible); - - setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, - visible ? Window.PROGRESS_VISIBILITY_ON : Window.PROGRESS_VISIBILITY_OFF); - } - - @Override - public void setProgressBarIndeterminate(boolean indeterminate) { - if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate); - - setFeatureInt(Window.FEATURE_PROGRESS, - indeterminate ? Window.PROGRESS_INDETERMINATE_ON : Window.PROGRESS_INDETERMINATE_OFF); - } - - @Override - public void setProgress(int progress) { - if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress); - - setFeatureInt(Window.FEATURE_PROGRESS, progress + Window.PROGRESS_START); - } - - @Override - public void setSecondaryProgress(int secondaryProgress) { - if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress); - - setFeatureInt(Window.FEATURE_PROGRESS, - secondaryProgress + Window.PROGRESS_SECONDARY_START); - } - - private void setFeatureInt(int featureId, int value) { - updateInt(featureId, value, false); - } - - private void updateInt(int featureId, int value, boolean fromResume) { - // Do nothing if the decor is not yet installed... an update will - // need to be forced when we eventually become active. - if (mContentParent == null) { - return; - } - - final int featureMask = 1 << featureId; - - if ((getFeatures() & featureMask) == 0 && !fromResume) { - return; - } - - onIntChanged(featureId, value); - } - - private void onIntChanged(int featureId, int value) { - if (featureId == Window.FEATURE_PROGRESS || featureId == Window.FEATURE_INDETERMINATE_PROGRESS) { - updateProgressBars(value); - } - } - - private void updateProgressBars(int value) { - IcsProgressBar circularProgressBar = getCircularProgressBar(true); - IcsProgressBar horizontalProgressBar = getHorizontalProgressBar(true); - - final int features = mFeatures;//getLocalFeatures(); - if (value == Window.PROGRESS_VISIBILITY_ON) { - if ((features & (1 << Window.FEATURE_PROGRESS)) != 0) { - int level = horizontalProgressBar.getProgress(); - int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ? - View.VISIBLE : View.INVISIBLE; - horizontalProgressBar.setVisibility(visibility); - } - if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0) { - circularProgressBar.setVisibility(View.VISIBLE); - } - } else if (value == Window.PROGRESS_VISIBILITY_OFF) { - if ((features & (1 << Window.FEATURE_PROGRESS)) != 0) { - horizontalProgressBar.setVisibility(View.GONE); - } - if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0) { - circularProgressBar.setVisibility(View.GONE); - } - } else if (value == Window.PROGRESS_INDETERMINATE_ON) { - horizontalProgressBar.setIndeterminate(true); - } else if (value == Window.PROGRESS_INDETERMINATE_OFF) { - horizontalProgressBar.setIndeterminate(false); - } else if (Window.PROGRESS_START <= value && value <= Window.PROGRESS_END) { - // We want to set the progress value before testing for visibility - // so that when the progress bar becomes visible again, it has the - // correct level. - horizontalProgressBar.setProgress(value - Window.PROGRESS_START); - - if (value < Window.PROGRESS_END) { - showProgressBars(horizontalProgressBar, circularProgressBar); - } else { - hideProgressBars(horizontalProgressBar, circularProgressBar); - } - } else if (Window.PROGRESS_SECONDARY_START <= value && value <= Window.PROGRESS_SECONDARY_END) { - horizontalProgressBar.setSecondaryProgress(value - Window.PROGRESS_SECONDARY_START); - - showProgressBars(horizontalProgressBar, circularProgressBar); - } - } - - private void showProgressBars(IcsProgressBar horizontalProgressBar, IcsProgressBar spinnyProgressBar) { - final int features = mFeatures;//getLocalFeatures(); - if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0 && - spinnyProgressBar.getVisibility() == View.INVISIBLE) { - spinnyProgressBar.setVisibility(View.VISIBLE); - } - // Only show the progress bars if the primary progress is not complete - if ((features & (1 << Window.FEATURE_PROGRESS)) != 0 && - horizontalProgressBar.getProgress() < 10000) { - horizontalProgressBar.setVisibility(View.VISIBLE); - } - } - - private void hideProgressBars(IcsProgressBar horizontalProgressBar, IcsProgressBar spinnyProgressBar) { - final int features = mFeatures;//getLocalFeatures(); - Animation anim = AnimationUtils.loadAnimation(mActivity, android.R.anim.fade_out); - anim.setDuration(1000); - if ((features & (1 << Window.FEATURE_INDETERMINATE_PROGRESS)) != 0 && - spinnyProgressBar.getVisibility() == View.VISIBLE) { - spinnyProgressBar.startAnimation(anim); - spinnyProgressBar.setVisibility(View.INVISIBLE); - } - if ((features & (1 << Window.FEATURE_PROGRESS)) != 0 && - horizontalProgressBar.getVisibility() == View.VISIBLE) { - horizontalProgressBar.startAnimation(anim); - horizontalProgressBar.setVisibility(View.INVISIBLE); - } - } - - private IcsProgressBar getCircularProgressBar(boolean shouldInstallDecor) { - if (mCircularProgressBar != null) { - return mCircularProgressBar; - } - if (mContentParent == null && shouldInstallDecor) { - installDecor(); - } - mCircularProgressBar = (IcsProgressBar)mDecor.findViewById(R.id.abs__progress_circular); - if (mCircularProgressBar != null) { - mCircularProgressBar.setVisibility(View.INVISIBLE); - } - return mCircularProgressBar; - } - - private IcsProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) { - if (mHorizontalProgressBar != null) { - return mHorizontalProgressBar; - } - if (mContentParent == null && shouldInstallDecor) { - installDecor(); - } - mHorizontalProgressBar = (IcsProgressBar)mDecor.findViewById(R.id.abs__progress_horizontal); - if (mHorizontalProgressBar != null) { - mHorizontalProgressBar.setVisibility(View.INVISIBLE); - } - return mHorizontalProgressBar; - } - - - /////////////////////////////////////////////////////////////////////////// - // Feature management and content interaction and creation - /////////////////////////////////////////////////////////////////////////// - - private int getFeatures() { - if (DEBUG) Log.d(TAG, "[getFeatures] returning " + mFeatures); - - return mFeatures; - } - - @Override - public boolean hasFeature(int featureId) { - if (DEBUG) Log.d(TAG, "[hasFeature] featureId: " + featureId); - - boolean result = (mFeatures & (1 << featureId)) != 0; - if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result); - return result; - } - - @Override - public boolean requestFeature(int featureId) { - if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId); - - if (mContentParent != null) { - throw new AndroidRuntimeException("requestFeature() must be called before adding content"); - } - - switch (featureId) { - case Window.FEATURE_ACTION_BAR: - case Window.FEATURE_ACTION_BAR_OVERLAY: - case Window.FEATURE_ACTION_MODE_OVERLAY: - case Window.FEATURE_INDETERMINATE_PROGRESS: - case Window.FEATURE_NO_TITLE: - case Window.FEATURE_PROGRESS: - mFeatures |= (1 << featureId); - return true; - - default: - return false; - } - } - - @Override - public void setUiOptions(int uiOptions) { - if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions); - - mUiOptions = uiOptions; - } - - @Override - public void setUiOptions(int uiOptions, int mask) { - if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask); - - mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask); - } - - @Override - public void setContentView(int layoutResId) { - if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId); - - if (mContentParent == null) { - installDecor(); - } else { - mContentParent.removeAllViews(); - } - mActivity.getLayoutInflater().inflate(layoutResId, mContentParent); - - android.view.Window.Callback callback = mActivity.getWindow().getCallback(); - if (callback != null) { - callback.onContentChanged(); - } - - initActionBar(); - } - - @Override - public void setContentView(View view, ViewGroup.LayoutParams params) { - if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params); - - if (mContentParent == null) { - installDecor(); - } else { - mContentParent.removeAllViews(); - } - mContentParent.addView(view, params); - - android.view.Window.Callback callback = mActivity.getWindow().getCallback(); - if (callback != null) { - callback.onContentChanged(); - } - - initActionBar(); - } - - @Override - public void addContentView(View view, ViewGroup.LayoutParams params) { - if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params); - - if (mContentParent == null) { - installDecor(); - } - mContentParent.addView(view, params); - - initActionBar(); - } - - private void installDecor() { - if (DEBUG) Log.d(TAG, "[installDecor]"); - - if (mDecor == null) { - mDecor = (ViewGroup)mActivity.getWindow().getDecorView().findViewById(android.R.id.content); - } - if (mContentParent == null) { - //Since we are not operating at the window level we need to take - //into account the fact that the true decor may have already been - //initialized and had content attached to it. If that is the case, - //copy over its children to our new content container. - List views = null; - if (mDecor.getChildCount() > 0) { - views = new ArrayList(1); //Usually there's only one child - for (int i = 0, children = mDecor.getChildCount(); i < children; i++) { - View child = mDecor.getChildAt(0); - mDecor.removeView(child); - views.add(child); - } - } - - mContentParent = generateLayout(); - - //Copy over the old children. See above for explanation. - if (views != null) { - for (View child : views) { - mContentParent.addView(child); - } - } - - mTitleView = (TextView)mDecor.findViewById(android.R.id.title); - if (mTitleView != null) { - if (hasFeature(Window.FEATURE_NO_TITLE)) { - mTitleView.setVisibility(View.GONE); - if (mContentParent instanceof FrameLayout) { - ((FrameLayout)mContentParent).setForeground(null); - } - } else { - mTitleView.setText(mTitle); - } - } else { - wActionBar = (ActionBarView)mDecor.findViewById(R.id.abs__action_bar); - if (wActionBar != null) { - wActionBar.setWindowCallback(this); - if (wActionBar.getTitle() == null) { - wActionBar.setWindowTitle(mActivity.getTitle()); - } - if (hasFeature(Window.FEATURE_PROGRESS)) { - wActionBar.initProgress(); - } - if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) { - wActionBar.initIndeterminateProgress(); - } - - //Since we don't require onCreate dispatching, parse for uiOptions here - int uiOptions = loadUiOptionsFromManifest(mActivity); - if (uiOptions != 0) { - mUiOptions = uiOptions; - } - - boolean splitActionBar = false; - final boolean splitWhenNarrow = (mUiOptions & ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW) != 0; - if (splitWhenNarrow) { - splitActionBar = getResources_getBoolean(mActivity, R.bool.abs__split_action_bar_is_narrow); - } else { - splitActionBar = mActivity.getTheme() - .obtainStyledAttributes(R.styleable.SherlockTheme) - .getBoolean(R.styleable.SherlockTheme_windowSplitActionBar, false); - } - final ActionBarContainer splitView = (ActionBarContainer)mDecor.findViewById(R.id.abs__split_action_bar); - if (splitView != null) { - wActionBar.setSplitView(splitView); - wActionBar.setSplitActionBar(splitActionBar); - wActionBar.setSplitWhenNarrow(splitWhenNarrow); - - mActionModeView = (ActionBarContextView)mDecor.findViewById(R.id.abs__action_context_bar); - mActionModeView.setSplitView(splitView); - mActionModeView.setSplitActionBar(splitActionBar); - mActionModeView.setSplitWhenNarrow(splitWhenNarrow); - } else if (splitActionBar) { - Log.e(TAG, "Requested split action bar with incompatible window decor! Ignoring request."); - } - - // Post the panel invalidate for later; avoid application onCreateOptionsMenu - // being called in the middle of onCreate or similar. - mDecor.post(new Runnable() { - @Override - public void run() { - //Invalidate if the panel menu hasn't been created before this. - if (!mIsDestroyed && !mActivity.isFinishing() && mMenu == null) { - dispatchInvalidateOptionsMenu(); - } - } - }); - } - } - } - } - - private ViewGroup generateLayout() { - if (DEBUG) Log.d(TAG, "[generateLayout]"); - - // Apply data from current theme. - - TypedArray a = mActivity.getTheme().obtainStyledAttributes(R.styleable.SherlockTheme); - - mIsFloating = a.getBoolean(R.styleable.SherlockTheme_android_windowIsFloating, false); - - if (!a.hasValue(R.styleable.SherlockTheme_windowActionBar)) { - throw new IllegalStateException("You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative."); - } - - if (a.getBoolean(R.styleable.SherlockTheme_windowNoTitle, false)) { - requestFeature(Window.FEATURE_NO_TITLE); - } else if (a.getBoolean(R.styleable.SherlockTheme_windowActionBar, false)) { - // Don't allow an action bar if there is no title. - requestFeature(Window.FEATURE_ACTION_BAR); - } - - if (a.getBoolean(R.styleable.SherlockTheme_windowActionBarOverlay, false)) { - requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); - } - - if (a.getBoolean(R.styleable.SherlockTheme_windowActionModeOverlay, false)) { - requestFeature(Window.FEATURE_ACTION_MODE_OVERLAY); - } - - a.recycle(); - - int layoutResource; - if (!hasFeature(Window.FEATURE_NO_TITLE)) { - if (mIsFloating) { - //Trash original dialog LinearLayout - mDecor = (ViewGroup)mDecor.getParent(); - mDecor.removeAllViews(); - - layoutResource = R.layout.abs__dialog_title_holo; - } else { - if (hasFeature(Window.FEATURE_ACTION_BAR_OVERLAY)) { - layoutResource = R.layout.abs__screen_action_bar_overlay; - } else { - layoutResource = R.layout.abs__screen_action_bar; - } - } - } else if (hasFeature(Window.FEATURE_ACTION_MODE_OVERLAY) && !hasFeature(Window.FEATURE_NO_TITLE)) { - layoutResource = R.layout.abs__screen_simple_overlay_action_mode; - } else { - layoutResource = R.layout.abs__screen_simple; - } - - if (DEBUG) Log.d(TAG, "[generateLayout] using screen XML " + mActivity.getResources().getString(layoutResource)); - View in = mActivity.getLayoutInflater().inflate(layoutResource, null); - mDecor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); - - ViewGroup contentParent = (ViewGroup)mDecor.findViewById(R.id.abs__content); - if (contentParent == null) { - throw new RuntimeException("Couldn't find content container view"); - } - - //Make our new child the true content view (for fragments). VERY VOLATILE! - mDecor.setId(View.NO_ID); - contentParent.setId(android.R.id.content); - - if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) { - IcsProgressBar progress = getCircularProgressBar(false); - if (progress != null) { - progress.setIndeterminate(true); - } - } - - return contentParent; - } - - - /////////////////////////////////////////////////////////////////////////// - // Miscellaneous - /////////////////////////////////////////////////////////////////////////// - - /** - * Determine whether or not the device has a dedicated menu key. - * - * @return {@code true} if native menu key is present. - */ - private boolean isReservingOverflow() { - if (!mReserveOverflowSet) { - mReserveOverflow = ActionMenuPresenter.reserveOverflow(mActivity); - mReserveOverflowSet = true; - } - return mReserveOverflow; - } - - private static int loadUiOptionsFromManifest(Activity activity) { - int uiOptions = 0; - try { - final String thisPackage = activity.getClass().getName(); - if (DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage); - - final String packageName = activity.getApplicationInfo().packageName; - final AssetManager am = activity.createPackageContext(packageName, 0).getAssets(); - final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml"); - - int eventType = xml.getEventType(); - while (eventType != XmlPullParser.END_DOCUMENT) { - if (eventType == XmlPullParser.START_TAG) { - String name = xml.getName(); - - if ("application".equals(name)) { - //Check if the has the attribute - if (DEBUG) Log.d(TAG, "Got "); - - for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { - if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); - - if ("uiOptions".equals(xml.getAttributeName(i))) { - uiOptions = xml.getAttributeIntValue(i, 0); - break; //out of for loop - } - } - } else if ("activity".equals(name)) { - //Check if the is us and has the attribute - if (DEBUG) Log.d(TAG, "Got "); - Integer activityUiOptions = null; - String activityPackage = null; - boolean isOurActivity = false; - - for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { - if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); - - //We need both uiOptions and name attributes - String attrName = xml.getAttributeName(i); - if ("uiOptions".equals(attrName)) { - activityUiOptions = xml.getAttributeIntValue(i, 0); - } else if ("name".equals(attrName)) { - activityPackage = cleanActivityName(packageName, xml.getAttributeValue(i)); - if (!thisPackage.equals(activityPackage)) { - break; //out of for loop - } - isOurActivity = true; - } - - //Make sure we have both attributes before processing - if ((activityUiOptions != null) && (activityPackage != null)) { - //Our activity, uiOptions specified, override with our value - uiOptions = activityUiOptions.intValue(); - } - } - if (isOurActivity) { - //If we matched our activity but it had no logo don't - //do any more processing of the manifest - break; - } - } - } - eventType = xml.nextToken(); - } - } catch (Exception e) { - e.printStackTrace(); - } - if (DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(uiOptions)); - return uiOptions; - } - - public static String cleanActivityName(String manifestPackage, String activityName) { - if (activityName.charAt(0) == '.') { - //Relative activity name (e.g., android:name=".ui.SomeClass") - return manifestPackage + activityName; - } - if (activityName.indexOf('.', 1) == -1) { - //Unqualified activity name (e.g., android:name="SomeClass") - return manifestPackage + "." + activityName; - } - //Fully-qualified activity name (e.g., "com.my.package.SomeClass") - return activityName; - } - - /** - * Clears out internal reference when the action mode is destroyed. - */ - private class ActionModeCallbackWrapper implements ActionMode.Callback { - private final ActionMode.Callback mWrapped; - - public ActionModeCallbackWrapper(ActionMode.Callback wrapped) { - mWrapped = wrapped; - } - - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - return mWrapped.onCreateActionMode(mode, menu); - } - - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - return mWrapped.onPrepareActionMode(mode, menu); - } - - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - return mWrapped.onActionItemClicked(mode, item); - } - - public void onDestroyActionMode(ActionMode mode) { - mWrapped.onDestroyActionMode(mode); - if (mActionModeView != null) { - mActionModeView.setVisibility(View.GONE); - mActionModeView.removeAllViews(); - } - if (mActivity instanceof OnActionModeFinishedListener) { - ((OnActionModeFinishedListener)mActivity).onActionModeFinished(mActionMode); - } - mActionMode = null; - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockNative.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockNative.java deleted file mode 100644 index 9afca185..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockNative.java +++ /dev/null @@ -1,328 +0,0 @@ -package com.actionbarsherlock.internal; - -import com.actionbarsherlock.ActionBarSherlock; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.internal.app.ActionBarWrapper; -import com.actionbarsherlock.internal.view.menu.MenuWrapper; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.MenuInflater; -import android.app.Activity; -import android.content.Context; -import android.util.Log; -import android.util.TypedValue; -import android.view.ContextThemeWrapper; -import android.view.View; -import android.view.Window; -import android.view.ViewGroup.LayoutParams; - -@ActionBarSherlock.Implementation(api = 14) -public class ActionBarSherlockNative extends ActionBarSherlock { - private ActionBarWrapper mActionBar; - private ActionModeWrapper mActionMode; - private MenuWrapper mMenu; - - public ActionBarSherlockNative(Activity activity, int flags) { - super(activity, flags); - } - - - @Override - public ActionBar getActionBar() { - if (DEBUG) Log.d(TAG, "[getActionBar]"); - - initActionBar(); - return mActionBar; - } - - private void initActionBar() { - if (mActionBar != null || mActivity.getActionBar() == null) { - return; - } - - mActionBar = new ActionBarWrapper(mActivity); - } - - @Override - public void dispatchInvalidateOptionsMenu() { - if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); - - mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); - } - - @Override - public boolean dispatchCreateOptionsMenu(android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] menu: " + menu); - - if (mMenu == null || menu != mMenu.unwrap()) { - mMenu = new MenuWrapper(menu); - } - - final boolean result = callbackCreateOptionsMenu(mMenu); - if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] returning " + result); - return result; - } - - @Override - public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] menu: " + menu); - - final boolean result = callbackPrepareOptionsMenu(mMenu); - if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result); - return result; - } - - @Override - public boolean dispatchOptionsItemSelected(android.view.MenuItem item) { - if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] item: " + item.getTitleCondensed()); - - final boolean result = callbackOptionsItemSelected(mMenu.findItem(item)); - if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] returning " + result); - return result; - } - - @Override - public boolean hasFeature(int feature) { - if (DEBUG) Log.d(TAG, "[hasFeature] feature: " + feature); - - final boolean result = mActivity.getWindow().hasFeature(feature); - if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result); - return result; - } - - @Override - public boolean requestFeature(int featureId) { - if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId); - - final boolean result = mActivity.getWindow().requestFeature(featureId); - if (DEBUG) Log.d(TAG, "[requestFeature] returning " + result); - return result; - } - - @Override - public void setUiOptions(int uiOptions) { - if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions); - - mActivity.getWindow().setUiOptions(uiOptions); - } - - @Override - public void setUiOptions(int uiOptions, int mask) { - if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask); - - mActivity.getWindow().setUiOptions(uiOptions, mask); - } - - @Override - public void setContentView(int layoutResId) { - if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId); - - mActivity.getWindow().setContentView(layoutResId); - initActionBar(); - } - - @Override - public void setContentView(View view, LayoutParams params) { - if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params); - - mActivity.getWindow().setContentView(view, params); - initActionBar(); - } - - @Override - public void addContentView(View view, LayoutParams params) { - if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params); - - mActivity.getWindow().addContentView(view, params); - initActionBar(); - } - - @Override - public void setTitle(CharSequence title) { - if (DEBUG) Log.d(TAG, "[setTitle] title: " + title); - - mActivity.getWindow().setTitle(title); - } - - @Override - public void setProgressBarVisibility(boolean visible) { - if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible); - - mActivity.setProgressBarVisibility(visible); - } - - @Override - public void setProgressBarIndeterminateVisibility(boolean visible) { - if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible); - - mActivity.setProgressBarIndeterminateVisibility(visible); - } - - @Override - public void setProgressBarIndeterminate(boolean indeterminate) { - if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate); - - mActivity.setProgressBarIndeterminate(indeterminate); - } - - @Override - public void setProgress(int progress) { - if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress); - - mActivity.setProgress(progress); - } - - @Override - public void setSecondaryProgress(int secondaryProgress) { - if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress); - - mActivity.setSecondaryProgress(secondaryProgress); - } - - @Override - protected Context getThemedContext() { - Context context = mActivity; - TypedValue outValue = new TypedValue(); - mActivity.getTheme().resolveAttribute(android.R.attr.actionBarWidgetTheme, outValue, true); - if (outValue.resourceId != 0) { - //We are unable to test if this is the same as our current theme - //so we just wrap it and hope that if the attribute was specified - //then the user is intentionally specifying an alternate theme. - context = new ContextThemeWrapper(context, outValue.resourceId); - } - return context; - } - - @Override - public ActionMode startActionMode(com.actionbarsherlock.view.ActionMode.Callback callback) { - if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback); - - if (mActionMode != null) { - mActionMode.finish(); - } - ActionModeCallbackWrapper wrapped = null; - if (callback != null) { - wrapped = new ActionModeCallbackWrapper(callback); - } - - //Calling this will trigger the callback wrapper's onCreate which - //is where we will set the new instance to mActionMode since we need - //to pass it through to the sherlock callbacks and the call below - //will not have returned yet to store its value. - mActivity.startActionMode(wrapped); - - return mActionMode; - } - - private class ActionModeCallbackWrapper implements android.view.ActionMode.Callback { - private final ActionMode.Callback mCallback; - - public ActionModeCallbackWrapper(ActionMode.Callback callback) { - mCallback = callback; - } - - @Override - public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) { - //See ActionBarSherlockNative#startActionMode - mActionMode = new ActionModeWrapper(mode); - - return mCallback.onCreateActionMode(mActionMode, mActionMode.getMenu()); - } - - @Override - public boolean onPrepareActionMode(android.view.ActionMode mode, android.view.Menu menu) { - return mCallback.onPrepareActionMode(mActionMode, mActionMode.getMenu()); - } - - @Override - public boolean onActionItemClicked(android.view.ActionMode mode, android.view.MenuItem item) { - return mCallback.onActionItemClicked(mActionMode, mActionMode.getMenu().findItem(item)); - } - - @Override - public void onDestroyActionMode(android.view.ActionMode mode) { - mCallback.onDestroyActionMode(mActionMode); - } - } - - private class ActionModeWrapper extends ActionMode { - private final android.view.ActionMode mActionMode; - private MenuWrapper mMenu = null; - - ActionModeWrapper(android.view.ActionMode actionMode) { - mActionMode = actionMode; - } - - @Override - public void setTitle(CharSequence title) { - mActionMode.setTitle(title); - } - - @Override - public void setTitle(int resId) { - mActionMode.setTitle(resId); - } - - @Override - public void setSubtitle(CharSequence subtitle) { - mActionMode.setSubtitle(subtitle); - } - - @Override - public void setSubtitle(int resId) { - mActionMode.setSubtitle(resId); - } - - @Override - public void setCustomView(View view) { - mActionMode.setCustomView(view); - } - - @Override - public void invalidate() { - mActionMode.invalidate(); - } - - @Override - public void finish() { - mActionMode.finish(); - } - - @Override - public MenuWrapper getMenu() { - if (mMenu == null) { - mMenu = new MenuWrapper(mActionMode.getMenu()); - } - return mMenu; - } - - @Override - public CharSequence getTitle() { - return mActionMode.getTitle(); - } - - @Override - public CharSequence getSubtitle() { - return mActionMode.getSubtitle(); - } - - @Override - public View getCustomView() { - return mActionMode.getCustomView(); - } - - @Override - public MenuInflater getMenuInflater() { - return ActionBarSherlockNative.this.getMenuInflater(); - } - - @Override - public void setTag(Object tag) { - mActionMode.setTag(tag); - } - - @Override - public Object getTag() { - return mActionMode.getTag(); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ResourcesCompat.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ResourcesCompat.java deleted file mode 100644 index 8e1efe8c..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ResourcesCompat.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.actionbarsherlock.internal; - -import android.content.Context; -import android.os.Build; -import android.util.DisplayMetrics; -import com.actionbarsherlock.R; - -public final class ResourcesCompat { - //No instances - private ResourcesCompat() {} - - - /** - * Support implementation of {@code getResources().getBoolean()} that we - * can use to simulate filtering based on width and smallest width - * qualifiers on pre-3.2. - * - * @param context Context to load booleans from on 3.2+ and to fetch the - * display metrics. - * @param id Id of boolean to load. - * @return Associated boolean value as reflected by the current display - * metrics. - */ - public static boolean getResources_getBoolean(Context context, int id) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { - return context.getResources().getBoolean(id); - } - - DisplayMetrics metrics = context.getResources().getDisplayMetrics(); - float widthDp = metrics.widthPixels / metrics.density; - float heightDp = metrics.heightPixels / metrics.density; - float smallestWidthDp = (widthDp < heightDp) ? widthDp : heightDp; - - if (id == R.bool.abs__action_bar_embed_tabs) { - if (widthDp >= 480) { - return true; //values-w480dp - } - return false; //values - } - if (id == R.bool.abs__split_action_bar_is_narrow) { - if (widthDp >= 480) { - return false; //values-w480dp - } - return true; //values - } - if (id == R.bool.abs__action_bar_expanded_action_views_exclusive) { - if (smallestWidthDp >= 600) { - return false; //values-sw600dp - } - return true; //values - } - if (id == R.bool.abs__config_allowActionMenuItemTextWithIcon) { - if (widthDp >= 480) { - return true; //values-w480dp - } - return false; //values - } - - throw new IllegalArgumentException("Unknown boolean resource ID " + id); - } - - /** - * Support implementation of {@code getResources().getInteger()} that we - * can use to simulate filtering based on width qualifiers on pre-3.2. - * - * @param context Context to load integers from on 3.2+ and to fetch the - * display metrics. - * @param id Id of integer to load. - * @return Associated integer value as reflected by the current display - * metrics. - */ - public static int getResources_getInteger(Context context, int id) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { - return context.getResources().getInteger(id); - } - - DisplayMetrics metrics = context.getResources().getDisplayMetrics(); - float widthDp = metrics.widthPixels / metrics.density; - - if (id == R.integer.abs__max_action_buttons) { - if (widthDp >= 600) { - return 5; //values-w600dp - } - if (widthDp >= 500) { - return 4; //values-w500dp - } - if (widthDp >= 360) { - return 3; //values-w360dp - } - return 2; //values - } - - throw new IllegalArgumentException("Unknown integer resource ID " + id); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarImpl.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarImpl.java deleted file mode 100644 index 6ae0402c..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarImpl.java +++ /dev/null @@ -1,1026 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.app; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import android.app.Activity; -import android.app.Dialog; -import android.content.Context; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.os.Handler; -import android.support.v4.app.FragmentTransaction; -import android.util.TypedValue; -import android.view.ContextThemeWrapper; -import android.view.LayoutInflater; -import android.view.View; -import android.view.Window; -import android.view.accessibility.AccessibilityEvent; -import android.widget.SpinnerAdapter; -import com.actionbarsherlock.R; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.app.SherlockFragmentActivity; -import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; -import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorListenerAdapter; -import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; -import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; -import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener; -import com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout; -import com.actionbarsherlock.internal.view.menu.MenuBuilder; -import com.actionbarsherlock.internal.view.menu.MenuPopupHelper; -import com.actionbarsherlock.internal.view.menu.SubMenuBuilder; -import com.actionbarsherlock.internal.widget.ActionBarContainer; -import com.actionbarsherlock.internal.widget.ActionBarContextView; -import com.actionbarsherlock.internal.widget.ActionBarView; -import com.actionbarsherlock.internal.widget.ScrollingTabContainerView; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; -import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; - -/** - * ActionBarImpl is the ActionBar implementation used - * by devices of all screen sizes. If it detects a compatible decor, - * it will split contextual modes across both the ActionBarView at - * the top of the screen and a horizontal LinearLayout at the bottom - * which is normally hidden. - */ -public class ActionBarImpl extends ActionBar { - //UNUSED private static final String TAG = "ActionBarImpl"; - - private Context mContext; - private Context mThemedContext; - private Activity mActivity; - //UNUSED private Dialog mDialog; - - private ActionBarContainer mContainerView; - private ActionBarView mActionView; - private ActionBarContextView mContextView; - private ActionBarContainer mSplitView; - private NineFrameLayout mContentView; - private ScrollingTabContainerView mTabScrollView; - - private ArrayList mTabs = new ArrayList(); - - private TabImpl mSelectedTab; - private int mSavedTabPosition = INVALID_POSITION; - - ActionModeImpl mActionMode; - ActionMode mDeferredDestroyActionMode; - ActionMode.Callback mDeferredModeDestroyCallback; - - private boolean mLastMenuVisibility; - private ArrayList mMenuVisibilityListeners = - new ArrayList(); - - private static final int CONTEXT_DISPLAY_NORMAL = 0; - private static final int CONTEXT_DISPLAY_SPLIT = 1; - - private static final int INVALID_POSITION = -1; - - private int mContextDisplayMode; - private boolean mHasEmbeddedTabs; - - final Handler mHandler = new Handler(); - Runnable mTabSelector; - - private Animator mCurrentShowAnim; - private Animator mCurrentModeAnim; - private boolean mShowHideAnimationEnabled; - boolean mWasHiddenBeforeMode; - - final AnimatorListener mHideListener = new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - if (mContentView != null) { - mContentView.setTranslationY(0); - mContainerView.setTranslationY(0); - } - if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) { - mSplitView.setVisibility(View.GONE); - } - mContainerView.setVisibility(View.GONE); - mContainerView.setTransitioning(false); - mCurrentShowAnim = null; - completeDeferredDestroyActionMode(); - } - }; - - final AnimatorListener mShowListener = new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - mCurrentShowAnim = null; - mContainerView.requestLayout(); - } - }; - - public ActionBarImpl(Activity activity, int features) { - mActivity = activity; - Window window = activity.getWindow(); - View decor = window.getDecorView(); - init(decor); - - //window.hasFeature() workaround for pre-3.0 - if ((features & (1 << Window.FEATURE_ACTION_BAR_OVERLAY)) == 0) { - mContentView = (NineFrameLayout)decor.findViewById(android.R.id.content); - } - } - - public ActionBarImpl(Dialog dialog) { - //UNUSED mDialog = dialog; - init(dialog.getWindow().getDecorView()); - } - - private void init(View decor) { - mContext = decor.getContext(); - mActionView = (ActionBarView) decor.findViewById(R.id.abs__action_bar); - mContextView = (ActionBarContextView) decor.findViewById( - R.id.abs__action_context_bar); - mContainerView = (ActionBarContainer) decor.findViewById( - R.id.abs__action_bar_container); - mSplitView = (ActionBarContainer) decor.findViewById( - R.id.abs__split_action_bar); - - if (mActionView == null || mContextView == null || mContainerView == null) { - throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + - "with a compatible window decor layout"); - } - - mActionView.setContextView(mContextView); - mContextDisplayMode = mActionView.isSplitActionBar() ? - CONTEXT_DISPLAY_SPLIT : CONTEXT_DISPLAY_NORMAL; - - // Older apps get the home button interaction enabled by default. - // Newer apps need to enable it explicitly. - setHomeButtonEnabled(mContext.getApplicationInfo().targetSdkVersion < 14); - - setHasEmbeddedTabs(getResources_getBoolean(mContext, - R.bool.abs__action_bar_embed_tabs)); - } - - public void onConfigurationChanged(Configuration newConfig) { - setHasEmbeddedTabs(getResources_getBoolean(mContext, - R.bool.abs__action_bar_embed_tabs)); - - //Manually dispatch a configuration change to the action bar view on pre-2.2 - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { - mActionView.onConfigurationChanged(newConfig); - if (mContextView != null) { - mContextView.onConfigurationChanged(newConfig); - } - } - } - - private void setHasEmbeddedTabs(boolean hasEmbeddedTabs) { - mHasEmbeddedTabs = hasEmbeddedTabs; - // Switch tab layout configuration if needed - if (!mHasEmbeddedTabs) { - mActionView.setEmbeddedTabView(null); - mContainerView.setTabContainer(mTabScrollView); - } else { - mContainerView.setTabContainer(null); - mActionView.setEmbeddedTabView(mTabScrollView); - } - final boolean isInTabMode = getNavigationMode() == NAVIGATION_MODE_TABS; - if (mTabScrollView != null) { - mTabScrollView.setVisibility(isInTabMode ? View.VISIBLE : View.GONE); - } - mActionView.setCollapsable(!mHasEmbeddedTabs && isInTabMode); - } - - private void ensureTabsExist() { - if (mTabScrollView != null) { - return; - } - - ScrollingTabContainerView tabScroller = new ScrollingTabContainerView(mContext); - - if (mHasEmbeddedTabs) { - tabScroller.setVisibility(View.VISIBLE); - mActionView.setEmbeddedTabView(tabScroller); - } else { - tabScroller.setVisibility(getNavigationMode() == NAVIGATION_MODE_TABS ? - View.VISIBLE : View.GONE); - mContainerView.setTabContainer(tabScroller); - } - mTabScrollView = tabScroller; - } - - void completeDeferredDestroyActionMode() { - if (mDeferredModeDestroyCallback != null) { - mDeferredModeDestroyCallback.onDestroyActionMode(mDeferredDestroyActionMode); - mDeferredDestroyActionMode = null; - mDeferredModeDestroyCallback = null; - } - } - - /** - * Enables or disables animation between show/hide states. - * If animation is disabled using this method, animations in progress - * will be finished. - * - * @param enabled true to animate, false to not animate. - */ - public void setShowHideAnimationEnabled(boolean enabled) { - mShowHideAnimationEnabled = enabled; - if (!enabled && mCurrentShowAnim != null) { - mCurrentShowAnim.end(); - } - } - - public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) { - mMenuVisibilityListeners.add(listener); - } - - public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) { - mMenuVisibilityListeners.remove(listener); - } - - public void dispatchMenuVisibilityChanged(boolean isVisible) { - if (isVisible == mLastMenuVisibility) { - return; - } - mLastMenuVisibility = isVisible; - - final int count = mMenuVisibilityListeners.size(); - for (int i = 0; i < count; i++) { - mMenuVisibilityListeners.get(i).onMenuVisibilityChanged(isVisible); - } - } - - @Override - public void setCustomView(int resId) { - setCustomView(LayoutInflater.from(getThemedContext()).inflate(resId, mActionView, false)); - } - - @Override - public void setDisplayUseLogoEnabled(boolean useLogo) { - setDisplayOptions(useLogo ? DISPLAY_USE_LOGO : 0, DISPLAY_USE_LOGO); - } - - @Override - public void setDisplayShowHomeEnabled(boolean showHome) { - setDisplayOptions(showHome ? DISPLAY_SHOW_HOME : 0, DISPLAY_SHOW_HOME); - } - - @Override - public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) { - setDisplayOptions(showHomeAsUp ? DISPLAY_HOME_AS_UP : 0, DISPLAY_HOME_AS_UP); - } - - @Override - public void setDisplayShowTitleEnabled(boolean showTitle) { - setDisplayOptions(showTitle ? DISPLAY_SHOW_TITLE : 0, DISPLAY_SHOW_TITLE); - } - - @Override - public void setDisplayShowCustomEnabled(boolean showCustom) { - setDisplayOptions(showCustom ? DISPLAY_SHOW_CUSTOM : 0, DISPLAY_SHOW_CUSTOM); - } - - @Override - public void setHomeButtonEnabled(boolean enable) { - mActionView.setHomeButtonEnabled(enable); - } - - @Override - public void setTitle(int resId) { - setTitle(mContext.getString(resId)); - } - - @Override - public void setSubtitle(int resId) { - setSubtitle(mContext.getString(resId)); - } - - public void setSelectedNavigationItem(int position) { - switch (mActionView.getNavigationMode()) { - case NAVIGATION_MODE_TABS: - selectTab(mTabs.get(position)); - break; - case NAVIGATION_MODE_LIST: - mActionView.setDropdownSelectedPosition(position); - break; - default: - throw new IllegalStateException( - "setSelectedNavigationIndex not valid for current navigation mode"); - } - } - - public void removeAllTabs() { - cleanupTabs(); - } - - private void cleanupTabs() { - if (mSelectedTab != null) { - selectTab(null); - } - mTabs.clear(); - if (mTabScrollView != null) { - mTabScrollView.removeAllTabs(); - } - mSavedTabPosition = INVALID_POSITION; - } - - public void setTitle(CharSequence title) { - mActionView.setTitle(title); - } - - public void setSubtitle(CharSequence subtitle) { - mActionView.setSubtitle(subtitle); - } - - public void setDisplayOptions(int options) { - mActionView.setDisplayOptions(options); - } - - public void setDisplayOptions(int options, int mask) { - final int current = mActionView.getDisplayOptions(); - mActionView.setDisplayOptions((options & mask) | (current & ~mask)); - } - - public void setBackgroundDrawable(Drawable d) { - mContainerView.setPrimaryBackground(d); - } - - public void setStackedBackgroundDrawable(Drawable d) { - mContainerView.setStackedBackground(d); - } - - public void setSplitBackgroundDrawable(Drawable d) { - if (mSplitView != null) { - mSplitView.setSplitBackground(d); - } - } - - public View getCustomView() { - return mActionView.getCustomNavigationView(); - } - - public CharSequence getTitle() { - return mActionView.getTitle(); - } - - public CharSequence getSubtitle() { - return mActionView.getSubtitle(); - } - - public int getNavigationMode() { - return mActionView.getNavigationMode(); - } - - public int getDisplayOptions() { - return mActionView.getDisplayOptions(); - } - - public ActionMode startActionMode(ActionMode.Callback callback) { - boolean wasHidden = false; - if (mActionMode != null) { - wasHidden = mWasHiddenBeforeMode; - mActionMode.finish(); - } - - mContextView.killMode(); - ActionModeImpl mode = new ActionModeImpl(callback); - if (mode.dispatchOnCreate()) { - mWasHiddenBeforeMode = !isShowing() || wasHidden; - mode.invalidate(); - mContextView.initForMode(mode); - animateToMode(true); - if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) { - // TODO animate this - mSplitView.setVisibility(View.VISIBLE); - } - mContextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); - mActionMode = mode; - return mode; - } - return null; - } - - private void configureTab(Tab tab, int position) { - final TabImpl tabi = (TabImpl) tab; - final ActionBar.TabListener callback = tabi.getCallback(); - - if (callback == null) { - throw new IllegalStateException("Action Bar Tab must have a Callback"); - } - - tabi.setPosition(position); - mTabs.add(position, tabi); - - final int count = mTabs.size(); - for (int i = position + 1; i < count; i++) { - mTabs.get(i).setPosition(i); - } - } - - @Override - public void addTab(Tab tab) { - addTab(tab, mTabs.isEmpty()); - } - - @Override - public void addTab(Tab tab, int position) { - addTab(tab, position, mTabs.isEmpty()); - } - - @Override - public void addTab(Tab tab, boolean setSelected) { - ensureTabsExist(); - mTabScrollView.addTab(tab, setSelected); - configureTab(tab, mTabs.size()); - if (setSelected) { - selectTab(tab); - } - } - - @Override - public void addTab(Tab tab, int position, boolean setSelected) { - ensureTabsExist(); - mTabScrollView.addTab(tab, position, setSelected); - configureTab(tab, position); - if (setSelected) { - selectTab(tab); - } - } - - @Override - public Tab newTab() { - return new TabImpl(); - } - - @Override - public void removeTab(Tab tab) { - removeTabAt(tab.getPosition()); - } - - @Override - public void removeTabAt(int position) { - if (mTabScrollView == null) { - // No tabs around to remove - return; - } - - int selectedTabPosition = mSelectedTab != null - ? mSelectedTab.getPosition() : mSavedTabPosition; - mTabScrollView.removeTabAt(position); - TabImpl removedTab = mTabs.remove(position); - if (removedTab != null) { - removedTab.setPosition(-1); - } - - final int newTabCount = mTabs.size(); - for (int i = position; i < newTabCount; i++) { - mTabs.get(i).setPosition(i); - } - - if (selectedTabPosition == position) { - selectTab(mTabs.isEmpty() ? null : mTabs.get(Math.max(0, position - 1))); - } - } - - @Override - public void selectTab(Tab tab) { - if (getNavigationMode() != NAVIGATION_MODE_TABS) { - mSavedTabPosition = tab != null ? tab.getPosition() : INVALID_POSITION; - return; - } - - FragmentTransaction trans = null; - if (mActivity instanceof SherlockFragmentActivity) { - trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() - .disallowAddToBackStack(); - } - - if (mSelectedTab == tab) { - if (mSelectedTab != null) { - mSelectedTab.getCallback().onTabReselected(mSelectedTab, trans); - mTabScrollView.animateToTab(tab.getPosition()); - } - } else { - mTabScrollView.setTabSelected(tab != null ? tab.getPosition() : Tab.INVALID_POSITION); - if (mSelectedTab != null) { - mSelectedTab.getCallback().onTabUnselected(mSelectedTab, trans); - } - mSelectedTab = (TabImpl) tab; - if (mSelectedTab != null) { - mSelectedTab.getCallback().onTabSelected(mSelectedTab, trans); - } - } - - if (trans != null && !trans.isEmpty()) { - trans.commit(); - } - } - - @Override - public Tab getSelectedTab() { - return mSelectedTab; - } - - @Override - public int getHeight() { - return mContainerView.getHeight(); - } - - @Override - public void show() { - show(true); - } - - void show(boolean markHiddenBeforeMode) { - if (mCurrentShowAnim != null) { - mCurrentShowAnim.end(); - } - if (mContainerView.getVisibility() == View.VISIBLE) { - if (markHiddenBeforeMode) mWasHiddenBeforeMode = false; - return; - } - mContainerView.setVisibility(View.VISIBLE); - - if (mShowHideAnimationEnabled) { - mContainerView.setAlpha(0); - AnimatorSet anim = new AnimatorSet(); - AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(mContainerView, "alpha", 1)); - if (mContentView != null) { - b.with(ObjectAnimator.ofFloat(mContentView, "translationY", - -mContainerView.getHeight(), 0)); - mContainerView.setTranslationY(-mContainerView.getHeight()); - b.with(ObjectAnimator.ofFloat(mContainerView, "translationY", 0)); - } - if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) { - mSplitView.setAlpha(0); - mSplitView.setVisibility(View.VISIBLE); - b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 1)); - } - anim.addListener(mShowListener); - mCurrentShowAnim = anim; - anim.start(); - } else { - mContainerView.setAlpha(1); - mContainerView.setTranslationY(0); - mShowListener.onAnimationEnd(null); - } - } - - @Override - public void hide() { - if (mCurrentShowAnim != null) { - mCurrentShowAnim.end(); - } - if (mContainerView.getVisibility() == View.GONE) { - return; - } - - if (mShowHideAnimationEnabled) { - mContainerView.setAlpha(1); - mContainerView.setTransitioning(true); - AnimatorSet anim = new AnimatorSet(); - AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(mContainerView, "alpha", 0)); - if (mContentView != null) { - b.with(ObjectAnimator.ofFloat(mContentView, "translationY", - 0, -mContainerView.getHeight())); - b.with(ObjectAnimator.ofFloat(mContainerView, "translationY", - -mContainerView.getHeight())); - } - if (mSplitView != null && mSplitView.getVisibility() == View.VISIBLE) { - mSplitView.setAlpha(1); - b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 0)); - } - anim.addListener(mHideListener); - mCurrentShowAnim = anim; - anim.start(); - } else { - mHideListener.onAnimationEnd(null); - } - } - - public boolean isShowing() { - return mContainerView.getVisibility() == View.VISIBLE; - } - - void animateToMode(boolean toActionMode) { - if (toActionMode) { - show(false); - } - if (mCurrentModeAnim != null) { - mCurrentModeAnim.end(); - } - - mActionView.animateToVisibility(toActionMode ? View.GONE : View.VISIBLE); - mContextView.animateToVisibility(toActionMode ? View.VISIBLE : View.GONE); - if (mTabScrollView != null && !mActionView.hasEmbeddedTabs() && mActionView.isCollapsed()) { - mTabScrollView.animateToVisibility(toActionMode ? View.GONE : View.VISIBLE); - } - } - - public Context getThemedContext() { - if (mThemedContext == null) { - TypedValue outValue = new TypedValue(); - Resources.Theme currentTheme = mContext.getTheme(); - currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, - outValue, true); - final int targetThemeRes = outValue.resourceId; - - if (targetThemeRes != 0) { //XXX && mContext.getThemeResId() != targetThemeRes) { - mThemedContext = new ContextThemeWrapper(mContext, targetThemeRes); - } else { - mThemedContext = mContext; - } - } - return mThemedContext; - } - - /** - * @hide - */ - public class ActionModeImpl extends ActionMode implements MenuBuilder.Callback { - private ActionMode.Callback mCallback; - private MenuBuilder mMenu; - private WeakReference mCustomView; - - public ActionModeImpl(ActionMode.Callback callback) { - mCallback = callback; - mMenu = new MenuBuilder(getThemedContext()) - .setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); - mMenu.setCallback(this); - } - - @Override - public MenuInflater getMenuInflater() { - return new MenuInflater(getThemedContext()); - } - - @Override - public Menu getMenu() { - return mMenu; - } - - @Override - public void finish() { - if (mActionMode != this) { - // Not the active action mode - no-op - return; - } - - // If we were hidden before the mode was shown, defer the onDestroy - // callback until the animation is finished and associated relayout - // is about to happen. This lets apps better anticipate visibility - // and layout behavior. - if (mWasHiddenBeforeMode) { - mDeferredDestroyActionMode = this; - mDeferredModeDestroyCallback = mCallback; - } else { - mCallback.onDestroyActionMode(this); - } - mCallback = null; - animateToMode(false); - - // Clear out the context mode views after the animation finishes - mContextView.closeMode(); - mActionView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); - - mActionMode = null; - - if (mWasHiddenBeforeMode) { - hide(); - } - } - - @Override - public void invalidate() { - mMenu.stopDispatchingItemsChanged(); - try { - mCallback.onPrepareActionMode(this, mMenu); - } finally { - mMenu.startDispatchingItemsChanged(); - } - } - - public boolean dispatchOnCreate() { - mMenu.stopDispatchingItemsChanged(); - try { - return mCallback.onCreateActionMode(this, mMenu); - } finally { - mMenu.startDispatchingItemsChanged(); - } - } - - @Override - public void setCustomView(View view) { - mContextView.setCustomView(view); - mCustomView = new WeakReference(view); - } - - @Override - public void setSubtitle(CharSequence subtitle) { - mContextView.setSubtitle(subtitle); - } - - @Override - public void setTitle(CharSequence title) { - mContextView.setTitle(title); - } - - @Override - public void setTitle(int resId) { - setTitle(mContext.getResources().getString(resId)); - } - - @Override - public void setSubtitle(int resId) { - setSubtitle(mContext.getResources().getString(resId)); - } - - @Override - public CharSequence getTitle() { - return mContextView.getTitle(); - } - - @Override - public CharSequence getSubtitle() { - return mContextView.getSubtitle(); - } - - @Override - public View getCustomView() { - return mCustomView != null ? mCustomView.get() : null; - } - - public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { - if (mCallback != null) { - return mCallback.onActionItemClicked(this, item); - } else { - return false; - } - } - - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - } - - public boolean onSubMenuSelected(SubMenuBuilder subMenu) { - if (mCallback == null) { - return false; - } - - if (!subMenu.hasVisibleItems()) { - return true; - } - - new MenuPopupHelper(getThemedContext(), subMenu).show(); - return true; - } - - public void onCloseSubMenu(SubMenuBuilder menu) { - } - - public void onMenuModeChange(MenuBuilder menu) { - if (mCallback == null) { - return; - } - invalidate(); - mContextView.showOverflowMenu(); - } - } - - /** - * @hide - */ - public class TabImpl extends ActionBar.Tab { - private ActionBar.TabListener mCallback; - private Object mTag; - private Drawable mIcon; - private CharSequence mText; - private CharSequence mContentDesc; - private int mPosition = -1; - private View mCustomView; - - @Override - public Object getTag() { - return mTag; - } - - @Override - public Tab setTag(Object tag) { - mTag = tag; - return this; - } - - public ActionBar.TabListener getCallback() { - return mCallback; - } - - @Override - public Tab setTabListener(ActionBar.TabListener callback) { - mCallback = callback; - return this; - } - - @Override - public View getCustomView() { - return mCustomView; - } - - @Override - public Tab setCustomView(View view) { - mCustomView = view; - if (mPosition >= 0) { - mTabScrollView.updateTab(mPosition); - } - return this; - } - - @Override - public Tab setCustomView(int layoutResId) { - return setCustomView(LayoutInflater.from(getThemedContext()) - .inflate(layoutResId, null)); - } - - @Override - public Drawable getIcon() { - return mIcon; - } - - @Override - public int getPosition() { - return mPosition; - } - - public void setPosition(int position) { - mPosition = position; - } - - @Override - public CharSequence getText() { - return mText; - } - - @Override - public Tab setIcon(Drawable icon) { - mIcon = icon; - if (mPosition >= 0) { - mTabScrollView.updateTab(mPosition); - } - return this; - } - - @Override - public Tab setIcon(int resId) { - return setIcon(mContext.getResources().getDrawable(resId)); - } - - @Override - public Tab setText(CharSequence text) { - mText = text; - if (mPosition >= 0) { - mTabScrollView.updateTab(mPosition); - } - return this; - } - - @Override - public Tab setText(int resId) { - return setText(mContext.getResources().getText(resId)); - } - - @Override - public void select() { - selectTab(this); - } - - @Override - public Tab setContentDescription(int resId) { - return setContentDescription(mContext.getResources().getText(resId)); - } - - @Override - public Tab setContentDescription(CharSequence contentDesc) { - mContentDesc = contentDesc; - if (mPosition >= 0) { - mTabScrollView.updateTab(mPosition); - } - return this; - } - - @Override - public CharSequence getContentDescription() { - return mContentDesc; - } - } - - @Override - public void setCustomView(View view) { - mActionView.setCustomNavigationView(view); - } - - @Override - public void setCustomView(View view, LayoutParams layoutParams) { - view.setLayoutParams(layoutParams); - mActionView.setCustomNavigationView(view); - } - - @Override - public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) { - mActionView.setDropdownAdapter(adapter); - mActionView.setCallback(callback); - } - - @Override - public int getSelectedNavigationIndex() { - switch (mActionView.getNavigationMode()) { - case NAVIGATION_MODE_TABS: - return mSelectedTab != null ? mSelectedTab.getPosition() : -1; - case NAVIGATION_MODE_LIST: - return mActionView.getDropdownSelectedPosition(); - default: - return -1; - } - } - - @Override - public int getNavigationItemCount() { - switch (mActionView.getNavigationMode()) { - case NAVIGATION_MODE_TABS: - return mTabs.size(); - case NAVIGATION_MODE_LIST: - SpinnerAdapter adapter = mActionView.getDropdownAdapter(); - return adapter != null ? adapter.getCount() : 0; - default: - return 0; - } - } - - @Override - public int getTabCount() { - return mTabs.size(); - } - - @Override - public void setNavigationMode(int mode) { - final int oldMode = mActionView.getNavigationMode(); - switch (oldMode) { - case NAVIGATION_MODE_TABS: - mSavedTabPosition = getSelectedNavigationIndex(); - selectTab(null); - mTabScrollView.setVisibility(View.GONE); - break; - } - mActionView.setNavigationMode(mode); - switch (mode) { - case NAVIGATION_MODE_TABS: - ensureTabsExist(); - mTabScrollView.setVisibility(View.VISIBLE); - if (mSavedTabPosition != INVALID_POSITION) { - setSelectedNavigationItem(mSavedTabPosition); - mSavedTabPosition = INVALID_POSITION; - } - break; - } - mActionView.setCollapsable(mode == NAVIGATION_MODE_TABS && !mHasEmbeddedTabs); - } - - @Override - public Tab getTabAt(int index) { - return mTabs.get(index); - } - - - @Override - public void setIcon(int resId) { - mActionView.setIcon(resId); - } - - @Override - public void setIcon(Drawable icon) { - mActionView.setIcon(icon); - } - - @Override - public void setLogo(int resId) { - mActionView.setLogo(resId); - } - - @Override - public void setLogo(Drawable logo) { - mActionView.setLogo(logo); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarWrapper.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarWrapper.java deleted file mode 100644 index e390ea42..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarWrapper.java +++ /dev/null @@ -1,468 +0,0 @@ -package com.actionbarsherlock.internal.app; - -import java.util.HashSet; -import java.util.Set; - -import android.app.Activity; -import android.content.Context; -import android.graphics.drawable.Drawable; -import android.support.v4.app.FragmentTransaction; -import android.view.View; -import android.widget.SpinnerAdapter; - -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.app.SherlockFragmentActivity; - -public class ActionBarWrapper extends ActionBar implements android.app.ActionBar.OnNavigationListener, android.app.ActionBar.OnMenuVisibilityListener { - private final Activity mActivity; - private final android.app.ActionBar mActionBar; - private ActionBar.OnNavigationListener mNavigationListener; - private Set mMenuVisibilityListeners = new HashSet(1); - private FragmentTransaction mFragmentTransaction; - - - public ActionBarWrapper(Activity activity) { - mActivity = activity; - mActionBar = activity.getActionBar(); - if (mActionBar != null) { - mActionBar.addOnMenuVisibilityListener(this); - } - } - - - @Override - public void setHomeButtonEnabled(boolean enabled) { - mActionBar.setHomeButtonEnabled(enabled); - } - - @Override - public Context getThemedContext() { - return mActionBar.getThemedContext(); - } - - @Override - public void setCustomView(View view) { - mActionBar.setCustomView(view); - } - - @Override - public void setCustomView(View view, LayoutParams layoutParams) { - android.app.ActionBar.LayoutParams lp = new android.app.ActionBar.LayoutParams(layoutParams); - lp.gravity = layoutParams.gravity; - lp.bottomMargin = layoutParams.bottomMargin; - lp.topMargin = layoutParams.topMargin; - lp.leftMargin = layoutParams.leftMargin; - lp.rightMargin = layoutParams.rightMargin; - mActionBar.setCustomView(view, lp); - } - - @Override - public void setCustomView(int resId) { - mActionBar.setCustomView(resId); - } - - @Override - public void setIcon(int resId) { - mActionBar.setIcon(resId); - } - - @Override - public void setIcon(Drawable icon) { - mActionBar.setIcon(icon); - } - - @Override - public void setLogo(int resId) { - mActionBar.setLogo(resId); - } - - @Override - public void setLogo(Drawable logo) { - mActionBar.setLogo(logo); - } - - @Override - public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) { - mNavigationListener = callback; - mActionBar.setListNavigationCallbacks(adapter, (callback != null) ? this : null); - } - - @Override - public boolean onNavigationItemSelected(int itemPosition, long itemId) { - //This should never be a NullPointerException since we only set - //ourselves as the listener when the callback is not null. - return mNavigationListener.onNavigationItemSelected(itemPosition, itemId); - } - - @Override - public void setSelectedNavigationItem(int position) { - mActionBar.setSelectedNavigationItem(position); - } - - @Override - public int getSelectedNavigationIndex() { - return mActionBar.getSelectedNavigationIndex(); - } - - @Override - public int getNavigationItemCount() { - return mActionBar.getNavigationItemCount(); - } - - @Override - public void setTitle(CharSequence title) { - mActionBar.setTitle(title); - } - - @Override - public void setTitle(int resId) { - mActionBar.setTitle(resId); - } - - @Override - public void setSubtitle(CharSequence subtitle) { - mActionBar.setSubtitle(subtitle); - } - - @Override - public void setSubtitle(int resId) { - mActionBar.setSubtitle(resId); - } - - @Override - public void setDisplayOptions(int options) { - mActionBar.setDisplayOptions(options); - } - - @Override - public void setDisplayOptions(int options, int mask) { - mActionBar.setDisplayOptions(options, mask); - } - - @Override - public void setDisplayUseLogoEnabled(boolean useLogo) { - mActionBar.setDisplayUseLogoEnabled(useLogo); - } - - @Override - public void setDisplayShowHomeEnabled(boolean showHome) { - mActionBar.setDisplayShowHomeEnabled(showHome); - } - - @Override - public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) { - mActionBar.setDisplayHomeAsUpEnabled(showHomeAsUp); - } - - @Override - public void setDisplayShowTitleEnabled(boolean showTitle) { - mActionBar.setDisplayShowTitleEnabled(showTitle); - } - - @Override - public void setDisplayShowCustomEnabled(boolean showCustom) { - mActionBar.setDisplayShowCustomEnabled(showCustom); - } - - @Override - public void setBackgroundDrawable(Drawable d) { - mActionBar.setBackgroundDrawable(d); - } - - @Override - public void setStackedBackgroundDrawable(Drawable d) { - mActionBar.setStackedBackgroundDrawable(d); - } - - @Override - public void setSplitBackgroundDrawable(Drawable d) { - mActionBar.setSplitBackgroundDrawable(d); - } - - @Override - public View getCustomView() { - return mActionBar.getCustomView(); - } - - @Override - public CharSequence getTitle() { - return mActionBar.getTitle(); - } - - @Override - public CharSequence getSubtitle() { - return mActionBar.getSubtitle(); - } - - @Override - public int getNavigationMode() { - return mActionBar.getNavigationMode(); - } - - @Override - public void setNavigationMode(int mode) { - mActionBar.setNavigationMode(mode); - } - - @Override - public int getDisplayOptions() { - return mActionBar.getDisplayOptions(); - } - - public class TabWrapper extends ActionBar.Tab implements android.app.ActionBar.TabListener { - final android.app.ActionBar.Tab mNativeTab; - private Object mTag; - private TabListener mListener; - - public TabWrapper(android.app.ActionBar.Tab nativeTab) { - mNativeTab = nativeTab; - mNativeTab.setTag(this); - } - - @Override - public int getPosition() { - return mNativeTab.getPosition(); - } - - @Override - public Drawable getIcon() { - return mNativeTab.getIcon(); - } - - @Override - public CharSequence getText() { - return mNativeTab.getText(); - } - - @Override - public Tab setIcon(Drawable icon) { - mNativeTab.setIcon(icon); - return this; - } - - @Override - public Tab setIcon(int resId) { - mNativeTab.setIcon(resId); - return this; - } - - @Override - public Tab setText(CharSequence text) { - mNativeTab.setText(text); - return this; - } - - @Override - public Tab setText(int resId) { - mNativeTab.setText(resId); - return this; - } - - @Override - public Tab setCustomView(View view) { - mNativeTab.setCustomView(view); - return this; - } - - @Override - public Tab setCustomView(int layoutResId) { - mNativeTab.setCustomView(layoutResId); - return this; - } - - @Override - public View getCustomView() { - return mNativeTab.getCustomView(); - } - - @Override - public Tab setTag(Object obj) { - mTag = obj; - return this; - } - - @Override - public Object getTag() { - return mTag; - } - - @Override - public Tab setTabListener(TabListener listener) { - mNativeTab.setTabListener(listener != null ? this : null); - mListener = listener; - return this; - } - - @Override - public void select() { - mNativeTab.select(); - } - - @Override - public Tab setContentDescription(int resId) { - mNativeTab.setContentDescription(resId); - return this; - } - - @Override - public Tab setContentDescription(CharSequence contentDesc) { - mNativeTab.setContentDescription(contentDesc); - return this; - } - - @Override - public CharSequence getContentDescription() { - return mNativeTab.getContentDescription(); - } - - @Override - public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) { - if (mListener != null) { - FragmentTransaction trans = null; - if (mActivity instanceof SherlockFragmentActivity) { - trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() - .disallowAddToBackStack(); - } - - mListener.onTabReselected(this, trans); - - if (trans != null && !trans.isEmpty()) { - trans.commit(); - } - } - } - - @Override - public void onTabSelected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) { - if (mListener != null) { - - if (mFragmentTransaction == null && mActivity instanceof SherlockFragmentActivity) { - mFragmentTransaction = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() - .disallowAddToBackStack(); - } - - mListener.onTabSelected(this, mFragmentTransaction); - - if (mFragmentTransaction != null) { - if (!mFragmentTransaction.isEmpty()) { - mFragmentTransaction.commit(); - } - mFragmentTransaction = null; - } - } - } - - @Override - public void onTabUnselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) { - if (mListener != null) { - FragmentTransaction trans = null; - if (mActivity instanceof SherlockFragmentActivity) { - trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() - .disallowAddToBackStack(); - mFragmentTransaction = trans; - } - - mListener.onTabUnselected(this, trans); - } - } - } - - @Override - public Tab newTab() { - return new TabWrapper(mActionBar.newTab()); - } - - @Override - public void addTab(Tab tab) { - mActionBar.addTab(((TabWrapper)tab).mNativeTab); - } - - @Override - public void addTab(Tab tab, boolean setSelected) { - mActionBar.addTab(((TabWrapper)tab).mNativeTab, setSelected); - } - - @Override - public void addTab(Tab tab, int position) { - mActionBar.addTab(((TabWrapper)tab).mNativeTab, position); - } - - @Override - public void addTab(Tab tab, int position, boolean setSelected) { - mActionBar.addTab(((TabWrapper)tab).mNativeTab, position, setSelected); - } - - @Override - public void removeTab(Tab tab) { - mActionBar.removeTab(((TabWrapper)tab).mNativeTab); - } - - @Override - public void removeTabAt(int position) { - mActionBar.removeTabAt(position); - } - - @Override - public void removeAllTabs() { - mActionBar.removeAllTabs(); - } - - @Override - public void selectTab(Tab tab) { - mActionBar.selectTab(((TabWrapper)tab).mNativeTab); - } - - @Override - public Tab getSelectedTab() { - android.app.ActionBar.Tab selected = mActionBar.getSelectedTab(); - return (selected != null) ? (Tab)selected.getTag() : null; - } - - @Override - public Tab getTabAt(int index) { - android.app.ActionBar.Tab selected = mActionBar.getTabAt(index); - return (selected != null) ? (Tab)selected.getTag() : null; - } - - @Override - public int getTabCount() { - return mActionBar.getTabCount(); - } - - @Override - public int getHeight() { - return mActionBar.getHeight(); - } - - @Override - public void show() { - mActionBar.show(); - } - - @Override - public void hide() { - mActionBar.hide(); - } - - @Override - public boolean isShowing() { - return mActionBar.isShowing(); - } - - @Override - public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) { - mMenuVisibilityListeners.add(listener); - } - - @Override - public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) { - mMenuVisibilityListeners.remove(listener); - } - - @Override - public void onMenuVisibilityChanged(boolean isVisible) { - for (OnMenuVisibilityListener listener : mMenuVisibilityListeners) { - listener.onMenuVisibilityChanged(isVisible); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.java deleted file mode 100644 index 2caf5b4a..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import java.util.ArrayList; - -import android.view.animation.Interpolator; - -/** - * This is the superclass for classes which provide basic support for animations which can be - * started, ended, and have AnimatorListeners added to them. - */ -public abstract class Animator implements Cloneable { - - - /** - * The set of listeners to be sent events through the life of an animation. - */ - ArrayList mListeners = null; - - /** - * Starts this animation. If the animation has a nonzero startDelay, the animation will start - * running after that delay elapses. A non-delayed animation will have its initial - * value(s) set immediately, followed by calls to - * {@link AnimatorListener#onAnimationStart(Animator)} for any listeners of this animator. - * - *

The animation started by calling this method will be run on the thread that called - * this method. This thread should have a Looper on it (a runtime exception will be thrown if - * this is not the case). Also, if the animation will animate - * properties of objects in the view hierarchy, then the calling thread should be the UI - * thread for that view hierarchy.

- * - */ - public void start() { - } - - /** - * Cancels the animation. Unlike {@link #end()}, cancel() causes the animation to - * stop in its tracks, sending an - * {@link android.animation.Animator.AnimatorListener#onAnimationCancel(Animator)} to - * its listeners, followed by an - * {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} message. - * - *

This method must be called on the thread that is running the animation.

- */ - public void cancel() { - } - - /** - * Ends the animation. This causes the animation to assign the end value of the property being - * animated, then calling the - * {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} method on - * its listeners. - * - *

This method must be called on the thread that is running the animation.

- */ - public void end() { - } - - /** - * The amount of time, in milliseconds, to delay starting the animation after - * {@link #start()} is called. - * - * @return the number of milliseconds to delay running the animation - */ - public abstract long getStartDelay(); - - /** - * The amount of time, in milliseconds, to delay starting the animation after - * {@link #start()} is called. - - * @param startDelay The amount of the delay, in milliseconds - */ - public abstract void setStartDelay(long startDelay); - - - /** - * Sets the length of the animation. - * - * @param duration The length of the animation, in milliseconds. - */ - public abstract Animator setDuration(long duration); - - /** - * Gets the length of the animation. - * - * @return The length of the animation, in milliseconds. - */ - public abstract long getDuration(); - - /** - * The time interpolator used in calculating the elapsed fraction of this animation. The - * interpolator determines whether the animation runs with linear or non-linear motion, - * such as acceleration and deceleration. The default value is - * {@link android.view.animation.AccelerateDecelerateInterpolator} - * - * @param value the interpolator to be used by this animation - */ - public abstract void setInterpolator(/*Time*/Interpolator value); - - /** - * Returns whether this Animator is currently running (having been started and gone past any - * initial startDelay period and not yet ended). - * - * @return Whether the Animator is running. - */ - public abstract boolean isRunning(); - - /** - * Returns whether this Animator has been started and not yet ended. This state is a superset - * of the state of {@link #isRunning()}, because an Animator with a nonzero - * {@link #getStartDelay() startDelay} will return true for {@link #isStarted()} during the - * delay phase, whereas {@link #isRunning()} will return true only after the delay phase - * is complete. - * - * @return Whether the Animator has been started and not yet ended. - */ - public boolean isStarted() { - // Default method returns value for isRunning(). Subclasses should override to return a - // real value. - return isRunning(); - } - - /** - * Adds a listener to the set of listeners that are sent events through the life of an - * animation, such as start, repeat, and end. - * - * @param listener the listener to be added to the current set of listeners for this animation. - */ - public void addListener(AnimatorListener listener) { - if (mListeners == null) { - mListeners = new ArrayList(); - } - mListeners.add(listener); - } - - /** - * Removes a listener from the set listening to this animation. - * - * @param listener the listener to be removed from the current set of listeners for this - * animation. - */ - public void removeListener(AnimatorListener listener) { - if (mListeners == null) { - return; - } - mListeners.remove(listener); - if (mListeners.size() == 0) { - mListeners = null; - } - } - - /** - * Gets the set of {@link android.animation.Animator.AnimatorListener} objects that are currently - * listening for events on this Animator object. - * - * @return ArrayList The set of listeners. - */ - public ArrayList getListeners() { - return mListeners; - } - - /** - * Removes all listeners from this object. This is equivalent to calling - * getListeners() followed by calling clear() on the - * returned list of listeners. - */ - public void removeAllListeners() { - if (mListeners != null) { - mListeners.clear(); - mListeners = null; - } - } - - @Override - public Animator clone() { - try { - final Animator anim = (Animator) super.clone(); - if (mListeners != null) { - ArrayList oldListeners = mListeners; - anim.mListeners = new ArrayList(); - int numListeners = oldListeners.size(); - for (int i = 0; i < numListeners; ++i) { - anim.mListeners.add(oldListeners.get(i)); - } - } - return anim; - } catch (CloneNotSupportedException e) { - throw new AssertionError(); - } - } - - /** - * This method tells the object to use appropriate information to extract - * starting values for the animation. For example, a AnimatorSet object will pass - * this call to its child objects to tell them to set up the values. A - * ObjectAnimator object will use the information it has about its target object - * and PropertyValuesHolder objects to get the start values for its properties. - * An ValueAnimator object will ignore the request since it does not have enough - * information (such as a target object) to gather these values. - */ - public void setupStartValues() { - } - - /** - * This method tells the object to use appropriate information to extract - * ending values for the animation. For example, a AnimatorSet object will pass - * this call to its child objects to tell them to set up the values. A - * ObjectAnimator object will use the information it has about its target object - * and PropertyValuesHolder objects to get the start values for its properties. - * An ValueAnimator object will ignore the request since it does not have enough - * information (such as a target object) to gather these values. - */ - public void setupEndValues() { - } - - /** - * Sets the target object whose property will be animated by this animation. Not all subclasses - * operate on target objects (for example, {@link ValueAnimator}, but this method - * is on the superclass for the convenience of dealing generically with those subclasses - * that do handle targets. - * - * @param target The object being animated - */ - public void setTarget(Object target) { - } - - /** - *

An animation listener receives notifications from an animation. - * Notifications indicate animation related events, such as the end or the - * repetition of the animation.

- */ - public static interface AnimatorListener { - /** - *

Notifies the start of the animation.

- * - * @param animation The started animation. - */ - void onAnimationStart(Animator animation); - - /** - *

Notifies the end of the animation. This callback is not invoked - * for animations with repeat count set to INFINITE.

- * - * @param animation The animation which reached its end. - */ - void onAnimationEnd(Animator animation); - - /** - *

Notifies the cancellation of the animation. This callback is not invoked - * for animations with repeat count set to INFINITE.

- * - * @param animation The animation which was canceled. - */ - void onAnimationCancel(Animator animation); - - /** - *

Notifies the repetition of the animation.

- * - * @param animation The animation which was repeated. - */ - void onAnimationRepeat(Animator animation); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.java deleted file mode 100644 index 02ddff48..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -/** - * This adapter class provides empty implementations of the methods from {@link android.animation.Animator.AnimatorListener}. - * Any custom listener that cares only about a subset of the methods of this listener can - * simply subclass this adapter class instead of implementing the interface directly. - */ -public abstract class AnimatorListenerAdapter implements Animator.AnimatorListener { - - /** - * {@inheritDoc} - */ - @Override - public void onAnimationCancel(Animator animation) { - } - - /** - * {@inheritDoc} - */ - @Override - public void onAnimationEnd(Animator animation) { - } - - /** - * {@inheritDoc} - */ - @Override - public void onAnimationRepeat(Animator animation) { - } - - /** - * {@inheritDoc} - */ - @Override - public void onAnimationStart(Animator animation) { - } - -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.java deleted file mode 100644 index 3231080c..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.java +++ /dev/null @@ -1,1111 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; - -import android.view.animation.Interpolator; - -/** - * This class plays a set of {@link Animator} objects in the specified order. Animations - * can be set up to play together, in sequence, or after a specified delay. - * - *

There are two different approaches to adding animations to a AnimatorSet: - * either the {@link AnimatorSet#playTogether(Animator[]) playTogether()} or - * {@link AnimatorSet#playSequentially(Animator[]) playSequentially()} methods can be called to add - * a set of animations all at once, or the {@link AnimatorSet#play(Animator)} can be - * used in conjunction with methods in the {@link AnimatorSet.Builder Builder} - * class to add animations - * one by one.

- * - *

It is possible to set up a AnimatorSet with circular dependencies between - * its animations. For example, an animation a1 could be set up to start before animation a2, a2 - * before a3, and a3 before a1. The results of this configuration are undefined, but will typically - * result in none of the affected animations being played. Because of this (and because - * circular dependencies do not make logical sense anyway), circular dependencies - * should be avoided, and the dependency flow of animations should only be in one direction. - */ -@SuppressWarnings("unchecked") -public final class AnimatorSet extends Animator { - - /** - * Internal variables - * NOTE: This object implements the clone() method, making a deep copy of any referenced - * objects. As other non-trivial fields are added to this class, make sure to add logic - * to clone() to make deep copies of them. - */ - - /** - * Tracks animations currently being played, so that we know what to - * cancel or end when cancel() or end() is called on this AnimatorSet - */ - private ArrayList mPlayingSet = new ArrayList(); - - /** - * Contains all nodes, mapped to their respective Animators. When new - * dependency information is added for an Animator, we want to add it - * to a single node representing that Animator, not create a new Node - * if one already exists. - */ - private HashMap mNodeMap = new HashMap(); - - /** - * Set of all nodes created for this AnimatorSet. This list is used upon - * starting the set, and the nodes are placed in sorted order into the - * sortedNodes collection. - */ - private ArrayList mNodes = new ArrayList(); - - /** - * The sorted list of nodes. This is the order in which the animations will - * be played. The details about when exactly they will be played depend - * on the dependency relationships of the nodes. - */ - private ArrayList mSortedNodes = new ArrayList(); - - /** - * Flag indicating whether the nodes should be sorted prior to playing. This - * flag allows us to cache the previous sorted nodes so that if the sequence - * is replayed with no changes, it does not have to re-sort the nodes again. - */ - private boolean mNeedsSort = true; - - private AnimatorSetListener mSetListener = null; - - /** - * Flag indicating that the AnimatorSet has been manually - * terminated (by calling cancel() or end()). - * This flag is used to avoid starting other animations when currently-playing - * child animations of this AnimatorSet end. It also determines whether cancel/end - * notifications are sent out via the normal AnimatorSetListener mechanism. - */ - boolean mTerminated = false; - - /** - * Indicates whether an AnimatorSet has been start()'d, whether or - * not there is a nonzero startDelay. - */ - private boolean mStarted = false; - - // The amount of time in ms to delay starting the animation after start() is called - private long mStartDelay = 0; - - // Animator used for a nonzero startDelay - private ValueAnimator mDelayAnim = null; - - - // How long the child animations should last in ms. The default value is negative, which - // simply means that there is no duration set on the AnimatorSet. When a real duration is - // set, it is passed along to the child animations. - private long mDuration = -1; - - - /** - * Sets up this AnimatorSet to play all of the supplied animations at the same time. - * - * @param items The animations that will be started simultaneously. - */ - public void playTogether(Animator... items) { - if (items != null) { - mNeedsSort = true; - Builder builder = play(items[0]); - for (int i = 1; i < items.length; ++i) { - builder.with(items[i]); - } - } - } - - /** - * Sets up this AnimatorSet to play all of the supplied animations at the same time. - * - * @param items The animations that will be started simultaneously. - */ - public void playTogether(Collection items) { - if (items != null && items.size() > 0) { - mNeedsSort = true; - Builder builder = null; - for (Animator anim : items) { - if (builder == null) { - builder = play(anim); - } else { - builder.with(anim); - } - } - } - } - - /** - * Sets up this AnimatorSet to play each of the supplied animations when the - * previous animation ends. - * - * @param items The animations that will be started one after another. - */ - public void playSequentially(Animator... items) { - if (items != null) { - mNeedsSort = true; - if (items.length == 1) { - play(items[0]); - } else { - for (int i = 0; i < items.length - 1; ++i) { - play(items[i]).before(items[i+1]); - } - } - } - } - - /** - * Sets up this AnimatorSet to play each of the supplied animations when the - * previous animation ends. - * - * @param items The animations that will be started one after another. - */ - public void playSequentially(List items) { - if (items != null && items.size() > 0) { - mNeedsSort = true; - if (items.size() == 1) { - play(items.get(0)); - } else { - for (int i = 0; i < items.size() - 1; ++i) { - play(items.get(i)).before(items.get(i+1)); - } - } - } - } - - /** - * Returns the current list of child Animator objects controlled by this - * AnimatorSet. This is a copy of the internal list; modifications to the returned list - * will not affect the AnimatorSet, although changes to the underlying Animator objects - * will affect those objects being managed by the AnimatorSet. - * - * @return ArrayList The list of child animations of this AnimatorSet. - */ - public ArrayList getChildAnimations() { - ArrayList childList = new ArrayList(); - for (Node node : mNodes) { - childList.add(node.animation); - } - return childList; - } - - /** - * Sets the target object for all current {@link #getChildAnimations() child animations} - * of this AnimatorSet that take targets ({@link ObjectAnimator} and - * AnimatorSet). - * - * @param target The object being animated - */ - @Override - public void setTarget(Object target) { - for (Node node : mNodes) { - Animator animation = node.animation; - if (animation instanceof AnimatorSet) { - ((AnimatorSet)animation).setTarget(target); - } else if (animation instanceof ObjectAnimator) { - ((ObjectAnimator)animation).setTarget(target); - } - } - } - - /** - * Sets the TimeInterpolator for all current {@link #getChildAnimations() child animations} - * of this AnimatorSet. - * - * @param interpolator the interpolator to be used by each child animation of this AnimatorSet - */ - @Override - public void setInterpolator(/*Time*/Interpolator interpolator) { - for (Node node : mNodes) { - node.animation.setInterpolator(interpolator); - } - } - - /** - * This method creates a Builder object, which is used to - * set up playing constraints. This initial play() method - * tells the Builder the animation that is the dependency for - * the succeeding commands to the Builder. For example, - * calling play(a1).with(a2) sets up the AnimatorSet to play - * a1 and a2 at the same time, - * play(a1).before(a2) sets up the AnimatorSet to play - * a1 first, followed by a2, and - * play(a1).after(a2) sets up the AnimatorSet to play - * a2 first, followed by a1. - * - *

Note that play() is the only way to tell the - * Builder the animation upon which the dependency is created, - * so successive calls to the various functions in Builder - * will all refer to the initial parameter supplied in play() - * as the dependency of the other animations. For example, calling - * play(a1).before(a2).before(a3) will play both a2 - * and a3 when a1 ends; it does not set up a dependency between - * a2 and a3.

- * - * @param anim The animation that is the dependency used in later calls to the - * methods in the returned Builder object. A null parameter will result - * in a null Builder return value. - * @return Builder The object that constructs the AnimatorSet based on the dependencies - * outlined in the calls to play and the other methods in the - * BuilderNote that canceling a AnimatorSet also cancels all of the animations that it - * is responsible for.

- */ - @Override - public void cancel() { - mTerminated = true; - if (isStarted()) { - ArrayList tmpListeners = null; - if (mListeners != null) { - tmpListeners = (ArrayList) mListeners.clone(); - for (AnimatorListener listener : tmpListeners) { - listener.onAnimationCancel(this); - } - } - if (mDelayAnim != null && mDelayAnim.isRunning()) { - // If we're currently in the startDelay period, just cancel that animator and - // send out the end event to all listeners - mDelayAnim.cancel(); - } else if (mSortedNodes.size() > 0) { - for (Node node : mSortedNodes) { - node.animation.cancel(); - } - } - if (tmpListeners != null) { - for (AnimatorListener listener : tmpListeners) { - listener.onAnimationEnd(this); - } - } - mStarted = false; - } - } - - /** - * {@inheritDoc} - * - *

Note that ending a AnimatorSet also ends all of the animations that it is - * responsible for.

- */ - @Override - public void end() { - mTerminated = true; - if (isStarted()) { - if (mSortedNodes.size() != mNodes.size()) { - // hasn't been started yet - sort the nodes now, then end them - sortNodes(); - for (Node node : mSortedNodes) { - if (mSetListener == null) { - mSetListener = new AnimatorSetListener(this); - } - node.animation.addListener(mSetListener); - } - } - if (mDelayAnim != null) { - mDelayAnim.cancel(); - } - if (mSortedNodes.size() > 0) { - for (Node node : mSortedNodes) { - node.animation.end(); - } - } - if (mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - for (AnimatorListener listener : tmpListeners) { - listener.onAnimationEnd(this); - } - } - mStarted = false; - } - } - - /** - * Returns true if any of the child animations of this AnimatorSet have been started and have - * not yet ended. - * @return Whether this AnimatorSet has been started and has not yet ended. - */ - @Override - public boolean isRunning() { - for (Node node : mNodes) { - if (node.animation.isRunning()) { - return true; - } - } - return false; - } - - @Override - public boolean isStarted() { - return mStarted; - } - - /** - * The amount of time, in milliseconds, to delay starting the animation after - * {@link #start()} is called. - * - * @return the number of milliseconds to delay running the animation - */ - @Override - public long getStartDelay() { - return mStartDelay; - } - - /** - * The amount of time, in milliseconds, to delay starting the animation after - * {@link #start()} is called. - - * @param startDelay The amount of the delay, in milliseconds - */ - @Override - public void setStartDelay(long startDelay) { - mStartDelay = startDelay; - } - - /** - * Gets the length of each of the child animations of this AnimatorSet. This value may - * be less than 0, which indicates that no duration has been set on this AnimatorSet - * and each of the child animations will use their own duration. - * - * @return The length of the animation, in milliseconds, of each of the child - * animations of this AnimatorSet. - */ - @Override - public long getDuration() { - return mDuration; - } - - /** - * Sets the length of each of the current child animations of this AnimatorSet. By default, - * each child animation will use its own duration. If the duration is set on the AnimatorSet, - * then each child animation inherits this duration. - * - * @param duration The length of the animation, in milliseconds, of each of the child - * animations of this AnimatorSet. - */ - @Override - public AnimatorSet setDuration(long duration) { - if (duration < 0) { - throw new IllegalArgumentException("duration must be a value of zero or greater"); - } - for (Node node : mNodes) { - // TODO: don't set the duration of the timing-only nodes created by AnimatorSet to - // insert "play-after" delays - node.animation.setDuration(duration); - } - mDuration = duration; - return this; - } - - @Override - public void setupStartValues() { - for (Node node : mNodes) { - node.animation.setupStartValues(); - } - } - - @Override - public void setupEndValues() { - for (Node node : mNodes) { - node.animation.setupEndValues(); - } - } - - /** - * {@inheritDoc} - * - *

Starting this AnimatorSet will, in turn, start the animations for which - * it is responsible. The details of when exactly those animations are started depends on - * the dependency relationships that have been set up between the animations. - */ - @Override - public void start() { - mTerminated = false; - mStarted = true; - - // First, sort the nodes (if necessary). This will ensure that sortedNodes - // contains the animation nodes in the correct order. - sortNodes(); - - int numSortedNodes = mSortedNodes.size(); - for (int i = 0; i < numSortedNodes; ++i) { - Node node = mSortedNodes.get(i); - // First, clear out the old listeners - ArrayList oldListeners = node.animation.getListeners(); - if (oldListeners != null && oldListeners.size() > 0) { - final ArrayList clonedListeners = new - ArrayList(oldListeners); - - for (AnimatorListener listener : clonedListeners) { - if (listener instanceof DependencyListener || - listener instanceof AnimatorSetListener) { - node.animation.removeListener(listener); - } - } - } - } - - // nodesToStart holds the list of nodes to be started immediately. We don't want to - // start the animations in the loop directly because we first need to set up - // dependencies on all of the nodes. For example, we don't want to start an animation - // when some other animation also wants to start when the first animation begins. - final ArrayList nodesToStart = new ArrayList(); - for (int i = 0; i < numSortedNodes; ++i) { - Node node = mSortedNodes.get(i); - if (mSetListener == null) { - mSetListener = new AnimatorSetListener(this); - } - if (node.dependencies == null || node.dependencies.size() == 0) { - nodesToStart.add(node); - } else { - int numDependencies = node.dependencies.size(); - for (int j = 0; j < numDependencies; ++j) { - Dependency dependency = node.dependencies.get(j); - dependency.node.animation.addListener( - new DependencyListener(this, node, dependency.rule)); - } - node.tmpDependencies = (ArrayList) node.dependencies.clone(); - } - node.animation.addListener(mSetListener); - } - // Now that all dependencies are set up, start the animations that should be started. - if (mStartDelay <= 0) { - for (Node node : nodesToStart) { - node.animation.start(); - mPlayingSet.add(node.animation); - } - } else { - mDelayAnim = ValueAnimator.ofFloat(0f, 1f); - mDelayAnim.setDuration(mStartDelay); - mDelayAnim.addListener(new AnimatorListenerAdapter() { - boolean canceled = false; - public void onAnimationCancel(Animator anim) { - canceled = true; - } - public void onAnimationEnd(Animator anim) { - if (!canceled) { - int numNodes = nodesToStart.size(); - for (int i = 0; i < numNodes; ++i) { - Node node = nodesToStart.get(i); - node.animation.start(); - mPlayingSet.add(node.animation); - } - } - } - }); - mDelayAnim.start(); - } - if (mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - int numListeners = tmpListeners.size(); - for (int i = 0; i < numListeners; ++i) { - tmpListeners.get(i).onAnimationStart(this); - } - } - if (mNodes.size() == 0 && mStartDelay == 0) { - // Handle unusual case where empty AnimatorSet is started - should send out - // end event immediately since the event will not be sent out at all otherwise - mStarted = false; - if (mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - int numListeners = tmpListeners.size(); - for (int i = 0; i < numListeners; ++i) { - tmpListeners.get(i).onAnimationEnd(this); - } - } - } - } - - @Override - public AnimatorSet clone() { - final AnimatorSet anim = (AnimatorSet) super.clone(); - /* - * The basic clone() operation copies all items. This doesn't work very well for - * AnimatorSet, because it will copy references that need to be recreated and state - * that may not apply. What we need to do now is put the clone in an uninitialized - * state, with fresh, empty data structures. Then we will build up the nodes list - * manually, as we clone each Node (and its animation). The clone will then be sorted, - * and will populate any appropriate lists, when it is started. - */ - anim.mNeedsSort = true; - anim.mTerminated = false; - anim.mStarted = false; - anim.mPlayingSet = new ArrayList(); - anim.mNodeMap = new HashMap(); - anim.mNodes = new ArrayList(); - anim.mSortedNodes = new ArrayList(); - - // Walk through the old nodes list, cloning each node and adding it to the new nodemap. - // One problem is that the old node dependencies point to nodes in the old AnimatorSet. - // We need to track the old/new nodes in order to reconstruct the dependencies in the clone. - HashMap nodeCloneMap = new HashMap(); // - for (Node node : mNodes) { - Node nodeClone = node.clone(); - nodeCloneMap.put(node, nodeClone); - anim.mNodes.add(nodeClone); - anim.mNodeMap.put(nodeClone.animation, nodeClone); - // Clear out the dependencies in the clone; we'll set these up manually later - nodeClone.dependencies = null; - nodeClone.tmpDependencies = null; - nodeClone.nodeDependents = null; - nodeClone.nodeDependencies = null; - // clear out any listeners that were set up by the AnimatorSet; these will - // be set up when the clone's nodes are sorted - ArrayList cloneListeners = nodeClone.animation.getListeners(); - if (cloneListeners != null) { - ArrayList listenersToRemove = null; - for (AnimatorListener listener : cloneListeners) { - if (listener instanceof AnimatorSetListener) { - if (listenersToRemove == null) { - listenersToRemove = new ArrayList(); - } - listenersToRemove.add(listener); - } - } - if (listenersToRemove != null) { - for (AnimatorListener listener : listenersToRemove) { - cloneListeners.remove(listener); - } - } - } - } - // Now that we've cloned all of the nodes, we're ready to walk through their - // dependencies, mapping the old dependencies to the new nodes - for (Node node : mNodes) { - Node nodeClone = nodeCloneMap.get(node); - if (node.dependencies != null) { - for (Dependency dependency : node.dependencies) { - Node clonedDependencyNode = nodeCloneMap.get(dependency.node); - Dependency cloneDependency = new Dependency(clonedDependencyNode, - dependency.rule); - nodeClone.addDependency(cloneDependency); - } - } - } - - return anim; - } - - /** - * This class is the mechanism by which animations are started based on events in other - * animations. If an animation has multiple dependencies on other animations, then - * all dependencies must be satisfied before the animation is started. - */ - private static class DependencyListener implements AnimatorListener { - - private AnimatorSet mAnimatorSet; - - // The node upon which the dependency is based. - private Node mNode; - - // The Dependency rule (WITH or AFTER) that the listener should wait for on - // the node - private int mRule; - - public DependencyListener(AnimatorSet animatorSet, Node node, int rule) { - this.mAnimatorSet = animatorSet; - this.mNode = node; - this.mRule = rule; - } - - /** - * Ignore cancel events for now. We may want to handle this eventually, - * to prevent follow-on animations from running when some dependency - * animation is canceled. - */ - public void onAnimationCancel(Animator animation) { - } - - /** - * An end event is received - see if this is an event we are listening for - */ - public void onAnimationEnd(Animator animation) { - if (mRule == Dependency.AFTER) { - startIfReady(animation); - } - } - - /** - * Ignore repeat events for now - */ - public void onAnimationRepeat(Animator animation) { - } - - /** - * A start event is received - see if this is an event we are listening for - */ - public void onAnimationStart(Animator animation) { - if (mRule == Dependency.WITH) { - startIfReady(animation); - } - } - - /** - * Check whether the event received is one that the node was waiting for. - * If so, mark it as complete and see whether it's time to start - * the animation. - * @param dependencyAnimation the animation that sent the event. - */ - private void startIfReady(Animator dependencyAnimation) { - if (mAnimatorSet.mTerminated) { - // if the parent AnimatorSet was canceled, then don't start any dependent anims - return; - } - Dependency dependencyToRemove = null; - int numDependencies = mNode.tmpDependencies.size(); - for (int i = 0; i < numDependencies; ++i) { - Dependency dependency = mNode.tmpDependencies.get(i); - if (dependency.rule == mRule && - dependency.node.animation == dependencyAnimation) { - // rule fired - remove the dependency and listener and check to - // see whether it's time to start the animation - dependencyToRemove = dependency; - dependencyAnimation.removeListener(this); - break; - } - } - mNode.tmpDependencies.remove(dependencyToRemove); - if (mNode.tmpDependencies.size() == 0) { - // all dependencies satisfied: start the animation - mNode.animation.start(); - mAnimatorSet.mPlayingSet.add(mNode.animation); - } - } - - } - - private class AnimatorSetListener implements AnimatorListener { - - private AnimatorSet mAnimatorSet; - - AnimatorSetListener(AnimatorSet animatorSet) { - mAnimatorSet = animatorSet; - } - - public void onAnimationCancel(Animator animation) { - if (!mTerminated) { - // Listeners are already notified of the AnimatorSet canceling in cancel(). - // The logic below only kicks in when animations end normally - if (mPlayingSet.size() == 0) { - if (mListeners != null) { - int numListeners = mListeners.size(); - for (int i = 0; i < numListeners; ++i) { - mListeners.get(i).onAnimationCancel(mAnimatorSet); - } - } - } - } - } - - public void onAnimationEnd(Animator animation) { - animation.removeListener(this); - mPlayingSet.remove(animation); - Node animNode = mAnimatorSet.mNodeMap.get(animation); - animNode.done = true; - if (!mTerminated) { - // Listeners are already notified of the AnimatorSet ending in cancel() or - // end(); the logic below only kicks in when animations end normally - ArrayList sortedNodes = mAnimatorSet.mSortedNodes; - boolean allDone = true; - int numSortedNodes = sortedNodes.size(); - for (int i = 0; i < numSortedNodes; ++i) { - if (!sortedNodes.get(i).done) { - allDone = false; - break; - } - } - if (allDone) { - // If this was the last child animation to end, then notify listeners that this - // AnimatorSet has ended - if (mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - int numListeners = tmpListeners.size(); - for (int i = 0; i < numListeners; ++i) { - tmpListeners.get(i).onAnimationEnd(mAnimatorSet); - } - } - mAnimatorSet.mStarted = false; - } - } - } - - // Nothing to do - public void onAnimationRepeat(Animator animation) { - } - - // Nothing to do - public void onAnimationStart(Animator animation) { - } - - } - - /** - * This method sorts the current set of nodes, if needed. The sort is a simple - * DependencyGraph sort, which goes like this: - * - All nodes without dependencies become 'roots' - * - while roots list is not null - * - for each root r - * - add r to sorted list - * - remove r as a dependency from any other node - * - any nodes with no dependencies are added to the roots list - */ - private void sortNodes() { - if (mNeedsSort) { - mSortedNodes.clear(); - ArrayList roots = new ArrayList(); - int numNodes = mNodes.size(); - for (int i = 0; i < numNodes; ++i) { - Node node = mNodes.get(i); - if (node.dependencies == null || node.dependencies.size() == 0) { - roots.add(node); - } - } - ArrayList tmpRoots = new ArrayList(); - while (roots.size() > 0) { - int numRoots = roots.size(); - for (int i = 0; i < numRoots; ++i) { - Node root = roots.get(i); - mSortedNodes.add(root); - if (root.nodeDependents != null) { - int numDependents = root.nodeDependents.size(); - for (int j = 0; j < numDependents; ++j) { - Node node = root.nodeDependents.get(j); - node.nodeDependencies.remove(root); - if (node.nodeDependencies.size() == 0) { - tmpRoots.add(node); - } - } - } - } - roots.clear(); - roots.addAll(tmpRoots); - tmpRoots.clear(); - } - mNeedsSort = false; - if (mSortedNodes.size() != mNodes.size()) { - throw new IllegalStateException("Circular dependencies cannot exist" - + " in AnimatorSet"); - } - } else { - // Doesn't need sorting, but still need to add in the nodeDependencies list - // because these get removed as the event listeners fire and the dependencies - // are satisfied - int numNodes = mNodes.size(); - for (int i = 0; i < numNodes; ++i) { - Node node = mNodes.get(i); - if (node.dependencies != null && node.dependencies.size() > 0) { - int numDependencies = node.dependencies.size(); - for (int j = 0; j < numDependencies; ++j) { - Dependency dependency = node.dependencies.get(j); - if (node.nodeDependencies == null) { - node.nodeDependencies = new ArrayList(); - } - if (!node.nodeDependencies.contains(dependency.node)) { - node.nodeDependencies.add(dependency.node); - } - } - } - // nodes are 'done' by default; they become un-done when started, and done - // again when ended - node.done = false; - } - } - } - - /** - * Dependency holds information about the node that some other node is - * dependent upon and the nature of that dependency. - * - */ - private static class Dependency { - static final int WITH = 0; // dependent node must start with this dependency node - static final int AFTER = 1; // dependent node must start when this dependency node finishes - - // The node that the other node with this Dependency is dependent upon - public Node node; - - // The nature of the dependency (WITH or AFTER) - public int rule; - - public Dependency(Node node, int rule) { - this.node = node; - this.rule = rule; - } - } - - /** - * A Node is an embodiment of both the Animator that it wraps as well as - * any dependencies that are associated with that Animation. This includes - * both dependencies upon other nodes (in the dependencies list) as - * well as dependencies of other nodes upon this (in the nodeDependents list). - */ - private static class Node implements Cloneable { - public Animator animation; - - /** - * These are the dependencies that this node's animation has on other - * nodes. For example, if this node's animation should begin with some - * other animation ends, then there will be an item in this node's - * dependencies list for that other animation's node. - */ - public ArrayList dependencies = null; - - /** - * tmpDependencies is a runtime detail. We use the dependencies list for sorting. - * But we also use the list to keep track of when multiple dependencies are satisfied, - * but removing each dependency as it is satisfied. We do not want to remove - * the dependency itself from the list, because we need to retain that information - * if the AnimatorSet is launched in the future. So we create a copy of the dependency - * list when the AnimatorSet starts and use this tmpDependencies list to track the - * list of satisfied dependencies. - */ - public ArrayList tmpDependencies = null; - - /** - * nodeDependencies is just a list of the nodes that this Node is dependent upon. - * This information is used in sortNodes(), to determine when a node is a root. - */ - public ArrayList nodeDependencies = null; - - /** - * nodeDepdendents is the list of nodes that have this node as a dependency. This - * is a utility field used in sortNodes to facilitate removing this node as a - * dependency when it is a root node. - */ - public ArrayList nodeDependents = null; - - /** - * Flag indicating whether the animation in this node is finished. This flag - * is used by AnimatorSet to check, as each animation ends, whether all child animations - * are done and it's time to send out an end event for the entire AnimatorSet. - */ - public boolean done = false; - - /** - * Constructs the Node with the animation that it encapsulates. A Node has no - * dependencies by default; dependencies are added via the addDependency() - * method. - * - * @param animation The animation that the Node encapsulates. - */ - public Node(Animator animation) { - this.animation = animation; - } - - /** - * Add a dependency to this Node. The dependency includes information about the - * node that this node is dependency upon and the nature of the dependency. - * @param dependency - */ - public void addDependency(Dependency dependency) { - if (dependencies == null) { - dependencies = new ArrayList(); - nodeDependencies = new ArrayList(); - } - dependencies.add(dependency); - if (!nodeDependencies.contains(dependency.node)) { - nodeDependencies.add(dependency.node); - } - Node dependencyNode = dependency.node; - if (dependencyNode.nodeDependents == null) { - dependencyNode.nodeDependents = new ArrayList(); - } - dependencyNode.nodeDependents.add(this); - } - - @Override - public Node clone() { - try { - Node node = (Node) super.clone(); - node.animation = animation.clone(); - return node; - } catch (CloneNotSupportedException e) { - throw new AssertionError(); - } - } - } - - /** - * The Builder object is a utility class to facilitate adding animations to a - * AnimatorSet along with the relationships between the various animations. The - * intention of the Builder methods, along with the {@link - * AnimatorSet#play(Animator) play()} method of AnimatorSet is to make it possible - * to express the dependency relationships of animations in a natural way. Developers can also - * use the {@link AnimatorSet#playTogether(Animator[]) playTogether()} and {@link - * AnimatorSet#playSequentially(Animator[]) playSequentially()} methods if these suit the need, - * but it might be easier in some situations to express the AnimatorSet of animations in pairs. - *

- *

The Builder object cannot be constructed directly, but is rather constructed - * internally via a call to {@link AnimatorSet#play(Animator)}.

- *

- *

For example, this sets up a AnimatorSet to play anim1 and anim2 at the same time, anim3 to - * play when anim2 finishes, and anim4 to play when anim3 finishes:

- *
-     *     AnimatorSet s = new AnimatorSet();
-     *     s.play(anim1).with(anim2);
-     *     s.play(anim2).before(anim3);
-     *     s.play(anim4).after(anim3);
-     * 
- *

- *

Note in the example that both {@link Builder#before(Animator)} and {@link - * Builder#after(Animator)} are used. These are just different ways of expressing the same - * relationship and are provided to make it easier to say things in a way that is more natural, - * depending on the situation.

- *

- *

It is possible to make several calls into the same Builder object to express - * multiple relationships. However, note that it is only the animation passed into the initial - * {@link AnimatorSet#play(Animator)} method that is the dependency in any of the successive - * calls to the Builder object. For example, the following code starts both anim2 - * and anim3 when anim1 ends; there is no direct dependency relationship between anim2 and - * anim3: - *

-     *   AnimatorSet s = new AnimatorSet();
-     *   s.play(anim1).before(anim2).before(anim3);
-     * 
- * If the desired result is to play anim1 then anim2 then anim3, this code expresses the - * relationship correctly:

- *
-     *   AnimatorSet s = new AnimatorSet();
-     *   s.play(anim1).before(anim2);
-     *   s.play(anim2).before(anim3);
-     * 
- *

- *

Note that it is possible to express relationships that cannot be resolved and will not - * result in sensible results. For example, play(anim1).after(anim1) makes no - * sense. In general, circular dependencies like this one (or more indirect ones where a depends - * on b, which depends on c, which depends on a) should be avoided. Only create AnimatorSets - * that can boil down to a simple, one-way relationship of animations starting with, before, and - * after other, different, animations.

- */ - public class Builder { - - /** - * This tracks the current node being processed. It is supplied to the play() method - * of AnimatorSet and passed into the constructor of Builder. - */ - private Node mCurrentNode; - - /** - * package-private constructor. Builders are only constructed by AnimatorSet, when the - * play() method is called. - * - * @param anim The animation that is the dependency for the other animations passed into - * the other methods of this Builder object. - */ - Builder(Animator anim) { - mCurrentNode = mNodeMap.get(anim); - if (mCurrentNode == null) { - mCurrentNode = new Node(anim); - mNodeMap.put(anim, mCurrentNode); - mNodes.add(mCurrentNode); - } - } - - /** - * Sets up the given animation to play at the same time as the animation supplied in the - * {@link AnimatorSet#play(Animator)} call that created this Builder object. - * - * @param anim The animation that will play when the animation supplied to the - * {@link AnimatorSet#play(Animator)} method starts. - */ - public Builder with(Animator anim) { - Node node = mNodeMap.get(anim); - if (node == null) { - node = new Node(anim); - mNodeMap.put(anim, node); - mNodes.add(node); - } - Dependency dependency = new Dependency(mCurrentNode, Dependency.WITH); - node.addDependency(dependency); - return this; - } - - /** - * Sets up the given animation to play when the animation supplied in the - * {@link AnimatorSet#play(Animator)} call that created this Builder object - * ends. - * - * @param anim The animation that will play when the animation supplied to the - * {@link AnimatorSet#play(Animator)} method ends. - */ - public Builder before(Animator anim) { - Node node = mNodeMap.get(anim); - if (node == null) { - node = new Node(anim); - mNodeMap.put(anim, node); - mNodes.add(node); - } - Dependency dependency = new Dependency(mCurrentNode, Dependency.AFTER); - node.addDependency(dependency); - return this; - } - - /** - * Sets up the given animation to play when the animation supplied in the - * {@link AnimatorSet#play(Animator)} call that created this Builder object - * to start when the animation supplied in this method call ends. - * - * @param anim The animation whose end will cause the animation supplied to the - * {@link AnimatorSet#play(Animator)} method to play. - */ - public Builder after(Animator anim) { - Node node = mNodeMap.get(anim); - if (node == null) { - node = new Node(anim); - mNodeMap.put(anim, node); - mNodes.add(node); - } - Dependency dependency = new Dependency(node, Dependency.AFTER); - mCurrentNode.addDependency(dependency); - return this; - } - - /** - * Sets up the animation supplied in the - * {@link AnimatorSet#play(Animator)} call that created this Builder object - * to play when the given amount of time elapses. - * - * @param delay The number of milliseconds that should elapse before the - * animation starts. - */ - public Builder after(long delay) { - // setup dummy ValueAnimator just to run the clock - ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f); - anim.setDuration(delay); - after(anim); - return this; - } - - } - -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java deleted file mode 100644 index e4101936..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -/** - * This evaluator can be used to perform type interpolation between float values. - */ -public class FloatEvaluator implements TypeEvaluator { - - /** - * This function returns the result of linearly interpolating the start and end values, with - * fraction representing the proportion between the start and end values. The - * calculation is a simple parametric calculation: result = x0 + t * (v1 - v0), - * where x0 is startValue, x1 is endValue, - * and t is fraction. - * - * @param fraction The fraction from the starting to the ending values - * @param startValue The start value; should be of type float or - * Float - * @param endValue The end value; should be of type float or Float - * @return A linear interpolation between the start and end values, given the - * fraction parameter. - */ - public Float evaluate(float fraction, Number startValue, Number endValue) { - float startFloat = startValue.floatValue(); - return startFloat + fraction * (endValue.floatValue() - startFloat); - } -} \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.java deleted file mode 100644 index 6d9dafa7..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import java.util.ArrayList; -import android.view.animation.Interpolator; - -import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.FloatKeyframe; - -/** - * This class holds a collection of FloatKeyframe objects and is called by ValueAnimator to calculate - * values between those keyframes for a given animation. The class internal to the animation - * package because it is an implementation detail of how Keyframes are stored and used. - * - *

This type-specific subclass of KeyframeSet, along with the other type-specific subclass for - * int, exists to speed up the getValue() method when there is no custom - * TypeEvaluator set for the animation, so that values can be calculated without autoboxing to the - * Object equivalents of these primitive types.

- */ -@SuppressWarnings("unchecked") -class FloatKeyframeSet extends KeyframeSet { - private float firstValue; - private float lastValue; - private float deltaValue; - private boolean firstTime = true; - - public FloatKeyframeSet(FloatKeyframe... keyframes) { - super(keyframes); - } - - @Override - public Object getValue(float fraction) { - return getFloatValue(fraction); - } - - @Override - public FloatKeyframeSet clone() { - ArrayList keyframes = mKeyframes; - int numKeyframes = mKeyframes.size(); - FloatKeyframe[] newKeyframes = new FloatKeyframe[numKeyframes]; - for (int i = 0; i < numKeyframes; ++i) { - newKeyframes[i] = (FloatKeyframe) keyframes.get(i).clone(); - } - FloatKeyframeSet newSet = new FloatKeyframeSet(newKeyframes); - return newSet; - } - - public float getFloatValue(float fraction) { - if (mNumKeyframes == 2) { - if (firstTime) { - firstTime = false; - firstValue = ((FloatKeyframe) mKeyframes.get(0)).getFloatValue(); - lastValue = ((FloatKeyframe) mKeyframes.get(1)).getFloatValue(); - deltaValue = lastValue - firstValue; - } - if (mInterpolator != null) { - fraction = mInterpolator.getInterpolation(fraction); - } - if (mEvaluator == null) { - return firstValue + fraction * deltaValue; - } else { - return ((Number)mEvaluator.evaluate(fraction, firstValue, lastValue)).floatValue(); - } - } - if (fraction <= 0f) { - final FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(0); - final FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(1); - float prevValue = prevKeyframe.getFloatValue(); - float nextValue = nextKeyframe.getFloatValue(); - float prevFraction = prevKeyframe.getFraction(); - float nextFraction = nextKeyframe.getFraction(); - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); - return mEvaluator == null ? - prevValue + intervalFraction * (nextValue - prevValue) : - ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). - floatValue(); - } else if (fraction >= 1f) { - final FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(mNumKeyframes - 2); - final FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(mNumKeyframes - 1); - float prevValue = prevKeyframe.getFloatValue(); - float nextValue = nextKeyframe.getFloatValue(); - float prevFraction = prevKeyframe.getFraction(); - float nextFraction = nextKeyframe.getFraction(); - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); - return mEvaluator == null ? - prevValue + intervalFraction * (nextValue - prevValue) : - ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). - floatValue(); - } - FloatKeyframe prevKeyframe = (FloatKeyframe) mKeyframes.get(0); - for (int i = 1; i < mNumKeyframes; ++i) { - FloatKeyframe nextKeyframe = (FloatKeyframe) mKeyframes.get(i); - if (fraction < nextKeyframe.getFraction()) { - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - float intervalFraction = (fraction - prevKeyframe.getFraction()) / - (nextKeyframe.getFraction() - prevKeyframe.getFraction()); - float prevValue = prevKeyframe.getFloatValue(); - float nextValue = nextKeyframe.getFloatValue(); - return mEvaluator == null ? - prevValue + intervalFraction * (nextValue - prevValue) : - ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). - floatValue(); - } - prevKeyframe = nextKeyframe; - } - // shouldn't get here - return ((Number)mKeyframes.get(mNumKeyframes - 1).getValue()).floatValue(); - } - -} - diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.java deleted file mode 100644 index ed5e79ec..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -/** - * This evaluator can be used to perform type interpolation between int values. - */ -public class IntEvaluator implements TypeEvaluator { - - /** - * This function returns the result of linearly interpolating the start and end values, with - * fraction representing the proportion between the start and end values. The - * calculation is a simple parametric calculation: result = x0 + t * (v1 - v0), - * where x0 is startValue, x1 is endValue, - * and t is fraction. - * - * @param fraction The fraction from the starting to the ending values - * @param startValue The start value; should be of type int or - * Integer - * @param endValue The end value; should be of type int or Integer - * @return A linear interpolation between the start and end values, given the - * fraction parameter. - */ - public Integer evaluate(float fraction, Integer startValue, Integer endValue) { - int startInt = startValue; - return (int)(startInt + fraction * (endValue - startInt)); - } -} \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.java deleted file mode 100644 index e9215e7f..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import java.util.ArrayList; -import android.view.animation.Interpolator; - -import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.IntKeyframe; - -/** - * This class holds a collection of IntKeyframe objects and is called by ValueAnimator to calculate - * values between those keyframes for a given animation. The class internal to the animation - * package because it is an implementation detail of how Keyframes are stored and used. - * - *

This type-specific subclass of KeyframeSet, along with the other type-specific subclass for - * float, exists to speed up the getValue() method when there is no custom - * TypeEvaluator set for the animation, so that values can be calculated without autoboxing to the - * Object equivalents of these primitive types.

- */ -@SuppressWarnings("unchecked") -class IntKeyframeSet extends KeyframeSet { - private int firstValue; - private int lastValue; - private int deltaValue; - private boolean firstTime = true; - - public IntKeyframeSet(IntKeyframe... keyframes) { - super(keyframes); - } - - @Override - public Object getValue(float fraction) { - return getIntValue(fraction); - } - - @Override - public IntKeyframeSet clone() { - ArrayList keyframes = mKeyframes; - int numKeyframes = mKeyframes.size(); - IntKeyframe[] newKeyframes = new IntKeyframe[numKeyframes]; - for (int i = 0; i < numKeyframes; ++i) { - newKeyframes[i] = (IntKeyframe) keyframes.get(i).clone(); - } - IntKeyframeSet newSet = new IntKeyframeSet(newKeyframes); - return newSet; - } - - public int getIntValue(float fraction) { - if (mNumKeyframes == 2) { - if (firstTime) { - firstTime = false; - firstValue = ((IntKeyframe) mKeyframes.get(0)).getIntValue(); - lastValue = ((IntKeyframe) mKeyframes.get(1)).getIntValue(); - deltaValue = lastValue - firstValue; - } - if (mInterpolator != null) { - fraction = mInterpolator.getInterpolation(fraction); - } - if (mEvaluator == null) { - return firstValue + (int)(fraction * deltaValue); - } else { - return ((Number)mEvaluator.evaluate(fraction, firstValue, lastValue)).intValue(); - } - } - if (fraction <= 0f) { - final IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(0); - final IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(1); - int prevValue = prevKeyframe.getIntValue(); - int nextValue = nextKeyframe.getIntValue(); - float prevFraction = prevKeyframe.getFraction(); - float nextFraction = nextKeyframe.getFraction(); - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); - return mEvaluator == null ? - prevValue + (int)(intervalFraction * (nextValue - prevValue)) : - ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). - intValue(); - } else if (fraction >= 1f) { - final IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(mNumKeyframes - 2); - final IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(mNumKeyframes - 1); - int prevValue = prevKeyframe.getIntValue(); - int nextValue = nextKeyframe.getIntValue(); - float prevFraction = prevKeyframe.getFraction(); - float nextFraction = nextKeyframe.getFraction(); - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - float intervalFraction = (fraction - prevFraction) / (nextFraction - prevFraction); - return mEvaluator == null ? - prevValue + (int)(intervalFraction * (nextValue - prevValue)) : - ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)).intValue(); - } - IntKeyframe prevKeyframe = (IntKeyframe) mKeyframes.get(0); - for (int i = 1; i < mNumKeyframes; ++i) { - IntKeyframe nextKeyframe = (IntKeyframe) mKeyframes.get(i); - if (fraction < nextKeyframe.getFraction()) { - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - float intervalFraction = (fraction - prevKeyframe.getFraction()) / - (nextKeyframe.getFraction() - prevKeyframe.getFraction()); - int prevValue = prevKeyframe.getIntValue(); - int nextValue = nextKeyframe.getIntValue(); - return mEvaluator == null ? - prevValue + (int)(intervalFraction * (nextValue - prevValue)) : - ((Number)mEvaluator.evaluate(intervalFraction, prevValue, nextValue)). - intValue(); - } - prevKeyframe = nextKeyframe; - } - // shouldn't get here - return ((Number)mKeyframes.get(mNumKeyframes - 1).getValue()).intValue(); - } - -} - diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.java deleted file mode 100644 index ab76fa7f..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import android.view.animation.Interpolator; - -/** - * This class holds a time/value pair for an animation. The Keyframe class is used - * by {@link ValueAnimator} to define the values that the animation target will have over the course - * of the animation. As the time proceeds from one keyframe to the other, the value of the - * target object will animate between the value at the previous keyframe and the value at the - * next keyframe. Each keyframe also holds an optional {@link TimeInterpolator} - * object, which defines the time interpolation over the intervalue preceding the keyframe. - * - *

The Keyframe class itself is abstract. The type-specific factory methods will return - * a subclass of Keyframe specific to the type of value being stored. This is done to improve - * performance when dealing with the most common cases (e.g., float and - * int values). Other types will fall into a more general Keyframe class that - * treats its values as Objects. Unless your animation requires dealing with a custom type - * or a data structure that needs to be animated directly (and evaluated using an implementation - * of {@link TypeEvaluator}), you should stick to using float and int as animations using those - * types have lower runtime overhead than other types.

- */ -@SuppressWarnings("rawtypes") -public abstract class Keyframe implements Cloneable { - /** - * The time at which mValue will hold true. - */ - float mFraction; - - /** - * The type of the value in this Keyframe. This type is determined at construction time, - * based on the type of the value object passed into the constructor. - */ - Class mValueType; - - /** - * The optional time interpolator for the interval preceding this keyframe. A null interpolator - * (the default) results in linear interpolation over the interval. - */ - private /*Time*/Interpolator mInterpolator = null; - - /** - * Flag to indicate whether this keyframe has a valid value. This flag is used when an - * animation first starts, to populate placeholder keyframes with real values derived - * from the target object. - */ - boolean mHasValue = false; - - /** - * Constructs a Keyframe object with the given time and value. The time defines the - * time, as a proportion of an overall animation's duration, at which the value will hold true - * for the animation. The value for the animation between keyframes will be calculated as - * an interpolation between the values at those keyframes. - * - * @param fraction The time, expressed as a value between 0 and 1, representing the fraction - * of time elapsed of the overall animation duration. - * @param value The value that the object will animate to as the animation time approaches - * the time in this keyframe, and the the value animated from as the time passes the time in - * this keyframe. - */ - public static Keyframe ofInt(float fraction, int value) { - return new IntKeyframe(fraction, value); - } - - /** - * Constructs a Keyframe object with the given time. The value at this time will be derived - * from the target object when the animation first starts (note that this implies that keyframes - * with no initial value must be used as part of an {@link ObjectAnimator}). - * The time defines the - * time, as a proportion of an overall animation's duration, at which the value will hold true - * for the animation. The value for the animation between keyframes will be calculated as - * an interpolation between the values at those keyframes. - * - * @param fraction The time, expressed as a value between 0 and 1, representing the fraction - * of time elapsed of the overall animation duration. - */ - public static Keyframe ofInt(float fraction) { - return new IntKeyframe(fraction); - } - - /** - * Constructs a Keyframe object with the given time and value. The time defines the - * time, as a proportion of an overall animation's duration, at which the value will hold true - * for the animation. The value for the animation between keyframes will be calculated as - * an interpolation between the values at those keyframes. - * - * @param fraction The time, expressed as a value between 0 and 1, representing the fraction - * of time elapsed of the overall animation duration. - * @param value The value that the object will animate to as the animation time approaches - * the time in this keyframe, and the the value animated from as the time passes the time in - * this keyframe. - */ - public static Keyframe ofFloat(float fraction, float value) { - return new FloatKeyframe(fraction, value); - } - - /** - * Constructs a Keyframe object with the given time. The value at this time will be derived - * from the target object when the animation first starts (note that this implies that keyframes - * with no initial value must be used as part of an {@link ObjectAnimator}). - * The time defines the - * time, as a proportion of an overall animation's duration, at which the value will hold true - * for the animation. The value for the animation between keyframes will be calculated as - * an interpolation between the values at those keyframes. - * - * @param fraction The time, expressed as a value between 0 and 1, representing the fraction - * of time elapsed of the overall animation duration. - */ - public static Keyframe ofFloat(float fraction) { - return new FloatKeyframe(fraction); - } - - /** - * Constructs a Keyframe object with the given time and value. The time defines the - * time, as a proportion of an overall animation's duration, at which the value will hold true - * for the animation. The value for the animation between keyframes will be calculated as - * an interpolation between the values at those keyframes. - * - * @param fraction The time, expressed as a value between 0 and 1, representing the fraction - * of time elapsed of the overall animation duration. - * @param value The value that the object will animate to as the animation time approaches - * the time in this keyframe, and the the value animated from as the time passes the time in - * this keyframe. - */ - public static Keyframe ofObject(float fraction, Object value) { - return new ObjectKeyframe(fraction, value); - } - - /** - * Constructs a Keyframe object with the given time. The value at this time will be derived - * from the target object when the animation first starts (note that this implies that keyframes - * with no initial value must be used as part of an {@link ObjectAnimator}). - * The time defines the - * time, as a proportion of an overall animation's duration, at which the value will hold true - * for the animation. The value for the animation between keyframes will be calculated as - * an interpolation between the values at those keyframes. - * - * @param fraction The time, expressed as a value between 0 and 1, representing the fraction - * of time elapsed of the overall animation duration. - */ - public static Keyframe ofObject(float fraction) { - return new ObjectKeyframe(fraction, null); - } - - /** - * Indicates whether this keyframe has a valid value. This method is called internally when - * an {@link ObjectAnimator} first starts; keyframes without values are assigned values at - * that time by deriving the value for the property from the target object. - * - * @return boolean Whether this object has a value assigned. - */ - public boolean hasValue() { - return mHasValue; - } - - /** - * Gets the value for this Keyframe. - * - * @return The value for this Keyframe. - */ - public abstract Object getValue(); - - /** - * Sets the value for this Keyframe. - * - * @param value value for this Keyframe. - */ - public abstract void setValue(Object value); - - /** - * Gets the time for this keyframe, as a fraction of the overall animation duration. - * - * @return The time associated with this keyframe, as a fraction of the overall animation - * duration. This should be a value between 0 and 1. - */ - public float getFraction() { - return mFraction; - } - - /** - * Sets the time for this keyframe, as a fraction of the overall animation duration. - * - * @param fraction time associated with this keyframe, as a fraction of the overall animation - * duration. This should be a value between 0 and 1. - */ - public void setFraction(float fraction) { - mFraction = fraction; - } - - /** - * Gets the optional interpolator for this Keyframe. A value of null indicates - * that there is no interpolation, which is the same as linear interpolation. - * - * @return The optional interpolator for this Keyframe. - */ - public /*Time*/Interpolator getInterpolator() { - return mInterpolator; - } - - /** - * Sets the optional interpolator for this Keyframe. A value of null indicates - * that there is no interpolation, which is the same as linear interpolation. - * - * @return The optional interpolator for this Keyframe. - */ - public void setInterpolator(/*Time*/Interpolator interpolator) { - mInterpolator = interpolator; - } - - /** - * Gets the type of keyframe. This information is used by ValueAnimator to determine the type of - * {@link TypeEvaluator} to use when calculating values between keyframes. The type is based - * on the type of Keyframe created. - * - * @return The type of the value stored in the Keyframe. - */ - public Class getType() { - return mValueType; - } - - @Override - public abstract Keyframe clone(); - - /** - * This internal subclass is used for all types which are not int or float. - */ - static class ObjectKeyframe extends Keyframe { - - /** - * The value of the animation at the time mFraction. - */ - Object mValue; - - ObjectKeyframe(float fraction, Object value) { - mFraction = fraction; - mValue = value; - mHasValue = (value != null); - mValueType = mHasValue ? value.getClass() : Object.class; - } - - public Object getValue() { - return mValue; - } - - public void setValue(Object value) { - mValue = value; - mHasValue = (value != null); - } - - @Override - public ObjectKeyframe clone() { - ObjectKeyframe kfClone = new ObjectKeyframe(getFraction(), mValue); - kfClone.setInterpolator(getInterpolator()); - return kfClone; - } - } - - /** - * Internal subclass used when the keyframe value is of type int. - */ - static class IntKeyframe extends Keyframe { - - /** - * The value of the animation at the time mFraction. - */ - int mValue; - - IntKeyframe(float fraction, int value) { - mFraction = fraction; - mValue = value; - mValueType = int.class; - mHasValue = true; - } - - IntKeyframe(float fraction) { - mFraction = fraction; - mValueType = int.class; - } - - public int getIntValue() { - return mValue; - } - - public Object getValue() { - return mValue; - } - - public void setValue(Object value) { - if (value != null && value.getClass() == Integer.class) { - mValue = ((Integer)value).intValue(); - mHasValue = true; - } - } - - @Override - public IntKeyframe clone() { - IntKeyframe kfClone = new IntKeyframe(getFraction(), mValue); - kfClone.setInterpolator(getInterpolator()); - return kfClone; - } - } - - /** - * Internal subclass used when the keyframe value is of type float. - */ - static class FloatKeyframe extends Keyframe { - /** - * The value of the animation at the time mFraction. - */ - float mValue; - - FloatKeyframe(float fraction, float value) { - mFraction = fraction; - mValue = value; - mValueType = float.class; - mHasValue = true; - } - - FloatKeyframe(float fraction) { - mFraction = fraction; - mValueType = float.class; - } - - public float getFloatValue() { - return mValue; - } - - public Object getValue() { - return mValue; - } - - public void setValue(Object value) { - if (value != null && value.getClass() == Float.class) { - mValue = ((Float)value).floatValue(); - mHasValue = true; - } - } - - @Override - public FloatKeyframe clone() { - FloatKeyframe kfClone = new FloatKeyframe(getFraction(), mValue); - kfClone.setInterpolator(getInterpolator()); - return kfClone; - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.java deleted file mode 100644 index a71e1ad3..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import java.util.ArrayList; -import java.util.Arrays; -import android.view.animation.Interpolator; - -import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.FloatKeyframe; -import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.IntKeyframe; -import com.actionbarsherlock.internal.nineoldandroids.animation.Keyframe.ObjectKeyframe; - -/** - * This class holds a collection of Keyframe objects and is called by ValueAnimator to calculate - * values between those keyframes for a given animation. The class internal to the animation - * package because it is an implementation detail of how Keyframes are stored and used. - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -class KeyframeSet { - - int mNumKeyframes; - - Keyframe mFirstKeyframe; - Keyframe mLastKeyframe; - /*Time*/Interpolator mInterpolator; // only used in the 2-keyframe case - ArrayList mKeyframes; // only used when there are not 2 keyframes - TypeEvaluator mEvaluator; - - - public KeyframeSet(Keyframe... keyframes) { - mNumKeyframes = keyframes.length; - mKeyframes = new ArrayList(); - mKeyframes.addAll(Arrays.asList(keyframes)); - mFirstKeyframe = mKeyframes.get(0); - mLastKeyframe = mKeyframes.get(mNumKeyframes - 1); - mInterpolator = mLastKeyframe.getInterpolator(); - } - - public static KeyframeSet ofInt(int... values) { - int numKeyframes = values.length; - IntKeyframe keyframes[] = new IntKeyframe[Math.max(numKeyframes,2)]; - if (numKeyframes == 1) { - keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f); - keyframes[1] = (IntKeyframe) Keyframe.ofInt(1f, values[0]); - } else { - keyframes[0] = (IntKeyframe) Keyframe.ofInt(0f, values[0]); - for (int i = 1; i < numKeyframes; ++i) { - keyframes[i] = (IntKeyframe) Keyframe.ofInt((float) i / (numKeyframes - 1), values[i]); - } - } - return new IntKeyframeSet(keyframes); - } - - public static KeyframeSet ofFloat(float... values) { - int numKeyframes = values.length; - FloatKeyframe keyframes[] = new FloatKeyframe[Math.max(numKeyframes,2)]; - if (numKeyframes == 1) { - keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f); - keyframes[1] = (FloatKeyframe) Keyframe.ofFloat(1f, values[0]); - } else { - keyframes[0] = (FloatKeyframe) Keyframe.ofFloat(0f, values[0]); - for (int i = 1; i < numKeyframes; ++i) { - keyframes[i] = (FloatKeyframe) Keyframe.ofFloat((float) i / (numKeyframes - 1), values[i]); - } - } - return new FloatKeyframeSet(keyframes); - } - - public static KeyframeSet ofKeyframe(Keyframe... keyframes) { - // if all keyframes of same primitive type, create the appropriate KeyframeSet - int numKeyframes = keyframes.length; - boolean hasFloat = false; - boolean hasInt = false; - boolean hasOther = false; - for (int i = 0; i < numKeyframes; ++i) { - if (keyframes[i] instanceof FloatKeyframe) { - hasFloat = true; - } else if (keyframes[i] instanceof IntKeyframe) { - hasInt = true; - } else { - hasOther = true; - } - } - if (hasFloat && !hasInt && !hasOther) { - FloatKeyframe floatKeyframes[] = new FloatKeyframe[numKeyframes]; - for (int i = 0; i < numKeyframes; ++i) { - floatKeyframes[i] = (FloatKeyframe) keyframes[i]; - } - return new FloatKeyframeSet(floatKeyframes); - } else if (hasInt && !hasFloat && !hasOther) { - IntKeyframe intKeyframes[] = new IntKeyframe[numKeyframes]; - for (int i = 0; i < numKeyframes; ++i) { - intKeyframes[i] = (IntKeyframe) keyframes[i]; - } - return new IntKeyframeSet(intKeyframes); - } else { - return new KeyframeSet(keyframes); - } - } - - public static KeyframeSet ofObject(Object... values) { - int numKeyframes = values.length; - ObjectKeyframe keyframes[] = new ObjectKeyframe[Math.max(numKeyframes,2)]; - if (numKeyframes == 1) { - keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f); - keyframes[1] = (ObjectKeyframe) Keyframe.ofObject(1f, values[0]); - } else { - keyframes[0] = (ObjectKeyframe) Keyframe.ofObject(0f, values[0]); - for (int i = 1; i < numKeyframes; ++i) { - keyframes[i] = (ObjectKeyframe) Keyframe.ofObject((float) i / (numKeyframes - 1), values[i]); - } - } - return new KeyframeSet(keyframes); - } - - /** - * Sets the TypeEvaluator to be used when calculating animated values. This object - * is required only for KeyframeSets that are not either IntKeyframeSet or FloatKeyframeSet, - * both of which assume their own evaluator to speed up calculations with those primitive - * types. - * - * @param evaluator The TypeEvaluator to be used to calculate animated values. - */ - public void setEvaluator(TypeEvaluator evaluator) { - mEvaluator = evaluator; - } - - @Override - public KeyframeSet clone() { - ArrayList keyframes = mKeyframes; - int numKeyframes = mKeyframes.size(); - Keyframe[] newKeyframes = new Keyframe[numKeyframes]; - for (int i = 0; i < numKeyframes; ++i) { - newKeyframes[i] = keyframes.get(i).clone(); - } - KeyframeSet newSet = new KeyframeSet(newKeyframes); - return newSet; - } - - /** - * Gets the animated value, given the elapsed fraction of the animation (interpolated by the - * animation's interpolator) and the evaluator used to calculate in-between values. This - * function maps the input fraction to the appropriate keyframe interval and a fraction - * between them and returns the interpolated value. Note that the input fraction may fall - * outside the [0-1] bounds, if the animation's interpolator made that happen (e.g., a - * spring interpolation that might send the fraction past 1.0). We handle this situation by - * just using the two keyframes at the appropriate end when the value is outside those bounds. - * - * @param fraction The elapsed fraction of the animation - * @return The animated value. - */ - public Object getValue(float fraction) { - - // Special-case optimization for the common case of only two keyframes - if (mNumKeyframes == 2) { - if (mInterpolator != null) { - fraction = mInterpolator.getInterpolation(fraction); - } - return mEvaluator.evaluate(fraction, mFirstKeyframe.getValue(), - mLastKeyframe.getValue()); - } - if (fraction <= 0f) { - final Keyframe nextKeyframe = mKeyframes.get(1); - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - final float prevFraction = mFirstKeyframe.getFraction(); - float intervalFraction = (fraction - prevFraction) / - (nextKeyframe.getFraction() - prevFraction); - return mEvaluator.evaluate(intervalFraction, mFirstKeyframe.getValue(), - nextKeyframe.getValue()); - } else if (fraction >= 1f) { - final Keyframe prevKeyframe = mKeyframes.get(mNumKeyframes - 2); - final /*Time*/Interpolator interpolator = mLastKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - final float prevFraction = prevKeyframe.getFraction(); - float intervalFraction = (fraction - prevFraction) / - (mLastKeyframe.getFraction() - prevFraction); - return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(), - mLastKeyframe.getValue()); - } - Keyframe prevKeyframe = mFirstKeyframe; - for (int i = 1; i < mNumKeyframes; ++i) { - Keyframe nextKeyframe = mKeyframes.get(i); - if (fraction < nextKeyframe.getFraction()) { - final /*Time*/Interpolator interpolator = nextKeyframe.getInterpolator(); - if (interpolator != null) { - fraction = interpolator.getInterpolation(fraction); - } - final float prevFraction = prevKeyframe.getFraction(); - float intervalFraction = (fraction - prevFraction) / - (nextKeyframe.getFraction() - prevFraction); - return mEvaluator.evaluate(intervalFraction, prevKeyframe.getValue(), - nextKeyframe.getValue()); - } - prevKeyframe = nextKeyframe; - } - // shouldn't reach here - return mLastKeyframe.getValue(); - } - - @Override - public String toString() { - String returnVal = " "; - for (int i = 0; i < mNumKeyframes; ++i) { - returnVal += mKeyframes.get(i).getValue() + " "; - } - return returnVal; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.java deleted file mode 100644 index 21d15c02..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import android.util.Log; -//import android.util.Property; - -//import java.lang.reflect.Method; -import java.util.ArrayList; - -/** - * This subclass of {@link ValueAnimator} provides support for animating properties on target objects. - * The constructors of this class take parameters to define the target object that will be animated - * as well as the name of the property that will be animated. Appropriate set/get functions - * are then determined internally and the animation will call these functions as necessary to - * animate the property. - * - * @see #setPropertyName(String) - * - */ -@SuppressWarnings("rawtypes") -public final class ObjectAnimator extends ValueAnimator { - private static final boolean DBG = false; - - // The target object on which the property exists, set in the constructor - private Object mTarget; - - private String mPropertyName; - - //private Property mProperty; - - /** - * Sets the name of the property that will be animated. This name is used to derive - * a setter function that will be called to set animated values. - * For example, a property name of foo will result - * in a call to the function setFoo() on the target object. If either - * valueFrom or valueTo is null, then a getter function will - * also be derived and called. - * - *

For best performance of the mechanism that calls the setter function determined by the - * name of the property being animated, use float or int typed values, - * and make the setter function for those properties have a void return value. This - * will cause the code to take an optimized path for these constrained circumstances. Other - * property types and return types will work, but will have more overhead in processing - * the requests due to normal reflection mechanisms.

- * - *

Note that the setter function derived from this property name - * must take the same parameter type as the - * valueFrom and valueTo properties, otherwise the call to - * the setter function will fail.

- * - *

If this ObjectAnimator has been set up to animate several properties together, - * using more than one PropertyValuesHolder objects, then setting the propertyName simply - * sets the propertyName in the first of those PropertyValuesHolder objects.

- * - * @param propertyName The name of the property being animated. Should not be null. - */ - public void setPropertyName(String propertyName) { - // mValues could be null if this is being constructed piecemeal. Just record the - // propertyName to be used later when setValues() is called if so. - if (mValues != null) { - PropertyValuesHolder valuesHolder = mValues[0]; - String oldName = valuesHolder.getPropertyName(); - valuesHolder.setPropertyName(propertyName); - mValuesMap.remove(oldName); - mValuesMap.put(propertyName, valuesHolder); - } - mPropertyName = propertyName; - // New property/values/target should cause re-initialization prior to starting - mInitialized = false; - } - - /** - * Sets the property that will be animated. Property objects will take precedence over - * properties specified by the {@link #setPropertyName(String)} method. Animations should - * be set up to use one or the other, not both. - * - * @param property The property being animated. Should not be null. - */ - //public void setProperty(Property property) { - // // mValues could be null if this is being constructed piecemeal. Just record the - // // propertyName to be used later when setValues() is called if so. - // if (mValues != null) { - // PropertyValuesHolder valuesHolder = mValues[0]; - // String oldName = valuesHolder.getPropertyName(); - // valuesHolder.setProperty(property); - // mValuesMap.remove(oldName); - // mValuesMap.put(mPropertyName, valuesHolder); - // } - // if (mProperty != null) { - // mPropertyName = property.getName(); - // } - // mProperty = property; - // // New property/values/target should cause re-initialization prior to starting - // mInitialized = false; - //} - - /** - * Gets the name of the property that will be animated. This name will be used to derive - * a setter function that will be called to set animated values. - * For example, a property name of foo will result - * in a call to the function setFoo() on the target object. If either - * valueFrom or valueTo is null, then a getter function will - * also be derived and called. - */ - public String getPropertyName() { - return mPropertyName; - } - - /** - * Creates a new ObjectAnimator object. This default constructor is primarily for - * use internally; the other constructors which take parameters are more generally - * useful. - */ - public ObjectAnimator() { - } - - /** - * Private utility constructor that initializes the target object and name of the - * property being animated. - * - * @param target The object whose property is to be animated. This object should - * have a public method on it called setName(), where name is - * the value of the propertyName parameter. - * @param propertyName The name of the property being animated. - */ - private ObjectAnimator(Object target, String propertyName) { - mTarget = target; - setPropertyName(propertyName); - } - - /** - * Private utility constructor that initializes the target object and property being animated. - * - * @param target The object whose property is to be animated. - * @param property The property being animated. - */ - //private ObjectAnimator(T target, Property property) { - // mTarget = target; - // setProperty(property); - //} - - /** - * Constructs and returns an ObjectAnimator that animates between int values. A single - * value implies that that value is the one being animated to. Two values imply a starting - * and ending values. More than two values imply a starting value, values to animate through - * along the way, and an ending value (these values will be distributed evenly across - * the duration of the animation). - * - * @param target The object whose property is to be animated. This object should - * have a public method on it called setName(), where name is - * the value of the propertyName parameter. - * @param propertyName The name of the property being animated. - * @param values A set of values that the animation will animate between over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - public static ObjectAnimator ofInt(Object target, String propertyName, int... values) { - ObjectAnimator anim = new ObjectAnimator(target, propertyName); - anim.setIntValues(values); - return anim; - } - - /** - * Constructs and returns an ObjectAnimator that animates between int values. A single - * value implies that that value is the one being animated to. Two values imply a starting - * and ending values. More than two values imply a starting value, values to animate through - * along the way, and an ending value (these values will be distributed evenly across - * the duration of the animation). - * - * @param target The object whose property is to be animated. - * @param property The property being animated. - * @param values A set of values that the animation will animate between over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - //public static ObjectAnimator ofInt(T target, Property property, int... values) { - // ObjectAnimator anim = new ObjectAnimator(target, property); - // anim.setIntValues(values); - // return anim; - //} - - /** - * Constructs and returns an ObjectAnimator that animates between float values. A single - * value implies that that value is the one being animated to. Two values imply a starting - * and ending values. More than two values imply a starting value, values to animate through - * along the way, and an ending value (these values will be distributed evenly across - * the duration of the animation). - * - * @param target The object whose property is to be animated. This object should - * have a public method on it called setName(), where name is - * the value of the propertyName parameter. - * @param propertyName The name of the property being animated. - * @param values A set of values that the animation will animate between over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - public static ObjectAnimator ofFloat(Object target, String propertyName, float... values) { - ObjectAnimator anim = new ObjectAnimator(target, propertyName); - anim.setFloatValues(values); - return anim; - } - - /** - * Constructs and returns an ObjectAnimator that animates between float values. A single - * value implies that that value is the one being animated to. Two values imply a starting - * and ending values. More than two values imply a starting value, values to animate through - * along the way, and an ending value (these values will be distributed evenly across - * the duration of the animation). - * - * @param target The object whose property is to be animated. - * @param property The property being animated. - * @param values A set of values that the animation will animate between over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - //public static ObjectAnimator ofFloat(T target, Property property, - // float... values) { - // ObjectAnimator anim = new ObjectAnimator(target, property); - // anim.setFloatValues(values); - // return anim; - //} - - /** - * Constructs and returns an ObjectAnimator that animates between Object values. A single - * value implies that that value is the one being animated to. Two values imply a starting - * and ending values. More than two values imply a starting value, values to animate through - * along the way, and an ending value (these values will be distributed evenly across - * the duration of the animation). - * - * @param target The object whose property is to be animated. This object should - * have a public method on it called setName(), where name is - * the value of the propertyName parameter. - * @param propertyName The name of the property being animated. - * @param evaluator A TypeEvaluator that will be called on each animation frame to - * provide the necessary interpolation between the Object values to derive the animated - * value. - * @param values A set of values that the animation will animate between over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - public static ObjectAnimator ofObject(Object target, String propertyName, - TypeEvaluator evaluator, Object... values) { - ObjectAnimator anim = new ObjectAnimator(target, propertyName); - anim.setObjectValues(values); - anim.setEvaluator(evaluator); - return anim; - } - - /** - * Constructs and returns an ObjectAnimator that animates between Object values. A single - * value implies that that value is the one being animated to. Two values imply a starting - * and ending values. More than two values imply a starting value, values to animate through - * along the way, and an ending value (these values will be distributed evenly across - * the duration of the animation). - * - * @param target The object whose property is to be animated. - * @param property The property being animated. - * @param evaluator A TypeEvaluator that will be called on each animation frame to - * provide the necessary interpolation between the Object values to derive the animated - * value. - * @param values A set of values that the animation will animate between over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - //public static ObjectAnimator ofObject(T target, Property property, - // TypeEvaluator evaluator, V... values) { - // ObjectAnimator anim = new ObjectAnimator(target, property); - // anim.setObjectValues(values); - // anim.setEvaluator(evaluator); - // return anim; - //} - - /** - * Constructs and returns an ObjectAnimator that animates between the sets of values specified - * in PropertyValueHolder objects. This variant should be used when animating - * several properties at once with the same ObjectAnimator, since PropertyValuesHolder allows - * you to associate a set of animation values with a property name. - * - * @param target The object whose property is to be animated. Depending on how the - * PropertyValuesObjects were constructed, the target object should either have the {@link - * android.util.Property} objects used to construct the PropertyValuesHolder objects or (if the - * PropertyValuesHOlder objects were created with property names) the target object should have - * public methods on it called setName(), where name is the name of - * the property passed in as the propertyName parameter for each of the - * PropertyValuesHolder objects. - * @param values A set of PropertyValuesHolder objects whose values will be animated between - * over time. - * @return An ObjectAnimator object that is set up to animate between the given values. - */ - public static ObjectAnimator ofPropertyValuesHolder(Object target, - PropertyValuesHolder... values) { - ObjectAnimator anim = new ObjectAnimator(); - anim.mTarget = target; - anim.setValues(values); - return anim; - } - - @Override - public void setIntValues(int... values) { - if (mValues == null || mValues.length == 0) { - // No values yet - this animator is being constructed piecemeal. Init the values with - // whatever the current propertyName is - //if (mProperty != null) { - // setValues(PropertyValuesHolder.ofInt(mProperty, values)); - //} else { - setValues(PropertyValuesHolder.ofInt(mPropertyName, values)); - //} - } else { - super.setIntValues(values); - } - } - - @Override - public void setFloatValues(float... values) { - if (mValues == null || mValues.length == 0) { - // No values yet - this animator is being constructed piecemeal. Init the values with - // whatever the current propertyName is - //if (mProperty != null) { - // setValues(PropertyValuesHolder.ofFloat(mProperty, values)); - //} else { - setValues(PropertyValuesHolder.ofFloat(mPropertyName, values)); - //} - } else { - super.setFloatValues(values); - } - } - - @Override - public void setObjectValues(Object... values) { - if (mValues == null || mValues.length == 0) { - // No values yet - this animator is being constructed piecemeal. Init the values with - // whatever the current propertyName is - //if (mProperty != null) { - // setValues(PropertyValuesHolder.ofObject(mProperty, (TypeEvaluator)null, values)); - //} else { - setValues(PropertyValuesHolder.ofObject(mPropertyName, (TypeEvaluator)null, values)); - //} - } else { - super.setObjectValues(values); - } - } - - @Override - public void start() { - if (DBG) { - Log.d("ObjectAnimator", "Anim target, duration: " + mTarget + ", " + getDuration()); - for (int i = 0; i < mValues.length; ++i) { - PropertyValuesHolder pvh = mValues[i]; - ArrayList keyframes = pvh.mKeyframeSet.mKeyframes; - Log.d("ObjectAnimator", " Values[" + i + "]: " + - pvh.getPropertyName() + ", " + keyframes.get(0).getValue() + ", " + - keyframes.get(pvh.mKeyframeSet.mNumKeyframes - 1).getValue()); - } - } - super.start(); - } - - /** - * This function is called immediately before processing the first animation - * frame of an animation. If there is a nonzero startDelay, the - * function is called after that delay ends. - * It takes care of the final initialization steps for the - * animation. This includes setting mEvaluator, if the user has not yet - * set it up, and the setter/getter methods, if the user did not supply - * them. - * - *

Overriders of this method should call the superclass method to cause - * internal mechanisms to be set up correctly.

- */ - @Override - void initAnimation() { - if (!mInitialized) { - // mValueType may change due to setter/getter setup; do this before calling super.init(), - // which uses mValueType to set up the default type evaluator. - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].setupSetterAndGetter(mTarget); - } - super.initAnimation(); - } - } - - /** - * Sets the length of the animation. The default duration is 300 milliseconds. - * - * @param duration The length of the animation, in milliseconds. - * @return ObjectAnimator The object called with setDuration(). This return - * value makes it easier to compose statements together that construct and then set the - * duration, as in - * ObjectAnimator.ofInt(target, propertyName, 0, 10).setDuration(500).start(). - */ - @Override - public ObjectAnimator setDuration(long duration) { - super.setDuration(duration); - return this; - } - - - /** - * The target object whose property will be animated by this animation - * - * @return The object being animated - */ - public Object getTarget() { - return mTarget; - } - - /** - * Sets the target object whose property will be animated by this animation - * - * @param target The object being animated - */ - @Override - public void setTarget(Object target) { - if (mTarget != target) { - final Object oldTarget = mTarget; - mTarget = target; - if (oldTarget != null && target != null && oldTarget.getClass() == target.getClass()) { - return; - } - // New target type should cause re-initialization prior to starting - mInitialized = false; - } - } - - @Override - public void setupStartValues() { - initAnimation(); - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].setupStartValue(mTarget); - } - } - - @Override - public void setupEndValues() { - initAnimation(); - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].setupEndValue(mTarget); - } - } - - /** - * This method is called with the elapsed fraction of the animation during every - * animation frame. This function turns the elapsed fraction into an interpolated fraction - * and then into an animated value (from the evaluator. The function is called mostly during - * animation updates, but it is also called when the end() - * function is called, to set the final value on the property. - * - *

Overrides of this method must call the superclass to perform the calculation - * of the animated value.

- * - * @param fraction The elapsed fraction of the animation. - */ - @Override - void animateValue(float fraction) { - super.animateValue(fraction); - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].setAnimatedValue(mTarget); - } - } - - @Override - public ObjectAnimator clone() { - final ObjectAnimator anim = (ObjectAnimator) super.clone(); - return anim; - } - - @Override - public String toString() { - String returnVal = "ObjectAnimator@" + Integer.toHexString(hashCode()) + ", target " + - mTarget; - if (mValues != null) { - for (int i = 0; i < mValues.length; ++i) { - returnVal += "\n " + mValues[i].toString(); - } - } - return returnVal; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java deleted file mode 100644 index 84f7504a..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java +++ /dev/null @@ -1,1012 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -//import android.util.FloatProperty; -//import android.util.IntProperty; -import android.util.Log; -//import android.util.Property; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * This class holds information about a property and the values that that property - * should take on during an animation. PropertyValuesHolder objects can be used to create - * animations with ValueAnimator or ObjectAnimator that operate on several different properties - * in parallel. - */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class PropertyValuesHolder implements Cloneable { - - /** - * The name of the property associated with the values. This need not be a real property, - * unless this object is being used with ObjectAnimator. But this is the name by which - * aniamted values are looked up with getAnimatedValue(String) in ValueAnimator. - */ - String mPropertyName; - - /** - * @hide - */ - //protected Property mProperty; - - /** - * The setter function, if needed. ObjectAnimator hands off this functionality to - * PropertyValuesHolder, since it holds all of the per-property information. This - * property is automatically - * derived when the animation starts in setupSetterAndGetter() if using ObjectAnimator. - */ - Method mSetter = null; - - /** - * The getter function, if needed. ObjectAnimator hands off this functionality to - * PropertyValuesHolder, since it holds all of the per-property information. This - * property is automatically - * derived when the animation starts in setupSetterAndGetter() if using ObjectAnimator. - * The getter is only derived and used if one of the values is null. - */ - private Method mGetter = null; - - /** - * The type of values supplied. This information is used both in deriving the setter/getter - * functions and in deriving the type of TypeEvaluator. - */ - Class mValueType; - - /** - * The set of keyframes (time/value pairs) that define this animation. - */ - KeyframeSet mKeyframeSet = null; - - - // type evaluators for the primitive types handled by this implementation - private static final TypeEvaluator sIntEvaluator = new IntEvaluator(); - private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator(); - - // We try several different types when searching for appropriate setter/getter functions. - // The caller may have supplied values in a type that does not match the setter/getter - // functions (such as the integers 0 and 1 to represent floating point values for alpha). - // Also, the use of generics in constructors means that we end up with the Object versions - // of primitive types (Float vs. float). But most likely, the setter/getter functions - // will take primitive types instead. - // So we supply an ordered array of other types to try before giving up. - private static Class[] FLOAT_VARIANTS = {float.class, Float.class, double.class, int.class, - Double.class, Integer.class}; - private static Class[] INTEGER_VARIANTS = {int.class, Integer.class, float.class, double.class, - Float.class, Double.class}; - private static Class[] DOUBLE_VARIANTS = {double.class, Double.class, float.class, int.class, - Float.class, Integer.class}; - - // These maps hold all property entries for a particular class. This map - // is used to speed up property/setter/getter lookups for a given class/property - // combination. No need to use reflection on the combination more than once. - private static final HashMap> sSetterPropertyMap = - new HashMap>(); - private static final HashMap> sGetterPropertyMap = - new HashMap>(); - - // This lock is used to ensure that only one thread is accessing the property maps - // at a time. - final ReentrantReadWriteLock mPropertyMapLock = new ReentrantReadWriteLock(); - - // Used to pass single value to varargs parameter in setter invocation - final Object[] mTmpValueArray = new Object[1]; - - /** - * The type evaluator used to calculate the animated values. This evaluator is determined - * automatically based on the type of the start/end objects passed into the constructor, - * but the system only knows about the primitive types int and float. Any other - * type will need to set the evaluator to a custom evaluator for that type. - */ - private TypeEvaluator mEvaluator; - - /** - * The value most recently calculated by calculateValue(). This is set during - * that function and might be retrieved later either by ValueAnimator.animatedValue() or - * by the property-setting logic in ObjectAnimator.animatedValue(). - */ - private Object mAnimatedValue; - - /** - * Internal utility constructor, used by the factory methods to set the property name. - * @param propertyName The name of the property for this holder. - */ - private PropertyValuesHolder(String propertyName) { - mPropertyName = propertyName; - } - - /** - * Internal utility constructor, used by the factory methods to set the property. - * @param property The property for this holder. - */ - //private PropertyValuesHolder(Property property) { - // mProperty = property; - // if (property != null) { - // mPropertyName = property.getName(); - // } - //} - - /** - * Constructs and returns a PropertyValuesHolder with a given property name and - * set of int values. - * @param propertyName The name of the property being animated. - * @param values The values that the named property will animate between. - * @return PropertyValuesHolder The constructed PropertyValuesHolder object. - */ - public static PropertyValuesHolder ofInt(String propertyName, int... values) { - return new IntPropertyValuesHolder(propertyName, values); - } - - /** - * Constructs and returns a PropertyValuesHolder with a given property and - * set of int values. - * @param property The property being animated. Should not be null. - * @param values The values that the property will animate between. - * @return PropertyValuesHolder The constructed PropertyValuesHolder object. - */ - //public static PropertyValuesHolder ofInt(Property property, int... values) { - // return new IntPropertyValuesHolder(property, values); - //} - - /** - * Constructs and returns a PropertyValuesHolder with a given property name and - * set of float values. - * @param propertyName The name of the property being animated. - * @param values The values that the named property will animate between. - * @return PropertyValuesHolder The constructed PropertyValuesHolder object. - */ - public static PropertyValuesHolder ofFloat(String propertyName, float... values) { - return new FloatPropertyValuesHolder(propertyName, values); - } - - /** - * Constructs and returns a PropertyValuesHolder with a given property and - * set of float values. - * @param property The property being animated. Should not be null. - * @param values The values that the property will animate between. - * @return PropertyValuesHolder The constructed PropertyValuesHolder object. - */ - //public static PropertyValuesHolder ofFloat(Property property, float... values) { - // return new FloatPropertyValuesHolder(property, values); - //} - - /** - * Constructs and returns a PropertyValuesHolder with a given property name and - * set of Object values. This variant also takes a TypeEvaluator because the system - * cannot automatically interpolate between objects of unknown type. - * - * @param propertyName The name of the property being animated. - * @param evaluator A TypeEvaluator that will be called on each animation frame to - * provide the necessary interpolation between the Object values to derive the animated - * value. - * @param values The values that the named property will animate between. - * @return PropertyValuesHolder The constructed PropertyValuesHolder object. - */ - public static PropertyValuesHolder ofObject(String propertyName, TypeEvaluator evaluator, - Object... values) { - PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName); - pvh.setObjectValues(values); - pvh.setEvaluator(evaluator); - return pvh; - } - - /** - * Constructs and returns a PropertyValuesHolder with a given property and - * set of Object values. This variant also takes a TypeEvaluator because the system - * cannot automatically interpolate between objects of unknown type. - * - * @param property The property being animated. Should not be null. - * @param evaluator A TypeEvaluator that will be called on each animation frame to - * provide the necessary interpolation between the Object values to derive the animated - * value. - * @param values The values that the property will animate between. - * @return PropertyValuesHolder The constructed PropertyValuesHolder object. - */ - //public static PropertyValuesHolder ofObject(Property property, - // TypeEvaluator evaluator, V... values) { - // PropertyValuesHolder pvh = new PropertyValuesHolder(property); - // pvh.setObjectValues(values); - // pvh.setEvaluator(evaluator); - // return pvh; - //} - - /** - * Constructs and returns a PropertyValuesHolder object with the specified property name and set - * of values. These values can be of any type, but the type should be consistent so that - * an appropriate {@link android.animation.TypeEvaluator} can be found that matches - * the common type. - *

If there is only one value, it is assumed to be the end value of an animation, - * and an initial value will be derived, if possible, by calling a getter function - * on the object. Also, if any value is null, the value will be filled in when the animation - * starts in the same way. This mechanism of automatically getting null values only works - * if the PropertyValuesHolder object is used in conjunction - * {@link ObjectAnimator}, and with a getter function - * derived automatically from propertyName, since otherwise PropertyValuesHolder has - * no way of determining what the value should be. - * @param propertyName The name of the property associated with this set of values. This - * can be the actual property name to be used when using a ObjectAnimator object, or - * just a name used to get animated values, such as if this object is used with an - * ValueAnimator object. - * @param values The set of values to animate between. - */ - public static PropertyValuesHolder ofKeyframe(String propertyName, Keyframe... values) { - KeyframeSet keyframeSet = KeyframeSet.ofKeyframe(values); - if (keyframeSet instanceof IntKeyframeSet) { - return new IntPropertyValuesHolder(propertyName, (IntKeyframeSet) keyframeSet); - } else if (keyframeSet instanceof FloatKeyframeSet) { - return new FloatPropertyValuesHolder(propertyName, (FloatKeyframeSet) keyframeSet); - } - else { - PropertyValuesHolder pvh = new PropertyValuesHolder(propertyName); - pvh.mKeyframeSet = keyframeSet; - pvh.mValueType = values[0].getType(); - return pvh; - } - } - - /** - * Constructs and returns a PropertyValuesHolder object with the specified property and set - * of values. These values can be of any type, but the type should be consistent so that - * an appropriate {@link android.animation.TypeEvaluator} can be found that matches - * the common type. - *

If there is only one value, it is assumed to be the end value of an animation, - * and an initial value will be derived, if possible, by calling the property's - * {@link android.util.Property#get(Object)} function. - * Also, if any value is null, the value will be filled in when the animation - * starts in the same way. This mechanism of automatically getting null values only works - * if the PropertyValuesHolder object is used in conjunction with - * {@link ObjectAnimator}, since otherwise PropertyValuesHolder has - * no way of determining what the value should be. - * @param property The property associated with this set of values. Should not be null. - * @param values The set of values to animate between. - */ - //public static PropertyValuesHolder ofKeyframe(Property property, Keyframe... values) { - // KeyframeSet keyframeSet = KeyframeSet.ofKeyframe(values); - // if (keyframeSet instanceof IntKeyframeSet) { - // return new IntPropertyValuesHolder(property, (IntKeyframeSet) keyframeSet); - // } else if (keyframeSet instanceof FloatKeyframeSet) { - // return new FloatPropertyValuesHolder(property, (FloatKeyframeSet) keyframeSet); - // } - // else { - // PropertyValuesHolder pvh = new PropertyValuesHolder(property); - // pvh.mKeyframeSet = keyframeSet; - // pvh.mValueType = ((Keyframe)values[0]).getType(); - // return pvh; - // } - //} - - /** - * Set the animated values for this object to this set of ints. - * If there is only one value, it is assumed to be the end value of an animation, - * and an initial value will be derived, if possible, by calling a getter function - * on the object. Also, if any value is null, the value will be filled in when the animation - * starts in the same way. This mechanism of automatically getting null values only works - * if the PropertyValuesHolder object is used in conjunction - * {@link ObjectAnimator}, and with a getter function - * derived automatically from propertyName, since otherwise PropertyValuesHolder has - * no way of determining what the value should be. - * - * @param values One or more values that the animation will animate between. - */ - public void setIntValues(int... values) { - mValueType = int.class; - mKeyframeSet = KeyframeSet.ofInt(values); - } - - /** - * Set the animated values for this object to this set of floats. - * If there is only one value, it is assumed to be the end value of an animation, - * and an initial value will be derived, if possible, by calling a getter function - * on the object. Also, if any value is null, the value will be filled in when the animation - * starts in the same way. This mechanism of automatically getting null values only works - * if the PropertyValuesHolder object is used in conjunction - * {@link ObjectAnimator}, and with a getter function - * derived automatically from propertyName, since otherwise PropertyValuesHolder has - * no way of determining what the value should be. - * - * @param values One or more values that the animation will animate between. - */ - public void setFloatValues(float... values) { - mValueType = float.class; - mKeyframeSet = KeyframeSet.ofFloat(values); - } - - /** - * Set the animated values for this object to this set of Keyframes. - * - * @param values One or more values that the animation will animate between. - */ - public void setKeyframes(Keyframe... values) { - int numKeyframes = values.length; - Keyframe keyframes[] = new Keyframe[Math.max(numKeyframes,2)]; - mValueType = values[0].getType(); - for (int i = 0; i < numKeyframes; ++i) { - keyframes[i] = values[i]; - } - mKeyframeSet = new KeyframeSet(keyframes); - } - - /** - * Set the animated values for this object to this set of Objects. - * If there is only one value, it is assumed to be the end value of an animation, - * and an initial value will be derived, if possible, by calling a getter function - * on the object. Also, if any value is null, the value will be filled in when the animation - * starts in the same way. This mechanism of automatically getting null values only works - * if the PropertyValuesHolder object is used in conjunction - * {@link ObjectAnimator}, and with a getter function - * derived automatically from propertyName, since otherwise PropertyValuesHolder has - * no way of determining what the value should be. - * - * @param values One or more values that the animation will animate between. - */ - public void setObjectValues(Object... values) { - mValueType = values[0].getClass(); - mKeyframeSet = KeyframeSet.ofObject(values); - } - - /** - * Determine the setter or getter function using the JavaBeans convention of setFoo or - * getFoo for a property named 'foo'. This function figures out what the name of the - * function should be and uses reflection to find the Method with that name on the - * target object. - * - * @param targetClass The class to search for the method - * @param prefix "set" or "get", depending on whether we need a setter or getter. - * @param valueType The type of the parameter (in the case of a setter). This type - * is derived from the values set on this PropertyValuesHolder. This type is used as - * a first guess at the parameter type, but we check for methods with several different - * types to avoid problems with slight mis-matches between supplied values and actual - * value types used on the setter. - * @return Method the method associated with mPropertyName. - */ - private Method getPropertyFunction(Class targetClass, String prefix, Class valueType) { - // TODO: faster implementation... - Method returnVal = null; - String methodName = getMethodName(prefix, mPropertyName); - Class args[] = null; - if (valueType == null) { - try { - returnVal = targetClass.getMethod(methodName, args); - } catch (NoSuchMethodException e) { - Log.e("PropertyValuesHolder", targetClass.getSimpleName() + " - " + - "Couldn't find no-arg method for property " + mPropertyName + ": " + e); - } - } else { - args = new Class[1]; - Class typeVariants[]; - if (mValueType.equals(Float.class)) { - typeVariants = FLOAT_VARIANTS; - } else if (mValueType.equals(Integer.class)) { - typeVariants = INTEGER_VARIANTS; - } else if (mValueType.equals(Double.class)) { - typeVariants = DOUBLE_VARIANTS; - } else { - typeVariants = new Class[1]; - typeVariants[0] = mValueType; - } - for (Class typeVariant : typeVariants) { - args[0] = typeVariant; - try { - returnVal = targetClass.getMethod(methodName, args); - // change the value type to suit - mValueType = typeVariant; - return returnVal; - } catch (NoSuchMethodException e) { - // Swallow the error and keep trying other variants - } - } - // If we got here, then no appropriate function was found - Log.e("PropertyValuesHolder", - "Couldn't find " + prefix + "ter property " + mPropertyName + - " for " + targetClass.getSimpleName() + - " with value type "+ mValueType); - } - - return returnVal; - } - - - /** - * Returns the setter or getter requested. This utility function checks whether the - * requested method exists in the propertyMapMap cache. If not, it calls another - * utility function to request the Method from the targetClass directly. - * @param targetClass The Class on which the requested method should exist. - * @param propertyMapMap The cache of setters/getters derived so far. - * @param prefix "set" or "get", for the setter or getter. - * @param valueType The type of parameter passed into the method (null for getter). - * @return Method the method associated with mPropertyName. - */ - private Method setupSetterOrGetter(Class targetClass, - HashMap> propertyMapMap, - String prefix, Class valueType) { - Method setterOrGetter = null; - try { - // Have to lock property map prior to reading it, to guard against - // another thread putting something in there after we've checked it - // but before we've added an entry to it - mPropertyMapLock.writeLock().lock(); - HashMap propertyMap = propertyMapMap.get(targetClass); - if (propertyMap != null) { - setterOrGetter = propertyMap.get(mPropertyName); - } - if (setterOrGetter == null) { - setterOrGetter = getPropertyFunction(targetClass, prefix, valueType); - if (propertyMap == null) { - propertyMap = new HashMap(); - propertyMapMap.put(targetClass, propertyMap); - } - propertyMap.put(mPropertyName, setterOrGetter); - } - } finally { - mPropertyMapLock.writeLock().unlock(); - } - return setterOrGetter; - } - - /** - * Utility function to get the setter from targetClass - * @param targetClass The Class on which the requested method should exist. - */ - void setupSetter(Class targetClass) { - mSetter = setupSetterOrGetter(targetClass, sSetterPropertyMap, "set", mValueType); - } - - /** - * Utility function to get the getter from targetClass - */ - private void setupGetter(Class targetClass) { - mGetter = setupSetterOrGetter(targetClass, sGetterPropertyMap, "get", null); - } - - /** - * Internal function (called from ObjectAnimator) to set up the setter and getter - * prior to running the animation. If the setter has not been manually set for this - * object, it will be derived automatically given the property name, target object, and - * types of values supplied. If no getter has been set, it will be supplied iff any of the - * supplied values was null. If there is a null value, then the getter (supplied or derived) - * will be called to set those null values to the current value of the property - * on the target object. - * @param target The object on which the setter (and possibly getter) exist. - */ - void setupSetterAndGetter(Object target) { - //if (mProperty != null) { - // // check to make sure that mProperty is on the class of target - // try { - // Object testValue = mProperty.get(target); - // for (Keyframe kf : mKeyframeSet.mKeyframes) { - // if (!kf.hasValue()) { - // kf.setValue(mProperty.get(target)); - // } - // } - // return; - // } catch (ClassCastException e) { - // Log.e("PropertyValuesHolder","No such property (" + mProperty.getName() + - // ") on target object " + target + ". Trying reflection instead"); - // mProperty = null; - // } - //} - Class targetClass = target.getClass(); - if (mSetter == null) { - setupSetter(targetClass); - } - for (Keyframe kf : mKeyframeSet.mKeyframes) { - if (!kf.hasValue()) { - if (mGetter == null) { - setupGetter(targetClass); - } - try { - kf.setValue(mGetter.invoke(target)); - } catch (InvocationTargetException e) { - Log.e("PropertyValuesHolder", e.toString()); - } catch (IllegalAccessException e) { - Log.e("PropertyValuesHolder", e.toString()); - } - } - } - } - - /** - * Utility function to set the value stored in a particular Keyframe. The value used is - * whatever the value is for the property name specified in the keyframe on the target object. - * - * @param target The target object from which the current value should be extracted. - * @param kf The keyframe which holds the property name and value. - */ - private void setupValue(Object target, Keyframe kf) { - //if (mProperty != null) { - // kf.setValue(mProperty.get(target)); - //} - try { - if (mGetter == null) { - Class targetClass = target.getClass(); - setupGetter(targetClass); - } - kf.setValue(mGetter.invoke(target)); - } catch (InvocationTargetException e) { - Log.e("PropertyValuesHolder", e.toString()); - } catch (IllegalAccessException e) { - Log.e("PropertyValuesHolder", e.toString()); - } - } - - /** - * This function is called by ObjectAnimator when setting the start values for an animation. - * The start values are set according to the current values in the target object. The - * property whose value is extracted is whatever is specified by the propertyName of this - * PropertyValuesHolder object. - * - * @param target The object which holds the start values that should be set. - */ - void setupStartValue(Object target) { - setupValue(target, mKeyframeSet.mKeyframes.get(0)); - } - - /** - * This function is called by ObjectAnimator when setting the end values for an animation. - * The end values are set according to the current values in the target object. The - * property whose value is extracted is whatever is specified by the propertyName of this - * PropertyValuesHolder object. - * - * @param target The object which holds the start values that should be set. - */ - void setupEndValue(Object target) { - setupValue(target, mKeyframeSet.mKeyframes.get(mKeyframeSet.mKeyframes.size() - 1)); - } - - @Override - public PropertyValuesHolder clone() { - try { - PropertyValuesHolder newPVH = (PropertyValuesHolder) super.clone(); - newPVH.mPropertyName = mPropertyName; - //newPVH.mProperty = mProperty; - newPVH.mKeyframeSet = mKeyframeSet.clone(); - newPVH.mEvaluator = mEvaluator; - return newPVH; - } catch (CloneNotSupportedException e) { - // won't reach here - return null; - } - } - - /** - * Internal function to set the value on the target object, using the setter set up - * earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator - * to handle turning the value calculated by ValueAnimator into a value set on the object - * according to the name of the property. - * @param target The target object on which the value is set - */ - void setAnimatedValue(Object target) { - //if (mProperty != null) { - // mProperty.set(target, getAnimatedValue()); - //} - if (mSetter != null) { - try { - mTmpValueArray[0] = getAnimatedValue(); - mSetter.invoke(target, mTmpValueArray); - } catch (InvocationTargetException e) { - Log.e("PropertyValuesHolder", e.toString()); - } catch (IllegalAccessException e) { - Log.e("PropertyValuesHolder", e.toString()); - } - } - } - - /** - * Internal function, called by ValueAnimator, to set up the TypeEvaluator that will be used - * to calculate animated values. - */ - void init() { - if (mEvaluator == null) { - // We already handle int and float automatically, but not their Object - // equivalents - mEvaluator = (mValueType == Integer.class) ? sIntEvaluator : - (mValueType == Float.class) ? sFloatEvaluator : - null; - } - if (mEvaluator != null) { - // KeyframeSet knows how to evaluate the common types - only give it a custom - // evaluator if one has been set on this class - mKeyframeSet.setEvaluator(mEvaluator); - } - } - - /** - * The TypeEvaluator will the automatically determined based on the type of values - * supplied to PropertyValuesHolder. The evaluator can be manually set, however, if so - * desired. This may be important in cases where either the type of the values supplied - * do not match the way that they should be interpolated between, or if the values - * are of a custom type or one not currently understood by the animation system. Currently, - * only values of type float and int (and their Object equivalents: Float - * and Integer) are correctly interpolated; all other types require setting a TypeEvaluator. - * @param evaluator - */ - public void setEvaluator(TypeEvaluator evaluator) { - mEvaluator = evaluator; - mKeyframeSet.setEvaluator(evaluator); - } - - /** - * Function used to calculate the value according to the evaluator set up for - * this PropertyValuesHolder object. This function is called by ValueAnimator.animateValue(). - * - * @param fraction The elapsed, interpolated fraction of the animation. - */ - void calculateValue(float fraction) { - mAnimatedValue = mKeyframeSet.getValue(fraction); - } - - /** - * Sets the name of the property that will be animated. This name is used to derive - * a setter function that will be called to set animated values. - * For example, a property name of foo will result - * in a call to the function setFoo() on the target object. If either - * valueFrom or valueTo is null, then a getter function will - * also be derived and called. - * - *

Note that the setter function derived from this property name - * must take the same parameter type as the - * valueFrom and valueTo properties, otherwise the call to - * the setter function will fail.

- * - * @param propertyName The name of the property being animated. - */ - public void setPropertyName(String propertyName) { - mPropertyName = propertyName; - } - - /** - * Sets the property that will be animated. - * - *

Note that if this PropertyValuesHolder object is used with ObjectAnimator, the property - * must exist on the target object specified in that ObjectAnimator.

- * - * @param property The property being animated. - */ - //public void setProperty(Property property) { - // mProperty = property; - //} - - /** - * Gets the name of the property that will be animated. This name will be used to derive - * a setter function that will be called to set animated values. - * For example, a property name of foo will result - * in a call to the function setFoo() on the target object. If either - * valueFrom or valueTo is null, then a getter function will - * also be derived and called. - */ - public String getPropertyName() { - return mPropertyName; - } - - /** - * Internal function, called by ValueAnimator and ObjectAnimator, to retrieve the value - * most recently calculated in calculateValue(). - * @return - */ - Object getAnimatedValue() { - return mAnimatedValue; - } - - @Override - public String toString() { - return mPropertyName + ": " + mKeyframeSet.toString(); - } - - /** - * Utility method to derive a setter/getter method name from a property name, where the - * prefix is typically "set" or "get" and the first letter of the property name is - * capitalized. - * - * @param prefix The precursor to the method name, before the property name begins, typically - * "set" or "get". - * @param propertyName The name of the property that represents the bulk of the method name - * after the prefix. The first letter of this word will be capitalized in the resulting - * method name. - * @return String the property name converted to a method name according to the conventions - * specified above. - */ - static String getMethodName(String prefix, String propertyName) { - if (propertyName == null || propertyName.length() == 0) { - // shouldn't get here - return prefix; - } - char firstLetter = Character.toUpperCase(propertyName.charAt(0)); - String theRest = propertyName.substring(1); - return prefix + firstLetter + theRest; - } - - static class IntPropertyValuesHolder extends PropertyValuesHolder { - - // Cache JNI functions to avoid looking them up twice - //private static final HashMap> sJNISetterPropertyMap = - // new HashMap>(); - //int mJniSetter; - //private IntProperty mIntProperty; - - IntKeyframeSet mIntKeyframeSet; - int mIntAnimatedValue; - - public IntPropertyValuesHolder(String propertyName, IntKeyframeSet keyframeSet) { - super(propertyName); - mValueType = int.class; - mKeyframeSet = keyframeSet; - mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet; - } - - //public IntPropertyValuesHolder(Property property, IntKeyframeSet keyframeSet) { - // super(property); - // mValueType = int.class; - // mKeyframeSet = keyframeSet; - // mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet; - // if (property instanceof IntProperty) { - // mIntProperty = (IntProperty) mProperty; - // } - //} - - public IntPropertyValuesHolder(String propertyName, int... values) { - super(propertyName); - setIntValues(values); - } - - //public IntPropertyValuesHolder(Property property, int... values) { - // super(property); - // setIntValues(values); - // if (property instanceof IntProperty) { - // mIntProperty = (IntProperty) mProperty; - // } - //} - - @Override - public void setIntValues(int... values) { - super.setIntValues(values); - mIntKeyframeSet = (IntKeyframeSet) mKeyframeSet; - } - - @Override - void calculateValue(float fraction) { - mIntAnimatedValue = mIntKeyframeSet.getIntValue(fraction); - } - - @Override - Object getAnimatedValue() { - return mIntAnimatedValue; - } - - @Override - public IntPropertyValuesHolder clone() { - IntPropertyValuesHolder newPVH = (IntPropertyValuesHolder) super.clone(); - newPVH.mIntKeyframeSet = (IntKeyframeSet) newPVH.mKeyframeSet; - return newPVH; - } - - /** - * Internal function to set the value on the target object, using the setter set up - * earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator - * to handle turning the value calculated by ValueAnimator into a value set on the object - * according to the name of the property. - * @param target The target object on which the value is set - */ - @Override - void setAnimatedValue(Object target) { - //if (mIntProperty != null) { - // mIntProperty.setValue(target, mIntAnimatedValue); - // return; - //} - //if (mProperty != null) { - // mProperty.set(target, mIntAnimatedValue); - // return; - //} - //if (mJniSetter != 0) { - // nCallIntMethod(target, mJniSetter, mIntAnimatedValue); - // return; - //} - if (mSetter != null) { - try { - mTmpValueArray[0] = mIntAnimatedValue; - mSetter.invoke(target, mTmpValueArray); - } catch (InvocationTargetException e) { - Log.e("PropertyValuesHolder", e.toString()); - } catch (IllegalAccessException e) { - Log.e("PropertyValuesHolder", e.toString()); - } - } - } - - @Override - void setupSetter(Class targetClass) { - //if (mProperty != null) { - // return; - //} - // Check new static hashmap for setter method - //try { - // mPropertyMapLock.writeLock().lock(); - // HashMap propertyMap = sJNISetterPropertyMap.get(targetClass); - // if (propertyMap != null) { - // Integer mJniSetterInteger = propertyMap.get(mPropertyName); - // if (mJniSetterInteger != null) { - // mJniSetter = mJniSetterInteger; - // } - // } - // if (mJniSetter == 0) { - // String methodName = getMethodName("set", mPropertyName); - // mJniSetter = nGetIntMethod(targetClass, methodName); - // if (mJniSetter != 0) { - // if (propertyMap == null) { - // propertyMap = new HashMap(); - // sJNISetterPropertyMap.put(targetClass, propertyMap); - // } - // propertyMap.put(mPropertyName, mJniSetter); - // } - // } - //} catch (NoSuchMethodError e) { - // Log.d("PropertyValuesHolder", - // "Can't find native method using JNI, use reflection" + e); - //} finally { - // mPropertyMapLock.writeLock().unlock(); - //} - //if (mJniSetter == 0) { - // Couldn't find method through fast JNI approach - just use reflection - super.setupSetter(targetClass); - //} - } - } - - static class FloatPropertyValuesHolder extends PropertyValuesHolder { - - // Cache JNI functions to avoid looking them up twice - //private static final HashMap> sJNISetterPropertyMap = - // new HashMap>(); - //int mJniSetter; - //private FloatProperty mFloatProperty; - - FloatKeyframeSet mFloatKeyframeSet; - float mFloatAnimatedValue; - - public FloatPropertyValuesHolder(String propertyName, FloatKeyframeSet keyframeSet) { - super(propertyName); - mValueType = float.class; - mKeyframeSet = keyframeSet; - mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet; - } - - //public FloatPropertyValuesHolder(Property property, FloatKeyframeSet keyframeSet) { - // super(property); - // mValueType = float.class; - // mKeyframeSet = keyframeSet; - // mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet; - // if (property instanceof FloatProperty) { - // mFloatProperty = (FloatProperty) mProperty; - // } - //} - - public FloatPropertyValuesHolder(String propertyName, float... values) { - super(propertyName); - setFloatValues(values); - } - - //public FloatPropertyValuesHolder(Property property, float... values) { - // super(property); - // setFloatValues(values); - // if (property instanceof FloatProperty) { - // mFloatProperty = (FloatProperty) mProperty; - // } - //} - - @Override - public void setFloatValues(float... values) { - super.setFloatValues(values); - mFloatKeyframeSet = (FloatKeyframeSet) mKeyframeSet; - } - - @Override - void calculateValue(float fraction) { - mFloatAnimatedValue = mFloatKeyframeSet.getFloatValue(fraction); - } - - @Override - Object getAnimatedValue() { - return mFloatAnimatedValue; - } - - @Override - public FloatPropertyValuesHolder clone() { - FloatPropertyValuesHolder newPVH = (FloatPropertyValuesHolder) super.clone(); - newPVH.mFloatKeyframeSet = (FloatKeyframeSet) newPVH.mKeyframeSet; - return newPVH; - } - - /** - * Internal function to set the value on the target object, using the setter set up - * earlier on this PropertyValuesHolder object. This function is called by ObjectAnimator - * to handle turning the value calculated by ValueAnimator into a value set on the object - * according to the name of the property. - * @param target The target object on which the value is set - */ - @Override - void setAnimatedValue(Object target) { - //if (mFloatProperty != null) { - // mFloatProperty.setValue(target, mFloatAnimatedValue); - // return; - //} - //if (mProperty != null) { - // mProperty.set(target, mFloatAnimatedValue); - // return; - //} - //if (mJniSetter != 0) { - // nCallFloatMethod(target, mJniSetter, mFloatAnimatedValue); - // return; - //} - if (mSetter != null) { - try { - mTmpValueArray[0] = mFloatAnimatedValue; - mSetter.invoke(target, mTmpValueArray); - } catch (InvocationTargetException e) { - Log.e("PropertyValuesHolder", e.toString()); - } catch (IllegalAccessException e) { - Log.e("PropertyValuesHolder", e.toString()); - } - } - } - - @Override - void setupSetter(Class targetClass) { - //if (mProperty != null) { - // return; - //} - // Check new static hashmap for setter method - //try { - // mPropertyMapLock.writeLock().lock(); - // HashMap propertyMap = sJNISetterPropertyMap.get(targetClass); - // if (propertyMap != null) { - // Integer mJniSetterInteger = propertyMap.get(mPropertyName); - // if (mJniSetterInteger != null) { - // mJniSetter = mJniSetterInteger; - // } - // } - // if (mJniSetter == 0) { - // String methodName = getMethodName("set", mPropertyName); - // mJniSetter = nGetFloatMethod(targetClass, methodName); - // if (mJniSetter != 0) { - // if (propertyMap == null) { - // propertyMap = new HashMap(); - // sJNISetterPropertyMap.put(targetClass, propertyMap); - // } - // propertyMap.put(mPropertyName, mJniSetter); - // } - // } - //} catch (NoSuchMethodError e) { - // Log.d("PropertyValuesHolder", - // "Can't find native method using JNI, use reflection" + e); - //} finally { - // mPropertyMapLock.writeLock().unlock(); - //} - //if (mJniSetter == 0) { - // Couldn't find method through fast JNI approach - just use reflection - super.setupSetter(targetClass); - //} - } - - } - - //native static private int nGetIntMethod(Class targetClass, String methodName); - //native static private int nGetFloatMethod(Class targetClass, String methodName); - //native static private void nCallIntMethod(Object target, int methodID, int arg); - //native static private void nCallFloatMethod(Object target, int methodID, float arg); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.java deleted file mode 100644 index 0ea31924..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -/** - * Interface for use with the {@link ValueAnimator#setEvaluator(TypeEvaluator)} function. Evaluators - * allow developers to create animations on arbitrary property types, by allowing them to supply - * custom evaulators for types that are not automatically understood and used by the animation - * system. - * - * @see ValueAnimator#setEvaluator(TypeEvaluator) - */ -public interface TypeEvaluator { - - /** - * This function returns the result of linearly interpolating the start and end values, with - * fraction representing the proportion between the start and end values. The - * calculation is a simple parametric calculation: result = x0 + t * (v1 - v0), - * where x0 is startValue, x1 is endValue, - * and t is fraction. - * - * @param fraction The fraction from the starting to the ending values - * @param startValue The start value. - * @param endValue The end value. - * @return A linear interpolation between the start and end values, given the - * fraction parameter. - */ - public T evaluate(float fraction, T startValue, T endValue); - -} \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java deleted file mode 100644 index d8a12c68..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java +++ /dev/null @@ -1,1265 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.nineoldandroids.animation; - -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.util.AndroidRuntimeException; -import android.view.animation.AccelerateDecelerateInterpolator; -import android.view.animation.AnimationUtils; -import android.view.animation.Interpolator; -import android.view.animation.LinearInterpolator; - -import java.util.ArrayList; -import java.util.HashMap; - -/** - * This class provides a simple timing engine for running animations - * which calculate animated values and set them on target objects. - * - *

There is a single timing pulse that all animations use. It runs in a - * custom handler to ensure that property changes happen on the UI thread.

- * - *

By default, ValueAnimator uses non-linear time interpolation, via the - * {@link AccelerateDecelerateInterpolator} class, which accelerates into and decelerates - * out of an animation. This behavior can be changed by calling - * {@link ValueAnimator#setInterpolator(TimeInterpolator)}.

- */ -@SuppressWarnings({"rawtypes", "unchecked"}) -public class ValueAnimator extends Animator { - - /** - * Internal constants - */ - - /* - * The default amount of time in ms between animation frames - */ - private static final long DEFAULT_FRAME_DELAY = 10; - - /** - * Messages sent to timing handler: START is sent when an animation first begins, FRAME is sent - * by the handler to itself to process the next animation frame - */ - static final int ANIMATION_START = 0; - static final int ANIMATION_FRAME = 1; - - /** - * Values used with internal variable mPlayingState to indicate the current state of an - * animation. - */ - static final int STOPPED = 0; // Not yet playing - static final int RUNNING = 1; // Playing normally - static final int SEEKED = 2; // Seeked to some time value - - /** - * Internal variables - * NOTE: This object implements the clone() method, making a deep copy of any referenced - * objects. As other non-trivial fields are added to this class, make sure to add logic - * to clone() to make deep copies of them. - */ - - // The first time that the animation's animateFrame() method is called. This time is used to - // determine elapsed time (and therefore the elapsed fraction) in subsequent calls - // to animateFrame() - long mStartTime; - - /** - * Set when setCurrentPlayTime() is called. If negative, animation is not currently seeked - * to a value. - */ - long mSeekTime = -1; - - // TODO: We access the following ThreadLocal variables often, some of them on every update. - // If ThreadLocal access is significantly expensive, we may want to put all of these - // fields into a structure sot hat we just access ThreadLocal once to get the reference - // to that structure, then access the structure directly for each field. - - // The static sAnimationHandler processes the internal timing loop on which all animations - // are based - private static ThreadLocal sAnimationHandler = - new ThreadLocal(); - - // The per-thread list of all active animations - private static final ThreadLocal> sAnimations = - new ThreadLocal>() { - @Override - protected ArrayList initialValue() { - return new ArrayList(); - } - }; - - // The per-thread set of animations to be started on the next animation frame - private static final ThreadLocal> sPendingAnimations = - new ThreadLocal>() { - @Override - protected ArrayList initialValue() { - return new ArrayList(); - } - }; - - /** - * Internal per-thread collections used to avoid set collisions as animations start and end - * while being processed. - */ - private static final ThreadLocal> sDelayedAnims = - new ThreadLocal>() { - @Override - protected ArrayList initialValue() { - return new ArrayList(); - } - }; - - private static final ThreadLocal> sEndingAnims = - new ThreadLocal>() { - @Override - protected ArrayList initialValue() { - return new ArrayList(); - } - }; - - private static final ThreadLocal> sReadyAnims = - new ThreadLocal>() { - @Override - protected ArrayList initialValue() { - return new ArrayList(); - } - }; - - // The time interpolator to be used if none is set on the animation - private static final /*Time*/Interpolator sDefaultInterpolator = - new AccelerateDecelerateInterpolator(); - - // type evaluators for the primitive types handled by this implementation - //private static final TypeEvaluator sIntEvaluator = new IntEvaluator(); - //private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator(); - - /** - * Used to indicate whether the animation is currently playing in reverse. This causes the - * elapsed fraction to be inverted to calculate the appropriate values. - */ - private boolean mPlayingBackwards = false; - - /** - * This variable tracks the current iteration that is playing. When mCurrentIteration exceeds the - * repeatCount (if repeatCount!=INFINITE), the animation ends - */ - private int mCurrentIteration = 0; - - /** - * Tracks current elapsed/eased fraction, for querying in getAnimatedFraction(). - */ - private float mCurrentFraction = 0f; - - /** - * Tracks whether a startDelay'd animation has begun playing through the startDelay. - */ - private boolean mStartedDelay = false; - - /** - * Tracks the time at which the animation began playing through its startDelay. This is - * different from the mStartTime variable, which is used to track when the animation became - * active (which is when the startDelay expired and the animation was added to the active - * animations list). - */ - private long mDelayStartTime; - - /** - * Flag that represents the current state of the animation. Used to figure out when to start - * an animation (if state == STOPPED). Also used to end an animation that - * has been cancel()'d or end()'d since the last animation frame. Possible values are - * STOPPED, RUNNING, SEEKED. - */ - int mPlayingState = STOPPED; - - /** - * Additional playing state to indicate whether an animator has been start()'d. There is - * some lag between a call to start() and the first animation frame. We should still note - * that the animation has been started, even if it's first animation frame has not yet - * happened, and reflect that state in isRunning(). - * Note that delayed animations are different: they are not started until their first - * animation frame, which occurs after their delay elapses. - */ - private boolean mRunning = false; - - /** - * Additional playing state to indicate whether an animator has been start()'d, whether or - * not there is a nonzero startDelay. - */ - private boolean mStarted = false; - - /** - * Flag that denotes whether the animation is set up and ready to go. Used to - * set up animation that has not yet been started. - */ - boolean mInitialized = false; - - // - // Backing variables - // - - // How long the animation should last in ms - private long mDuration = 300; - - // The amount of time in ms to delay starting the animation after start() is called - private long mStartDelay = 0; - - // The number of milliseconds between animation frames - private static long sFrameDelay = DEFAULT_FRAME_DELAY; - - // The number of times the animation will repeat. The default is 0, which means the animation - // will play only once - private int mRepeatCount = 0; - - /** - * The type of repetition that will occur when repeatMode is nonzero. RESTART means the - * animation will start from the beginning on every new cycle. REVERSE means the animation - * will reverse directions on each iteration. - */ - private int mRepeatMode = RESTART; - - /** - * The time interpolator to be used. The elapsed fraction of the animation will be passed - * through this interpolator to calculate the interpolated fraction, which is then used to - * calculate the animated values. - */ - private /*Time*/Interpolator mInterpolator = sDefaultInterpolator; - - /** - * The set of listeners to be sent events through the life of an animation. - */ - private ArrayList mUpdateListeners = null; - - /** - * The property/value sets being animated. - */ - PropertyValuesHolder[] mValues; - - /** - * A hashmap of the PropertyValuesHolder objects. This map is used to lookup animated values - * by property name during calls to getAnimatedValue(String). - */ - HashMap mValuesMap; - - /** - * Public constants - */ - - /** - * When the animation reaches the end and repeatCount is INFINITE - * or a positive value, the animation restarts from the beginning. - */ - public static final int RESTART = 1; - /** - * When the animation reaches the end and repeatCount is INFINITE - * or a positive value, the animation reverses direction on every iteration. - */ - public static final int REVERSE = 2; - /** - * This value used used with the {@link #setRepeatCount(int)} property to repeat - * the animation indefinitely. - */ - public static final int INFINITE = -1; - - /** - * Creates a new ValueAnimator object. This default constructor is primarily for - * use internally; the factory methods which take parameters are more generally - * useful. - */ - public ValueAnimator() { - } - - /** - * Constructs and returns a ValueAnimator that animates between int values. A single - * value implies that that value is the one being animated to. However, this is not typically - * useful in a ValueAnimator object because there is no way for the object to determine the - * starting value for the animation (unlike ObjectAnimator, which can derive that value - * from the target object and property being animated). Therefore, there should typically - * be two or more values. - * - * @param values A set of values that the animation will animate between over time. - * @return A ValueAnimator object that is set up to animate between the given values. - */ - public static ValueAnimator ofInt(int... values) { - ValueAnimator anim = new ValueAnimator(); - anim.setIntValues(values); - return anim; - } - - /** - * Constructs and returns a ValueAnimator that animates between float values. A single - * value implies that that value is the one being animated to. However, this is not typically - * useful in a ValueAnimator object because there is no way for the object to determine the - * starting value for the animation (unlike ObjectAnimator, which can derive that value - * from the target object and property being animated). Therefore, there should typically - * be two or more values. - * - * @param values A set of values that the animation will animate between over time. - * @return A ValueAnimator object that is set up to animate between the given values. - */ - public static ValueAnimator ofFloat(float... values) { - ValueAnimator anim = new ValueAnimator(); - anim.setFloatValues(values); - return anim; - } - - /** - * Constructs and returns a ValueAnimator that animates between the values - * specified in the PropertyValuesHolder objects. - * - * @param values A set of PropertyValuesHolder objects whose values will be animated - * between over time. - * @return A ValueAnimator object that is set up to animate between the given values. - */ - public static ValueAnimator ofPropertyValuesHolder(PropertyValuesHolder... values) { - ValueAnimator anim = new ValueAnimator(); - anim.setValues(values); - return anim; - } - /** - * Constructs and returns a ValueAnimator that animates between Object values. A single - * value implies that that value is the one being animated to. However, this is not typically - * useful in a ValueAnimator object because there is no way for the object to determine the - * starting value for the animation (unlike ObjectAnimator, which can derive that value - * from the target object and property being animated). Therefore, there should typically - * be two or more values. - * - *

Since ValueAnimator does not know how to animate between arbitrary Objects, this - * factory method also takes a TypeEvaluator object that the ValueAnimator will use - * to perform that interpolation. - * - * @param evaluator A TypeEvaluator that will be called on each animation frame to - * provide the ncessry interpolation between the Object values to derive the animated - * value. - * @param values A set of values that the animation will animate between over time. - * @return A ValueAnimator object that is set up to animate between the given values. - */ - public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values) { - ValueAnimator anim = new ValueAnimator(); - anim.setObjectValues(values); - anim.setEvaluator(evaluator); - return anim; - } - - /** - * Sets int values that will be animated between. A single - * value implies that that value is the one being animated to. However, this is not typically - * useful in a ValueAnimator object because there is no way for the object to determine the - * starting value for the animation (unlike ObjectAnimator, which can derive that value - * from the target object and property being animated). Therefore, there should typically - * be two or more values. - * - *

If there are already multiple sets of values defined for this ValueAnimator via more - * than one PropertyValuesHolder object, this method will set the values for the first - * of those objects.

- * - * @param values A set of values that the animation will animate between over time. - */ - public void setIntValues(int... values) { - if (values == null || values.length == 0) { - return; - } - if (mValues == null || mValues.length == 0) { - setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofInt("", values)}); - } else { - PropertyValuesHolder valuesHolder = mValues[0]; - valuesHolder.setIntValues(values); - } - // New property/values/target should cause re-initialization prior to starting - mInitialized = false; - } - - /** - * Sets float values that will be animated between. A single - * value implies that that value is the one being animated to. However, this is not typically - * useful in a ValueAnimator object because there is no way for the object to determine the - * starting value for the animation (unlike ObjectAnimator, which can derive that value - * from the target object and property being animated). Therefore, there should typically - * be two or more values. - * - *

If there are already multiple sets of values defined for this ValueAnimator via more - * than one PropertyValuesHolder object, this method will set the values for the first - * of those objects.

- * - * @param values A set of values that the animation will animate between over time. - */ - public void setFloatValues(float... values) { - if (values == null || values.length == 0) { - return; - } - if (mValues == null || mValues.length == 0) { - setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofFloat("", values)}); - } else { - PropertyValuesHolder valuesHolder = mValues[0]; - valuesHolder.setFloatValues(values); - } - // New property/values/target should cause re-initialization prior to starting - mInitialized = false; - } - - /** - * Sets the values to animate between for this animation. A single - * value implies that that value is the one being animated to. However, this is not typically - * useful in a ValueAnimator object because there is no way for the object to determine the - * starting value for the animation (unlike ObjectAnimator, which can derive that value - * from the target object and property being animated). Therefore, there should typically - * be two or more values. - * - *

If there are already multiple sets of values defined for this ValueAnimator via more - * than one PropertyValuesHolder object, this method will set the values for the first - * of those objects.

- * - *

There should be a TypeEvaluator set on the ValueAnimator that knows how to interpolate - * between these value objects. ValueAnimator only knows how to interpolate between the - * primitive types specified in the other setValues() methods.

- * - * @param values The set of values to animate between. - */ - public void setObjectValues(Object... values) { - if (values == null || values.length == 0) { - return; - } - if (mValues == null || mValues.length == 0) { - setValues(new PropertyValuesHolder[]{PropertyValuesHolder.ofObject("", - (TypeEvaluator)null, values)}); - } else { - PropertyValuesHolder valuesHolder = mValues[0]; - valuesHolder.setObjectValues(values); - } - // New property/values/target should cause re-initialization prior to starting - mInitialized = false; - } - - /** - * Sets the values, per property, being animated between. This function is called internally - * by the constructors of ValueAnimator that take a list of values. But an ValueAnimator can - * be constructed without values and this method can be called to set the values manually - * instead. - * - * @param values The set of values, per property, being animated between. - */ - public void setValues(PropertyValuesHolder... values) { - int numValues = values.length; - mValues = values; - mValuesMap = new HashMap(numValues); - for (int i = 0; i < numValues; ++i) { - PropertyValuesHolder valuesHolder = values[i]; - mValuesMap.put(valuesHolder.getPropertyName(), valuesHolder); - } - // New property/values/target should cause re-initialization prior to starting - mInitialized = false; - } - - /** - * Returns the values that this ValueAnimator animates between. These values are stored in - * PropertyValuesHolder objects, even if the ValueAnimator was created with a simple list - * of value objects instead. - * - * @return PropertyValuesHolder[] An array of PropertyValuesHolder objects which hold the - * values, per property, that define the animation. - */ - public PropertyValuesHolder[] getValues() { - return mValues; - } - - /** - * This function is called immediately before processing the first animation - * frame of an animation. If there is a nonzero startDelay, the - * function is called after that delay ends. - * It takes care of the final initialization steps for the - * animation. - * - *

Overrides of this method should call the superclass method to ensure - * that internal mechanisms for the animation are set up correctly.

- */ - void initAnimation() { - if (!mInitialized) { - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].init(); - } - mInitialized = true; - } - } - - - /** - * Sets the length of the animation. The default duration is 300 milliseconds. - * - * @param duration The length of the animation, in milliseconds. This value cannot - * be negative. - * @return ValueAnimator The object called with setDuration(). This return - * value makes it easier to compose statements together that construct and then set the - * duration, as in ValueAnimator.ofInt(0, 10).setDuration(500).start(). - */ - public ValueAnimator setDuration(long duration) { - if (duration < 0) { - throw new IllegalArgumentException("Animators cannot have negative duration: " + - duration); - } - mDuration = duration; - return this; - } - - /** - * Gets the length of the animation. The default duration is 300 milliseconds. - * - * @return The length of the animation, in milliseconds. - */ - public long getDuration() { - return mDuration; - } - - /** - * Sets the position of the animation to the specified point in time. This time should - * be between 0 and the total duration of the animation, including any repetition. If - * the animation has not yet been started, then it will not advance forward after it is - * set to this time; it will simply set the time to this value and perform any appropriate - * actions based on that time. If the animation is already running, then setCurrentPlayTime() - * will set the current playing time to this value and continue playing from that point. - * - * @param playTime The time, in milliseconds, to which the animation is advanced or rewound. - */ - public void setCurrentPlayTime(long playTime) { - initAnimation(); - long currentTime = AnimationUtils.currentAnimationTimeMillis(); - if (mPlayingState != RUNNING) { - mSeekTime = playTime; - mPlayingState = SEEKED; - } - mStartTime = currentTime - playTime; - animationFrame(currentTime); - } - - /** - * Gets the current position of the animation in time, which is equal to the current - * time minus the time that the animation started. An animation that is not yet started will - * return a value of zero. - * - * @return The current position in time of the animation. - */ - public long getCurrentPlayTime() { - if (!mInitialized || mPlayingState == STOPPED) { - return 0; - } - return AnimationUtils.currentAnimationTimeMillis() - mStartTime; - } - - /** - * This custom, static handler handles the timing pulse that is shared by - * all active animations. This approach ensures that the setting of animation - * values will happen on the UI thread and that all animations will share - * the same times for calculating their values, which makes synchronizing - * animations possible. - * - */ - private static class AnimationHandler extends Handler { - /** - * There are only two messages that we care about: ANIMATION_START and - * ANIMATION_FRAME. The START message is sent when an animation's start() - * method is called. It cannot start synchronously when start() is called - * because the call may be on the wrong thread, and it would also not be - * synchronized with other animations because it would not start on a common - * timing pulse. So each animation sends a START message to the handler, which - * causes the handler to place the animation on the active animations queue and - * start processing frames for that animation. - * The FRAME message is the one that is sent over and over while there are any - * active animations to process. - */ - @Override - public void handleMessage(Message msg) { - boolean callAgain = true; - ArrayList animations = sAnimations.get(); - ArrayList delayedAnims = sDelayedAnims.get(); - switch (msg.what) { - // TODO: should we avoid sending frame message when starting if we - // were already running? - case ANIMATION_START: - ArrayList pendingAnimations = sPendingAnimations.get(); - if (animations.size() > 0 || delayedAnims.size() > 0) { - callAgain = false; - } - // pendingAnims holds any animations that have requested to be started - // We're going to clear sPendingAnimations, but starting animation may - // cause more to be added to the pending list (for example, if one animation - // starting triggers another starting). So we loop until sPendingAnimations - // is empty. - while (pendingAnimations.size() > 0) { - ArrayList pendingCopy = - (ArrayList) pendingAnimations.clone(); - pendingAnimations.clear(); - int count = pendingCopy.size(); - for (int i = 0; i < count; ++i) { - ValueAnimator anim = pendingCopy.get(i); - // If the animation has a startDelay, place it on the delayed list - if (anim.mStartDelay == 0) { - anim.startAnimation(); - } else { - delayedAnims.add(anim); - } - } - } - // fall through to process first frame of new animations - case ANIMATION_FRAME: - // currentTime holds the common time for all animations processed - // during this frame - long currentTime = AnimationUtils.currentAnimationTimeMillis(); - ArrayList readyAnims = sReadyAnims.get(); - ArrayList endingAnims = sEndingAnims.get(); - - // First, process animations currently sitting on the delayed queue, adding - // them to the active animations if they are ready - int numDelayedAnims = delayedAnims.size(); - for (int i = 0; i < numDelayedAnims; ++i) { - ValueAnimator anim = delayedAnims.get(i); - if (anim.delayedAnimationFrame(currentTime)) { - readyAnims.add(anim); - } - } - int numReadyAnims = readyAnims.size(); - if (numReadyAnims > 0) { - for (int i = 0; i < numReadyAnims; ++i) { - ValueAnimator anim = readyAnims.get(i); - anim.startAnimation(); - anim.mRunning = true; - delayedAnims.remove(anim); - } - readyAnims.clear(); - } - - // Now process all active animations. The return value from animationFrame() - // tells the handler whether it should now be ended - int numAnims = animations.size(); - int i = 0; - while (i < numAnims) { - ValueAnimator anim = animations.get(i); - if (anim.animationFrame(currentTime)) { - endingAnims.add(anim); - } - if (animations.size() == numAnims) { - ++i; - } else { - // An animation might be canceled or ended by client code - // during the animation frame. Check to see if this happened by - // seeing whether the current index is the same as it was before - // calling animationFrame(). Another approach would be to copy - // animations to a temporary list and process that list instead, - // but that entails garbage and processing overhead that would - // be nice to avoid. - --numAnims; - endingAnims.remove(anim); - } - } - if (endingAnims.size() > 0) { - for (i = 0; i < endingAnims.size(); ++i) { - endingAnims.get(i).endAnimation(); - } - endingAnims.clear(); - } - - // If there are still active or delayed animations, call the handler again - // after the frameDelay - if (callAgain && (!animations.isEmpty() || !delayedAnims.isEmpty())) { - sendEmptyMessageDelayed(ANIMATION_FRAME, Math.max(0, sFrameDelay - - (AnimationUtils.currentAnimationTimeMillis() - currentTime))); - } - break; - } - } - } - - /** - * The amount of time, in milliseconds, to delay starting the animation after - * {@link #start()} is called. - * - * @return the number of milliseconds to delay running the animation - */ - public long getStartDelay() { - return mStartDelay; - } - - /** - * The amount of time, in milliseconds, to delay starting the animation after - * {@link #start()} is called. - - * @param startDelay The amount of the delay, in milliseconds - */ - public void setStartDelay(long startDelay) { - this.mStartDelay = startDelay; - } - - /** - * The amount of time, in milliseconds, between each frame of the animation. This is a - * requested time that the animation will attempt to honor, but the actual delay between - * frames may be different, depending on system load and capabilities. This is a static - * function because the same delay will be applied to all animations, since they are all - * run off of a single timing loop. - * - * @return the requested time between frames, in milliseconds - */ - public static long getFrameDelay() { - return sFrameDelay; - } - - /** - * The amount of time, in milliseconds, between each frame of the animation. This is a - * requested time that the animation will attempt to honor, but the actual delay between - * frames may be different, depending on system load and capabilities. This is a static - * function because the same delay will be applied to all animations, since they are all - * run off of a single timing loop. - * - * @param frameDelay the requested time between frames, in milliseconds - */ - public static void setFrameDelay(long frameDelay) { - sFrameDelay = frameDelay; - } - - /** - * The most recent value calculated by this ValueAnimator when there is just one - * property being animated. This value is only sensible while the animation is running. The main - * purpose for this read-only property is to retrieve the value from the ValueAnimator - * during a call to {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which - * is called during each animation frame, immediately after the value is calculated. - * - * @return animatedValue The value most recently calculated by this ValueAnimator for - * the single property being animated. If there are several properties being animated - * (specified by several PropertyValuesHolder objects in the constructor), this function - * returns the animated value for the first of those objects. - */ - public Object getAnimatedValue() { - if (mValues != null && mValues.length > 0) { - return mValues[0].getAnimatedValue(); - } - // Shouldn't get here; should always have values unless ValueAnimator was set up wrong - return null; - } - - /** - * The most recent value calculated by this ValueAnimator for propertyName. - * The main purpose for this read-only property is to retrieve the value from the - * ValueAnimator during a call to - * {@link AnimatorUpdateListener#onAnimationUpdate(ValueAnimator)}, which - * is called during each animation frame, immediately after the value is calculated. - * - * @return animatedValue The value most recently calculated for the named property - * by this ValueAnimator. - */ - public Object getAnimatedValue(String propertyName) { - PropertyValuesHolder valuesHolder = mValuesMap.get(propertyName); - if (valuesHolder != null) { - return valuesHolder.getAnimatedValue(); - } else { - // At least avoid crashing if called with bogus propertyName - return null; - } - } - - /** - * Sets how many times the animation should be repeated. If the repeat - * count is 0, the animation is never repeated. If the repeat count is - * greater than 0 or {@link #INFINITE}, the repeat mode will be taken - * into account. The repeat count is 0 by default. - * - * @param value the number of times the animation should be repeated - */ - public void setRepeatCount(int value) { - mRepeatCount = value; - } - /** - * Defines how many times the animation should repeat. The default value - * is 0. - * - * @return the number of times the animation should repeat, or {@link #INFINITE} - */ - public int getRepeatCount() { - return mRepeatCount; - } - - /** - * Defines what this animation should do when it reaches the end. This - * setting is applied only when the repeat count is either greater than - * 0 or {@link #INFINITE}. Defaults to {@link #RESTART}. - * - * @param value {@link #RESTART} or {@link #REVERSE} - */ - public void setRepeatMode(int value) { - mRepeatMode = value; - } - - /** - * Defines what this animation should do when it reaches the end. - * - * @return either one of {@link #REVERSE} or {@link #RESTART} - */ - public int getRepeatMode() { - return mRepeatMode; - } - - /** - * Adds a listener to the set of listeners that are sent update events through the life of - * an animation. This method is called on all listeners for every frame of the animation, - * after the values for the animation have been calculated. - * - * @param listener the listener to be added to the current set of listeners for this animation. - */ - public void addUpdateListener(AnimatorUpdateListener listener) { - if (mUpdateListeners == null) { - mUpdateListeners = new ArrayList(); - } - mUpdateListeners.add(listener); - } - - /** - * Removes all listeners from the set listening to frame updates for this animation. - */ - public void removeAllUpdateListeners() { - if (mUpdateListeners == null) { - return; - } - mUpdateListeners.clear(); - mUpdateListeners = null; - } - - /** - * Removes a listener from the set listening to frame updates for this animation. - * - * @param listener the listener to be removed from the current set of update listeners - * for this animation. - */ - public void removeUpdateListener(AnimatorUpdateListener listener) { - if (mUpdateListeners == null) { - return; - } - mUpdateListeners.remove(listener); - if (mUpdateListeners.size() == 0) { - mUpdateListeners = null; - } - } - - - /** - * The time interpolator used in calculating the elapsed fraction of this animation. The - * interpolator determines whether the animation runs with linear or non-linear motion, - * such as acceleration and deceleration. The default value is - * {@link android.view.animation.AccelerateDecelerateInterpolator} - * - * @param value the interpolator to be used by this animation. A value of null - * will result in linear interpolation. - */ - @Override - public void setInterpolator(/*Time*/Interpolator value) { - if (value != null) { - mInterpolator = value; - } else { - mInterpolator = new LinearInterpolator(); - } - } - - /** - * Returns the timing interpolator that this ValueAnimator uses. - * - * @return The timing interpolator for this ValueAnimator. - */ - public /*Time*/Interpolator getInterpolator() { - return mInterpolator; - } - - /** - * The type evaluator to be used when calculating the animated values of this animation. - * The system will automatically assign a float or int evaluator based on the type - * of startValue and endValue in the constructor. But if these values - * are not one of these primitive types, or if different evaluation is desired (such as is - * necessary with int values that represent colors), a custom evaluator needs to be assigned. - * For example, when running an animation on color values, the {@link ArgbEvaluator} - * should be used to get correct RGB color interpolation. - * - *

If this ValueAnimator has only one set of values being animated between, this evaluator - * will be used for that set. If there are several sets of values being animated, which is - * the case if PropertyValuesHOlder objects were set on the ValueAnimator, then the evaluator - * is assigned just to the first PropertyValuesHolder object.

- * - * @param value the evaluator to be used this animation - */ - public void setEvaluator(TypeEvaluator value) { - if (value != null && mValues != null && mValues.length > 0) { - mValues[0].setEvaluator(value); - } - } - - /** - * Start the animation playing. This version of start() takes a boolean flag that indicates - * whether the animation should play in reverse. The flag is usually false, but may be set - * to true if called from the reverse() method. - * - *

The animation started by calling this method will be run on the thread that called - * this method. This thread should have a Looper on it (a runtime exception will be thrown if - * this is not the case). Also, if the animation will animate - * properties of objects in the view hierarchy, then the calling thread should be the UI - * thread for that view hierarchy.

- * - * @param playBackwards Whether the ValueAnimator should start playing in reverse. - */ - private void start(boolean playBackwards) { - if (Looper.myLooper() == null) { - throw new AndroidRuntimeException("Animators may only be run on Looper threads"); - } - mPlayingBackwards = playBackwards; - mCurrentIteration = 0; - mPlayingState = STOPPED; - mStarted = true; - mStartedDelay = false; - sPendingAnimations.get().add(this); - if (mStartDelay == 0) { - // This sets the initial value of the animation, prior to actually starting it running - setCurrentPlayTime(getCurrentPlayTime()); - mPlayingState = STOPPED; - mRunning = true; - - if (mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - int numListeners = tmpListeners.size(); - for (int i = 0; i < numListeners; ++i) { - tmpListeners.get(i).onAnimationStart(this); - } - } - } - AnimationHandler animationHandler = sAnimationHandler.get(); - if (animationHandler == null) { - animationHandler = new AnimationHandler(); - sAnimationHandler.set(animationHandler); - } - animationHandler.sendEmptyMessage(ANIMATION_START); - } - - @Override - public void start() { - start(false); - } - - @Override - public void cancel() { - // Only cancel if the animation is actually running or has been started and is about - // to run - if (mPlayingState != STOPPED || sPendingAnimations.get().contains(this) || - sDelayedAnims.get().contains(this)) { - // Only notify listeners if the animator has actually started - if (mRunning && mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - for (AnimatorListener listener : tmpListeners) { - listener.onAnimationCancel(this); - } - } - endAnimation(); - } - } - - @Override - public void end() { - if (!sAnimations.get().contains(this) && !sPendingAnimations.get().contains(this)) { - // Special case if the animation has not yet started; get it ready for ending - mStartedDelay = false; - startAnimation(); - } else if (!mInitialized) { - initAnimation(); - } - // The final value set on the target varies, depending on whether the animation - // was supposed to repeat an odd number of times - if (mRepeatCount > 0 && (mRepeatCount & 0x01) == 1) { - animateValue(0f); - } else { - animateValue(1f); - } - endAnimation(); - } - - @Override - public boolean isRunning() { - return (mPlayingState == RUNNING || mRunning); - } - - @Override - public boolean isStarted() { - return mStarted; - } - - /** - * Plays the ValueAnimator in reverse. If the animation is already running, - * it will stop itself and play backwards from the point reached when reverse was called. - * If the animation is not currently running, then it will start from the end and - * play backwards. This behavior is only set for the current animation; future playing - * of the animation will use the default behavior of playing forward. - */ - public void reverse() { - mPlayingBackwards = !mPlayingBackwards; - if (mPlayingState == RUNNING) { - long currentTime = AnimationUtils.currentAnimationTimeMillis(); - long currentPlayTime = currentTime - mStartTime; - long timeLeft = mDuration - currentPlayTime; - mStartTime = currentTime - timeLeft; - } else { - start(true); - } - } - - /** - * Called internally to end an animation by removing it from the animations list. Must be - * called on the UI thread. - */ - private void endAnimation() { - sAnimations.get().remove(this); - sPendingAnimations.get().remove(this); - sDelayedAnims.get().remove(this); - mPlayingState = STOPPED; - if (mRunning && mListeners != null) { - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - int numListeners = tmpListeners.size(); - for (int i = 0; i < numListeners; ++i) { - tmpListeners.get(i).onAnimationEnd(this); - } - } - mRunning = false; - mStarted = false; - } - - /** - * Called internally to start an animation by adding it to the active animations list. Must be - * called on the UI thread. - */ - private void startAnimation() { - initAnimation(); - sAnimations.get().add(this); - if (mStartDelay > 0 && mListeners != null) { - // Listeners were already notified in start() if startDelay is 0; this is - // just for delayed animations - ArrayList tmpListeners = - (ArrayList) mListeners.clone(); - int numListeners = tmpListeners.size(); - for (int i = 0; i < numListeners; ++i) { - tmpListeners.get(i).onAnimationStart(this); - } - } - } - - /** - * Internal function called to process an animation frame on an animation that is currently - * sleeping through its startDelay phase. The return value indicates whether it - * should be woken up and put on the active animations queue. - * - * @param currentTime The current animation time, used to calculate whether the animation - * has exceeded its startDelay and should be started. - * @return True if the animation's startDelay has been exceeded and the animation - * should be added to the set of active animations. - */ - private boolean delayedAnimationFrame(long currentTime) { - if (!mStartedDelay) { - mStartedDelay = true; - mDelayStartTime = currentTime; - } else { - long deltaTime = currentTime - mDelayStartTime; - if (deltaTime > mStartDelay) { - // startDelay ended - start the anim and record the - // mStartTime appropriately - mStartTime = currentTime - (deltaTime - mStartDelay); - mPlayingState = RUNNING; - return true; - } - } - return false; - } - - /** - * This internal function processes a single animation frame for a given animation. The - * currentTime parameter is the timing pulse sent by the handler, used to calculate the - * elapsed duration, and therefore - * the elapsed fraction, of the animation. The return value indicates whether the animation - * should be ended (which happens when the elapsed time of the animation exceeds the - * animation's duration, including the repeatCount). - * - * @param currentTime The current time, as tracked by the static timing handler - * @return true if the animation's duration, including any repetitions due to - * repeatCount has been exceeded and the animation should be ended. - */ - boolean animationFrame(long currentTime) { - boolean done = false; - - if (mPlayingState == STOPPED) { - mPlayingState = RUNNING; - if (mSeekTime < 0) { - mStartTime = currentTime; - } else { - mStartTime = currentTime - mSeekTime; - // Now that we're playing, reset the seek time - mSeekTime = -1; - } - } - switch (mPlayingState) { - case RUNNING: - case SEEKED: - float fraction = mDuration > 0 ? (float)(currentTime - mStartTime) / mDuration : 1f; - if (fraction >= 1f) { - if (mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE) { - // Time to repeat - if (mListeners != null) { - int numListeners = mListeners.size(); - for (int i = 0; i < numListeners; ++i) { - mListeners.get(i).onAnimationRepeat(this); - } - } - if (mRepeatMode == REVERSE) { - mPlayingBackwards = mPlayingBackwards ? false : true; - } - mCurrentIteration += (int)fraction; - fraction = fraction % 1f; - mStartTime += mDuration; - } else { - done = true; - fraction = Math.min(fraction, 1.0f); - } - } - if (mPlayingBackwards) { - fraction = 1f - fraction; - } - animateValue(fraction); - break; - } - - return done; - } - - /** - * Returns the current animation fraction, which is the elapsed/interpolated fraction used in - * the most recent frame update on the animation. - * - * @return Elapsed/interpolated fraction of the animation. - */ - public float getAnimatedFraction() { - return mCurrentFraction; - } - - /** - * This method is called with the elapsed fraction of the animation during every - * animation frame. This function turns the elapsed fraction into an interpolated fraction - * and then into an animated value (from the evaluator. The function is called mostly during - * animation updates, but it is also called when the end() - * function is called, to set the final value on the property. - * - *

Overrides of this method must call the superclass to perform the calculation - * of the animated value.

- * - * @param fraction The elapsed fraction of the animation. - */ - void animateValue(float fraction) { - fraction = mInterpolator.getInterpolation(fraction); - mCurrentFraction = fraction; - int numValues = mValues.length; - for (int i = 0; i < numValues; ++i) { - mValues[i].calculateValue(fraction); - } - if (mUpdateListeners != null) { - int numListeners = mUpdateListeners.size(); - for (int i = 0; i < numListeners; ++i) { - mUpdateListeners.get(i).onAnimationUpdate(this); - } - } - } - - @Override - public ValueAnimator clone() { - final ValueAnimator anim = (ValueAnimator) super.clone(); - if (mUpdateListeners != null) { - ArrayList oldListeners = mUpdateListeners; - anim.mUpdateListeners = new ArrayList(); - int numListeners = oldListeners.size(); - for (int i = 0; i < numListeners; ++i) { - anim.mUpdateListeners.add(oldListeners.get(i)); - } - } - anim.mSeekTime = -1; - anim.mPlayingBackwards = false; - anim.mCurrentIteration = 0; - anim.mInitialized = false; - anim.mPlayingState = STOPPED; - anim.mStartedDelay = false; - PropertyValuesHolder[] oldValues = mValues; - if (oldValues != null) { - int numValues = oldValues.length; - anim.mValues = new PropertyValuesHolder[numValues]; - anim.mValuesMap = new HashMap(numValues); - for (int i = 0; i < numValues; ++i) { - PropertyValuesHolder newValuesHolder = oldValues[i].clone(); - anim.mValues[i] = newValuesHolder; - anim.mValuesMap.put(newValuesHolder.getPropertyName(), newValuesHolder); - } - } - return anim; - } - - /** - * Implementors of this interface can add themselves as update listeners - * to an ValueAnimator instance to receive callbacks on every animation - * frame, after the current frame's values have been calculated for that - * ValueAnimator. - */ - public static interface AnimatorUpdateListener { - /** - *

Notifies the occurrence of another frame of the animation.

- * - * @param animation The animation which was repeated. - */ - void onAnimationUpdate(ValueAnimator animation); - - } - - /** - * Return the number of animations currently running. - * - * Used by StrictMode internally to annotate violations. Only - * called on the main thread. - * - * @hide - */ - public static int getCurrentAnimationsCount() { - return sAnimations.get().size(); - } - - /** - * Clear all animations on this thread, without canceling or ending them. - * This should be used with caution. - * - * @hide - */ - public static void clearAllAnimations() { - sAnimations.get().clear(); - sPendingAnimations.get().clear(); - sDelayedAnims.get().clear(); - } - - @Override - public String toString() { - String returnVal = "ValueAnimator@" + Integer.toHexString(hashCode()); - if (mValues != null) { - for (int i = 0; i < mValues.length; ++i) { - returnVal += "\n " + mValues[i].toString(); - } - } - return returnVal; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.java deleted file mode 100644 index 7b830b9c..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.actionbarsherlock.internal.nineoldandroids.view; - -import android.content.Context; -import android.util.AttributeSet; -import android.view.ViewGroup; - -import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; - -public abstract class NineViewGroup extends ViewGroup { - private final AnimatorProxy mProxy; - - public NineViewGroup(Context context) { - super(context); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - public NineViewGroup(Context context, AttributeSet attrs) { - super(context, attrs); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - public NineViewGroup(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - - @Override - public void setVisibility(int visibility) { - if (mProxy != null) { - if (visibility == GONE) { - clearAnimation(); - } else if (visibility == VISIBLE) { - setAnimation(mProxy); - } - } - super.setVisibility(visibility); - } - - public float getAlpha() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getAlpha(); - } else { - return super.getAlpha(); - } - } - public void setAlpha(float alpha) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setAlpha(alpha); - } else { - super.setAlpha(alpha); - } - } - public float getTranslationX() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getTranslationX(); - } else { - return super.getTranslationX(); - } - } - public void setTranslationX(float translationX) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setTranslationX(translationX); - } else { - super.setTranslationX(translationX); - } - } - public float getTranslationY() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getTranslationY(); - } else { - return super.getTranslationY(); - } - } - public void setTranslationY(float translationY) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setTranslationY(translationY); - } else { - super.setTranslationY(translationY); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.java deleted file mode 100644 index 067d0494..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.java +++ /dev/null @@ -1,212 +0,0 @@ -package com.actionbarsherlock.internal.nineoldandroids.view.animation; - -import java.lang.ref.WeakReference; -import java.util.WeakHashMap; -import android.graphics.Matrix; -import android.graphics.RectF; -import android.os.Build; -import android.util.FloatMath; -import android.view.View; -import android.view.animation.Animation; -import android.view.animation.Transformation; - -public final class AnimatorProxy extends Animation { - public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; - - private static final WeakHashMap PROXIES = - new WeakHashMap(); - - public static AnimatorProxy wrap(View view) { - AnimatorProxy proxy = PROXIES.get(view); - if (proxy == null) { - proxy = new AnimatorProxy(view); - PROXIES.put(view, proxy); - } - return proxy; - } - - private final WeakReference mView; - - private float mAlpha = 1; - private float mScaleX = 1; - private float mScaleY = 1; - private float mTranslationX; - private float mTranslationY; - - private final RectF mBefore = new RectF(); - private final RectF mAfter = new RectF(); - private final Matrix mTempMatrix = new Matrix(); - - private AnimatorProxy(View view) { - setDuration(0); //perform transformation immediately - setFillAfter(true); //persist transformation beyond duration - view.setAnimation(this); - mView = new WeakReference(view); - } - - public float getAlpha() { - return mAlpha; - } - public void setAlpha(float alpha) { - if (mAlpha != alpha) { - mAlpha = alpha; - View view = mView.get(); - if (view != null) { - view.invalidate(); - } - } - } - public float getScaleX() { - return mScaleX; - } - public void setScaleX(float scaleX) { - if (mScaleX != scaleX) { - prepareForUpdate(); - mScaleX = scaleX; - invalidateAfterUpdate(); - } - } - public float getScaleY() { - return mScaleY; - } - public void setScaleY(float scaleY) { - if (mScaleY != scaleY) { - prepareForUpdate(); - mScaleY = scaleY; - invalidateAfterUpdate(); - } - } - public int getScrollX() { - View view = mView.get(); - if (view == null) { - return 0; - } - return view.getScrollX(); - } - public void setScrollX(int value) { - View view = mView.get(); - if (view != null) { - view.scrollTo(value, view.getScrollY()); - } - } - public int getScrollY() { - View view = mView.get(); - if (view == null) { - return 0; - } - return view.getScrollY(); - } - public void setScrollY(int value) { - View view = mView.get(); - if (view != null) { - view.scrollTo(view.getScrollY(), value); - } - } - - public float getTranslationX() { - return mTranslationX; - } - public void setTranslationX(float translationX) { - if (mTranslationX != translationX) { - prepareForUpdate(); - mTranslationX = translationX; - invalidateAfterUpdate(); - } - } - public float getTranslationY() { - return mTranslationY; - } - public void setTranslationY(float translationY) { - if (mTranslationY != translationY) { - prepareForUpdate(); - mTranslationY = translationY; - invalidateAfterUpdate(); - } - } - - private void prepareForUpdate() { - View view = mView.get(); - if (view != null) { - computeRect(mBefore, view); - } - } - private void invalidateAfterUpdate() { - View view = mView.get(); - if (view == null) { - return; - } - View parent = (View)view.getParent(); - if (parent == null) { - return; - } - - view.setAnimation(this); - - final RectF after = mAfter; - computeRect(after, view); - after.union(mBefore); - - parent.invalidate( - (int) FloatMath.floor(after.left), - (int) FloatMath.floor(after.top), - (int) FloatMath.ceil(after.right), - (int) FloatMath.ceil(after.bottom)); - } - - private void computeRect(final RectF r, View view) { - // compute current rectangle according to matrix transformation - final float w = view.getWidth(); - final float h = view.getHeight(); - - // use a rectangle at 0,0 to make sure we don't run into issues with scaling - r.set(0, 0, w, h); - - final Matrix m = mTempMatrix; - m.reset(); - transformMatrix(m, view); - mTempMatrix.mapRect(r); - - r.offset(view.getLeft(), view.getTop()); - - // Straighten coords if rotations flipped them - if (r.right < r.left) { - final float f = r.right; - r.right = r.left; - r.left = f; - } - if (r.bottom < r.top) { - final float f = r.top; - r.top = r.bottom; - r.bottom = f; - } - } - - private void transformMatrix(Matrix m, View view) { - final float w = view.getWidth(); - final float h = view.getHeight(); - - final float sX = mScaleX; - final float sY = mScaleY; - if ((sX != 1.0f) || (sY != 1.0f)) { - final float deltaSX = ((sX * w) - w) / 2f; - final float deltaSY = ((sY * h) - h) / 2f; - m.postScale(sX, sY); - m.postTranslate(-deltaSX, -deltaSY); - } - m.postTranslate(mTranslationX, mTranslationY); - } - - @Override - protected void applyTransformation(float interpolatedTime, Transformation t) { - View view = mView.get(); - if (view != null) { - t.setAlpha(mAlpha); - transformMatrix(t.getMatrix(), view); - } - } - - @Override - public void reset() { - /* Do nothing. */ - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.java deleted file mode 100644 index 2c428e90..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.actionbarsherlock.internal.nineoldandroids.widget; - -import android.content.Context; -import android.util.AttributeSet; -import android.widget.FrameLayout; - -import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; - -public class NineFrameLayout extends FrameLayout { - private final AnimatorProxy mProxy; - - public NineFrameLayout(Context context) { - super(context); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - public NineFrameLayout(Context context, AttributeSet attrs) { - super(context, attrs); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - public NineFrameLayout(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - - @Override - public void setVisibility(int visibility) { - if (mProxy != null) { - if (visibility == GONE) { - clearAnimation(); - } else if (visibility == VISIBLE) { - setAnimation(mProxy); - } - } - super.setVisibility(visibility); - } - - public float getAlpha() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getAlpha(); - } else { - return super.getAlpha(); - } - } - public void setAlpha(float alpha) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setAlpha(alpha); - } else { - super.setAlpha(alpha); - } - } - public float getTranslationY() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getTranslationY(); - } else { - return super.getTranslationY(); - } - } - public void setTranslationY(float translationY) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setTranslationY(translationY); - } else { - super.setTranslationY(translationY); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.java deleted file mode 100644 index 129b5aaa..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.actionbarsherlock.internal.nineoldandroids.widget; - -import android.content.Context; -import android.widget.HorizontalScrollView; -import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; - -public class NineHorizontalScrollView extends HorizontalScrollView { - private final AnimatorProxy mProxy; - - public NineHorizontalScrollView(Context context) { - super(context); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - - @Override - public void setVisibility(int visibility) { - if (mProxy != null) { - if (visibility == GONE) { - clearAnimation(); - } else if (visibility == VISIBLE) { - setAnimation(mProxy); - } - } - super.setVisibility(visibility); - } - - public float getAlpha() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getAlpha(); - } else { - return super.getAlpha(); - } - } - public void setAlpha(float alpha) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setAlpha(alpha); - } else { - super.setAlpha(alpha); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.java deleted file mode 100644 index a670b1f6..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.actionbarsherlock.internal.nineoldandroids.widget; - -import android.content.Context; -import android.util.AttributeSet; -import android.widget.LinearLayout; - -import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; - -public class NineLinearLayout extends LinearLayout { - private final AnimatorProxy mProxy; - - public NineLinearLayout(Context context) { - super(context); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - public NineLinearLayout(Context context, AttributeSet attrs) { - super(context, attrs); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - public NineLinearLayout(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; - } - - @Override - public void setVisibility(int visibility) { - if (mProxy != null) { - if (visibility == GONE) { - clearAnimation(); - } else if (visibility == VISIBLE) { - setAnimation(mProxy); - } - } - super.setVisibility(visibility); - } - - public float getAlpha() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getAlpha(); - } else { - return super.getAlpha(); - } - } - public void setAlpha(float alpha) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setAlpha(alpha); - } else { - super.setAlpha(alpha); - } - } - public float getTranslationX() { - if (AnimatorProxy.NEEDS_PROXY) { - return mProxy.getTranslationX(); - } else { - return super.getTranslationX(); - } - } - public void setTranslationX(float translationX) { - if (AnimatorProxy.NEEDS_PROXY) { - mProxy.setTranslationX(translationX); - } else { - super.setTranslationX(translationX); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/ActionProviderWrapper.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/ActionProviderWrapper.java deleted file mode 100644 index b136d50f..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/ActionProviderWrapper.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.actionbarsherlock.internal.view; - -import com.actionbarsherlock.internal.view.menu.SubMenuWrapper; -import com.actionbarsherlock.view.ActionProvider; -import android.view.View; - -public class ActionProviderWrapper extends android.view.ActionProvider { - private final ActionProvider mProvider; - - - public ActionProviderWrapper(ActionProvider provider) { - super(null/*TODO*/); //XXX this *should* be unused - mProvider = provider; - } - - - public ActionProvider unwrap() { - return mProvider; - } - - @Override - public View onCreateActionView() { - return mProvider.onCreateActionView(); - } - - @Override - public boolean hasSubMenu() { - return mProvider.hasSubMenu(); - } - - @Override - public boolean onPerformDefaultAction() { - return mProvider.onPerformDefaultAction(); - } - - @Override - public void onPrepareSubMenu(android.view.SubMenu subMenu) { - mProvider.onPrepareSubMenu(new SubMenuWrapper(subMenu)); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/StandaloneActionMode.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/StandaloneActionMode.java deleted file mode 100644 index 0a87bd3f..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/StandaloneActionMode.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.actionbarsherlock.internal.view; - -import android.content.Context; -import android.view.View; -import android.view.accessibility.AccessibilityEvent; - -import java.lang.ref.WeakReference; - -import com.actionbarsherlock.internal.view.menu.MenuBuilder; -import com.actionbarsherlock.internal.view.menu.MenuPopupHelper; -import com.actionbarsherlock.internal.view.menu.SubMenuBuilder; -import com.actionbarsherlock.internal.widget.ActionBarContextView; -import com.actionbarsherlock.view.ActionMode; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -public class StandaloneActionMode extends ActionMode implements MenuBuilder.Callback { - private Context mContext; - private ActionBarContextView mContextView; - private ActionMode.Callback mCallback; - private WeakReference mCustomView; - private boolean mFinished; - private boolean mFocusable; - - private MenuBuilder mMenu; - - public StandaloneActionMode(Context context, ActionBarContextView view, - ActionMode.Callback callback, boolean isFocusable) { - mContext = context; - mContextView = view; - mCallback = callback; - - mMenu = new MenuBuilder(context).setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); - mMenu.setCallback(this); - mFocusable = isFocusable; - } - - @Override - public void setTitle(CharSequence title) { - mContextView.setTitle(title); - } - - @Override - public void setSubtitle(CharSequence subtitle) { - mContextView.setSubtitle(subtitle); - } - - @Override - public void setTitle(int resId) { - setTitle(mContext.getString(resId)); - } - - @Override - public void setSubtitle(int resId) { - setSubtitle(mContext.getString(resId)); - } - - @Override - public void setCustomView(View view) { - mContextView.setCustomView(view); - mCustomView = view != null ? new WeakReference(view) : null; - } - - @Override - public void invalidate() { - mCallback.onPrepareActionMode(this, mMenu); - } - - @Override - public void finish() { - if (mFinished) { - return; - } - mFinished = true; - - mContextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); - mCallback.onDestroyActionMode(this); - } - - @Override - public Menu getMenu() { - return mMenu; - } - - @Override - public CharSequence getTitle() { - return mContextView.getTitle(); - } - - @Override - public CharSequence getSubtitle() { - return mContextView.getSubtitle(); - } - - @Override - public View getCustomView() { - return mCustomView != null ? mCustomView.get() : null; - } - - @Override - public MenuInflater getMenuInflater() { - return new MenuInflater(mContext); - } - - public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { - return mCallback.onActionItemClicked(this, item); - } - - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - } - - public boolean onSubMenuSelected(SubMenuBuilder subMenu) { - if (!subMenu.hasVisibleItems()) { - return true; - } - - new MenuPopupHelper(mContext, subMenu).show(); - return true; - } - - public void onCloseSubMenu(SubMenuBuilder menu) { - } - - public void onMenuModeChange(MenuBuilder menu) { - invalidate(); - mContextView.showOverflowMenu(); - } - - public boolean isUiFocusable() { - return mFocusable; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.java deleted file mode 100644 index 7d45e81b..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.actionbarsherlock.internal.view; - -public interface View_HasStateListenerSupport { - void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener); - void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.java deleted file mode 100644 index 3869d329..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.actionbarsherlock.internal.view; - -import android.view.View; - -public interface View_OnAttachStateChangeListener { - void onViewAttachedToWindow(View v); - void onViewDetachedFromWindow(View v); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenu.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenu.java deleted file mode 100644 index 0354ad1a..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenu.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import java.util.ArrayList; -import java.util.List; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.view.KeyEvent; - -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -/** - * @hide - */ -public class ActionMenu implements Menu { - private Context mContext; - - private boolean mIsQwerty; - - private ArrayList mItems; - - public ActionMenu(Context context) { - mContext = context; - mItems = new ArrayList(); - } - - public Context getContext() { - return mContext; - } - - public MenuItem add(CharSequence title) { - return add(0, 0, 0, title); - } - - public MenuItem add(int titleRes) { - return add(0, 0, 0, titleRes); - } - - public MenuItem add(int groupId, int itemId, int order, int titleRes) { - return add(groupId, itemId, order, mContext.getResources().getString(titleRes)); - } - - public MenuItem add(int groupId, int itemId, int order, CharSequence title) { - ActionMenuItem item = new ActionMenuItem(getContext(), - groupId, itemId, 0, order, title); - mItems.add(order, item); - return item; - } - - public int addIntentOptions(int groupId, int itemId, int order, - ComponentName caller, Intent[] specifics, Intent intent, int flags, - MenuItem[] outSpecificItems) { - PackageManager pm = mContext.getPackageManager(); - final List lri = - pm.queryIntentActivityOptions(caller, specifics, intent, 0); - final int N = lri != null ? lri.size() : 0; - - if ((flags & FLAG_APPEND_TO_GROUP) == 0) { - removeGroup(groupId); - } - - for (int i=0; i= 0) { - outSpecificItems[ri.specificIndex] = item; - } - } - - return N; - } - - public SubMenu addSubMenu(CharSequence title) { - // TODO Implement submenus - return null; - } - - public SubMenu addSubMenu(int titleRes) { - // TODO Implement submenus - return null; - } - - public SubMenu addSubMenu(int groupId, int itemId, int order, - CharSequence title) { - // TODO Implement submenus - return null; - } - - public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { - // TODO Implement submenus - return null; - } - - public void clear() { - mItems.clear(); - } - - public void close() { - } - - private int findItemIndex(int id) { - final ArrayList items = mItems; - final int itemCount = items.size(); - for (int i = 0; i < itemCount; i++) { - if (items.get(i).getItemId() == id) { - return i; - } - } - - return -1; - } - - public MenuItem findItem(int id) { - return mItems.get(findItemIndex(id)); - } - - public MenuItem getItem(int index) { - return mItems.get(index); - } - - public boolean hasVisibleItems() { - final ArrayList items = mItems; - final int itemCount = items.size(); - - for (int i = 0; i < itemCount; i++) { - if (items.get(i).isVisible()) { - return true; - } - } - - return false; - } - - private ActionMenuItem findItemWithShortcut(int keyCode, KeyEvent event) { - // TODO Make this smarter. - final boolean qwerty = mIsQwerty; - final ArrayList items = mItems; - final int itemCount = items.size(); - - for (int i = 0; i < itemCount; i++) { - ActionMenuItem item = items.get(i); - final char shortcut = qwerty ? item.getAlphabeticShortcut() : - item.getNumericShortcut(); - if (keyCode == shortcut) { - return item; - } - } - return null; - } - - public boolean isShortcutKey(int keyCode, KeyEvent event) { - return findItemWithShortcut(keyCode, event) != null; - } - - public boolean performIdentifierAction(int id, int flags) { - final int index = findItemIndex(id); - if (index < 0) { - return false; - } - - return mItems.get(index).invoke(); - } - - public boolean performShortcut(int keyCode, KeyEvent event, int flags) { - ActionMenuItem item = findItemWithShortcut(keyCode, event); - if (item == null) { - return false; - } - - return item.invoke(); - } - - public void removeGroup(int groupId) { - final ArrayList items = mItems; - int itemCount = items.size(); - int i = 0; - while (i < itemCount) { - if (items.get(i).getGroupId() == groupId) { - items.remove(i); - itemCount--; - } else { - i++; - } - } - } - - public void removeItem(int id) { - mItems.remove(findItemIndex(id)); - } - - public void setGroupCheckable(int group, boolean checkable, - boolean exclusive) { - final ArrayList items = mItems; - final int itemCount = items.size(); - - for (int i = 0; i < itemCount; i++) { - ActionMenuItem item = items.get(i); - if (item.getGroupId() == group) { - item.setCheckable(checkable); - item.setExclusiveCheckable(exclusive); - } - } - } - - public void setGroupEnabled(int group, boolean enabled) { - final ArrayList items = mItems; - final int itemCount = items.size(); - - for (int i = 0; i < itemCount; i++) { - ActionMenuItem item = items.get(i); - if (item.getGroupId() == group) { - item.setEnabled(enabled); - } - } - } - - public void setGroupVisible(int group, boolean visible) { - final ArrayList items = mItems; - final int itemCount = items.size(); - - for (int i = 0; i < itemCount; i++) { - ActionMenuItem item = items.get(i); - if (item.getGroupId() == group) { - item.setVisible(visible); - } - } - } - - public void setQwertyMode(boolean isQwerty) { - mIsQwerty = isQwerty; - } - - public int size() { - return mItems.size(); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItem.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItem.java deleted file mode 100644 index 510b9748..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItem.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import android.content.Context; -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.View; - -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -/** - * @hide - */ -public class ActionMenuItem implements MenuItem { - private final int mId; - private final int mGroup; - //UNUSED private final int mCategoryOrder; - private final int mOrdering; - - private CharSequence mTitle; - private CharSequence mTitleCondensed; - private Intent mIntent; - private char mShortcutNumericChar; - private char mShortcutAlphabeticChar; - - private Drawable mIconDrawable; - //UNUSED private int mIconResId = NO_ICON; - - private Context mContext; - - private MenuItem.OnMenuItemClickListener mClickListener; - - //UNUSED private static final int NO_ICON = 0; - - private int mFlags = ENABLED; - private static final int CHECKABLE = 0x00000001; - private static final int CHECKED = 0x00000002; - private static final int EXCLUSIVE = 0x00000004; - private static final int HIDDEN = 0x00000008; - private static final int ENABLED = 0x00000010; - - public ActionMenuItem(Context context, int group, int id, int categoryOrder, int ordering, - CharSequence title) { - mContext = context; - mId = id; - mGroup = group; - //UNUSED mCategoryOrder = categoryOrder; - mOrdering = ordering; - mTitle = title; - } - - public char getAlphabeticShortcut() { - return mShortcutAlphabeticChar; - } - - public int getGroupId() { - return mGroup; - } - - public Drawable getIcon() { - return mIconDrawable; - } - - public Intent getIntent() { - return mIntent; - } - - public int getItemId() { - return mId; - } - - public ContextMenuInfo getMenuInfo() { - return null; - } - - public char getNumericShortcut() { - return mShortcutNumericChar; - } - - public int getOrder() { - return mOrdering; - } - - public SubMenu getSubMenu() { - return null; - } - - public CharSequence getTitle() { - return mTitle; - } - - public CharSequence getTitleCondensed() { - return mTitleCondensed; - } - - public boolean hasSubMenu() { - return false; - } - - public boolean isCheckable() { - return (mFlags & CHECKABLE) != 0; - } - - public boolean isChecked() { - return (mFlags & CHECKED) != 0; - } - - public boolean isEnabled() { - return (mFlags & ENABLED) != 0; - } - - public boolean isVisible() { - return (mFlags & HIDDEN) == 0; - } - - public MenuItem setAlphabeticShortcut(char alphaChar) { - mShortcutAlphabeticChar = alphaChar; - return this; - } - - public MenuItem setCheckable(boolean checkable) { - mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0); - return this; - } - - public ActionMenuItem setExclusiveCheckable(boolean exclusive) { - mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0); - return this; - } - - public MenuItem setChecked(boolean checked) { - mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0); - return this; - } - - public MenuItem setEnabled(boolean enabled) { - mFlags = (mFlags & ~ENABLED) | (enabled ? ENABLED : 0); - return this; - } - - public MenuItem setIcon(Drawable icon) { - mIconDrawable = icon; - //UNUSED mIconResId = NO_ICON; - return this; - } - - public MenuItem setIcon(int iconRes) { - //UNUSED mIconResId = iconRes; - mIconDrawable = mContext.getResources().getDrawable(iconRes); - return this; - } - - public MenuItem setIntent(Intent intent) { - mIntent = intent; - return this; - } - - public MenuItem setNumericShortcut(char numericChar) { - mShortcutNumericChar = numericChar; - return this; - } - - public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { - mClickListener = menuItemClickListener; - return this; - } - - public MenuItem setShortcut(char numericChar, char alphaChar) { - mShortcutNumericChar = numericChar; - mShortcutAlphabeticChar = alphaChar; - return this; - } - - public MenuItem setTitle(CharSequence title) { - mTitle = title; - return this; - } - - public MenuItem setTitle(int title) { - mTitle = mContext.getResources().getString(title); - return this; - } - - public MenuItem setTitleCondensed(CharSequence title) { - mTitleCondensed = title; - return this; - } - - public MenuItem setVisible(boolean visible) { - mFlags = (mFlags & HIDDEN) | (visible ? 0 : HIDDEN); - return this; - } - - public boolean invoke() { - if (mClickListener != null && mClickListener.onMenuItemClick(this)) { - return true; - } - - if (mIntent != null) { - mContext.startActivity(mIntent); - return true; - } - - return false; - } - - public void setShowAsAction(int show) { - // Do nothing. ActionMenuItems always show as action buttons. - } - - public MenuItem setActionView(View actionView) { - throw new UnsupportedOperationException(); - } - - public View getActionView() { - return null; - } - - @Override - public MenuItem setActionView(int resId) { - throw new UnsupportedOperationException(); - } - - @Override - public ActionProvider getActionProvider() { - return null; - } - - @Override - public MenuItem setActionProvider(ActionProvider actionProvider) { - throw new UnsupportedOperationException(); - } - - @Override - public MenuItem setShowAsActionFlags(int actionEnum) { - setShowAsAction(actionEnum); - return this; - } - - @Override - public boolean expandActionView() { - return false; - } - - @Override - public boolean collapseActionView() { - return false; - } - - @Override - public boolean isActionViewExpanded() { - return false; - } - - @Override - public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { - // No need to save the listener; ActionMenuItem does not support collapsing items. - return this; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.java deleted file mode 100644 index dcb50f36..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import java.util.HashSet; -import java.util.Set; -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.text.TextUtils; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.MotionEvent; -import android.view.View; -import android.view.accessibility.AccessibilityEvent; -import android.widget.ImageButton; -import android.widget.LinearLayout; -import android.widget.Toast; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.view.View_HasStateListenerSupport; -import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener; -import com.actionbarsherlock.internal.widget.CapitalizingButton; - -import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; - -/** - * @hide - */ -public class ActionMenuItemView extends LinearLayout - implements MenuView.ItemView, View.OnClickListener, View.OnLongClickListener, - ActionMenuView.ActionMenuChildView, View_HasStateListenerSupport { - //UNUSED private static final String TAG = "ActionMenuItemView"; - - private MenuItemImpl mItemData; - private CharSequence mTitle; - private MenuBuilder.ItemInvoker mItemInvoker; - - private ImageButton mImageButton; - private CapitalizingButton mTextButton; - private boolean mAllowTextWithIcon; - private boolean mExpandedFormat; - private int mMinWidth; - - private final Set mListeners = new HashSet(); - - public ActionMenuItemView(Context context) { - this(context, null); - } - - public ActionMenuItemView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public ActionMenuItemView(Context context, AttributeSet attrs, int defStyle) { - //TODO super(context, attrs, defStyle); - super(context, attrs); - mAllowTextWithIcon = getResources_getBoolean(context, - R.bool.abs__config_allowActionMenuItemTextWithIcon); - TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SherlockActionMenuItemView, 0, 0); - mMinWidth = a.getDimensionPixelSize( - R.styleable.SherlockActionMenuItemView_android_minWidth, 0); - a.recycle(); - } - - @Override - public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { - mListeners.add(listener); - } - - @Override - public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { - mListeners.remove(listener); - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - for (View_OnAttachStateChangeListener listener : mListeners) { - listener.onViewAttachedToWindow(this); - } - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - for (View_OnAttachStateChangeListener listener : mListeners) { - listener.onViewDetachedFromWindow(this); - } - } - - @Override - public void onFinishInflate() { - - mImageButton = (ImageButton) findViewById(R.id.abs__imageButton); - mTextButton = (CapitalizingButton) findViewById(R.id.abs__textButton); - mImageButton.setOnClickListener(this); - mTextButton.setOnClickListener(this); - mImageButton.setOnLongClickListener(this); - setOnClickListener(this); - setOnLongClickListener(this); - } - - public MenuItemImpl getItemData() { - return mItemData; - } - - public void initialize(MenuItemImpl itemData, int menuType) { - mItemData = itemData; - - setIcon(itemData.getIcon()); - setTitle(itemData.getTitleForItemView(this)); // Title only takes effect if there is no icon - setId(itemData.getItemId()); - - setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE); - setEnabled(itemData.isEnabled()); - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - mImageButton.setEnabled(enabled); - mTextButton.setEnabled(enabled); - } - - public void onClick(View v) { - if (mItemInvoker != null) { - mItemInvoker.invokeItem(mItemData); - } - } - - public void setItemInvoker(MenuBuilder.ItemInvoker invoker) { - mItemInvoker = invoker; - } - - public boolean prefersCondensedTitle() { - return true; - } - - public void setCheckable(boolean checkable) { - // TODO Support checkable action items - } - - public void setChecked(boolean checked) { - // TODO Support checkable action items - } - - public void setExpandedFormat(boolean expandedFormat) { - if (mExpandedFormat != expandedFormat) { - mExpandedFormat = expandedFormat; - if (mItemData != null) { - mItemData.actionFormatChanged(); - } - } - } - - private void updateTextButtonVisibility() { - boolean visible = !TextUtils.isEmpty(mTextButton.getText()); - visible &= mImageButton.getDrawable() == null || - (mItemData.showsTextAsAction() && (mAllowTextWithIcon || mExpandedFormat)); - - mTextButton.setVisibility(visible ? VISIBLE : GONE); - } - - public void setIcon(Drawable icon) { - mImageButton.setImageDrawable(icon); - if (icon != null) { - mImageButton.setVisibility(VISIBLE); - } else { - mImageButton.setVisibility(GONE); - } - - updateTextButtonVisibility(); - } - - public boolean hasText() { - return mTextButton.getVisibility() != GONE; - } - - public void setShortcut(boolean showShortcut, char shortcutKey) { - // Action buttons don't show text for shortcut keys. - } - - public void setTitle(CharSequence title) { - mTitle = title; - - mTextButton.setTextCompat(mTitle); - - setContentDescription(mTitle); - updateTextButtonVisibility(); - } - - @Override - public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { - onPopulateAccessibilityEvent(event); - return true; - } - - @Override - public void onPopulateAccessibilityEvent(AccessibilityEvent event) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - super.onPopulateAccessibilityEvent(event); - } - final CharSequence cdesc = getContentDescription(); - if (!TextUtils.isEmpty(cdesc)) { - event.getText().add(cdesc); - } - } - - @Override - public boolean dispatchHoverEvent(MotionEvent event) { - // Don't allow children to hover; we want this to be treated as a single component. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - return onHoverEvent(event); - } - return false; - } - - public boolean showsIcon() { - return true; - } - - public boolean needsDividerBefore() { - return hasText() && mItemData.getIcon() == null; - } - - public boolean needsDividerAfter() { - return hasText(); - } - - @Override - public boolean onLongClick(View v) { - if (hasText()) { - // Don't show the cheat sheet for items that already show text. - return false; - } - - final int[] screenPos = new int[2]; - final Rect displayFrame = new Rect(); - getLocationOnScreen(screenPos); - getWindowVisibleDisplayFrame(displayFrame); - - final Context context = getContext(); - final int width = getWidth(); - final int height = getHeight(); - final int midy = screenPos[1] + height / 2; - final int screenWidth = context.getResources().getDisplayMetrics().widthPixels; - - Toast cheatSheet = Toast.makeText(context, mItemData.getTitle(), Toast.LENGTH_SHORT); - if (midy < displayFrame.height()) { - // Show along the top; follow action buttons - cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT, - screenWidth - screenPos[0] - width / 2, height); - } else { - // Show along the bottom center - cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height); - } - cheatSheet.show(); - return true; - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - final int widthMode = MeasureSpec.getMode(widthMeasureSpec); - final int specSize = MeasureSpec.getSize(widthMeasureSpec); - final int oldMeasuredWidth = getMeasuredWidth(); - final int targetWidth = widthMode == MeasureSpec.AT_MOST ? Math.min(specSize, mMinWidth) - : mMinWidth; - - if (widthMode != MeasureSpec.EXACTLY && mMinWidth > 0 && oldMeasuredWidth < targetWidth) { - // Remeasure at exactly the minimum width. - super.onMeasure(MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY), - heightMeasureSpec); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.java deleted file mode 100644 index 6f568c69..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.java +++ /dev/null @@ -1,721 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getInteger; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; -import android.content.Context; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.os.Build; -import android.os.Parcel; -import android.os.Parcelable; -import android.util.SparseBooleanArray; -import android.view.SoundEffectConstants; -import android.view.View; -import android.view.View.MeasureSpec; -import android.view.ViewConfiguration; -import android.view.ViewGroup; -import android.widget.ImageButton; -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.view.View_HasStateListenerSupport; -import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener; -import com.actionbarsherlock.internal.view.menu.ActionMenuView.ActionMenuChildView; -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.view.MenuItem; - -/** - * MenuPresenter for building action menus as seen in the action bar and action modes. - */ -public class ActionMenuPresenter extends BaseMenuPresenter - implements ActionProvider.SubUiVisibilityListener { - //UNUSED private static final String TAG = "ActionMenuPresenter"; - - private View mOverflowButton; - private boolean mReserveOverflow; - private boolean mReserveOverflowSet; - private int mWidthLimit; - private int mActionItemWidthLimit; - private int mMaxItems; - private boolean mMaxItemsSet; - private boolean mStrictWidthLimit; - private boolean mWidthLimitSet; - private boolean mExpandedActionViewsExclusive; - - private int mMinCellSize; - - // Group IDs that have been added as actions - used temporarily, allocated here for reuse. - private final SparseBooleanArray mActionButtonGroups = new SparseBooleanArray(); - - private View mScrapActionButtonView; - - private OverflowPopup mOverflowPopup; - private ActionButtonSubmenu mActionButtonPopup; - - private OpenOverflowRunnable mPostedOpenRunnable; - - final PopupPresenterCallback mPopupPresenterCallback = new PopupPresenterCallback(); - int mOpenSubMenuId; - - public ActionMenuPresenter(Context context) { - super(context, R.layout.abs__action_menu_layout, - R.layout.abs__action_menu_item_layout); - } - - @Override - public void initForMenu(Context context, MenuBuilder menu) { - super.initForMenu(context, menu); - - final Resources res = context.getResources(); - - if (!mReserveOverflowSet) { - mReserveOverflow = reserveOverflow(mContext); - } - - if (!mWidthLimitSet) { - mWidthLimit = res.getDisplayMetrics().widthPixels / 2; - } - - // Measure for initial configuration - if (!mMaxItemsSet) { - mMaxItems = getResources_getInteger(context, R.integer.abs__max_action_buttons); - } - - int width = mWidthLimit; - if (mReserveOverflow) { - if (mOverflowButton == null) { - mOverflowButton = new OverflowMenuButton(mSystemContext); - final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - mOverflowButton.measure(spec, spec); - } - width -= mOverflowButton.getMeasuredWidth(); - } else { - mOverflowButton = null; - } - - mActionItemWidthLimit = width; - - mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density); - - // Drop a scrap view as it may no longer reflect the proper context/config. - mScrapActionButtonView = null; - } - - public static boolean reserveOverflow(Context context) { - //Check for theme-forced overflow action item - TypedArray a = context.getTheme().obtainStyledAttributes(R.styleable.SherlockTheme); - boolean result = a.getBoolean(R.styleable.SherlockTheme_absForceOverflow, false); - a.recycle(); - if (result) { - return true; - } - - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB); - } else { - return !HasPermanentMenuKey.get(context); - } - } - - private static class HasPermanentMenuKey { - public static boolean get(Context context) { - return ViewConfiguration.get(context).hasPermanentMenuKey(); - } - } - - public void onConfigurationChanged(Configuration newConfig) { - if (!mMaxItemsSet) { - mMaxItems = getResources_getInteger(mContext, - R.integer.abs__max_action_buttons); - if (mMenu != null) { - mMenu.onItemsChanged(true); - } - } - } - - public void setWidthLimit(int width, boolean strict) { - mWidthLimit = width; - mStrictWidthLimit = strict; - mWidthLimitSet = true; - } - - public void setReserveOverflow(boolean reserveOverflow) { - mReserveOverflow = reserveOverflow; - mReserveOverflowSet = true; - } - - public void setItemLimit(int itemCount) { - mMaxItems = itemCount; - mMaxItemsSet = true; - } - - public void setExpandedActionViewsExclusive(boolean isExclusive) { - mExpandedActionViewsExclusive = isExclusive; - } - - @Override - public MenuView getMenuView(ViewGroup root) { - MenuView result = super.getMenuView(root); - ((ActionMenuView) result).setPresenter(this); - return result; - } - - @Override - public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) { - View actionView = item.getActionView(); - if (actionView == null || item.hasCollapsibleActionView()) { - if (!(convertView instanceof ActionMenuItemView)) { - convertView = null; - } - actionView = super.getItemView(item, convertView, parent); - } - actionView.setVisibility(item.isActionViewExpanded() ? View.GONE : View.VISIBLE); - - final ActionMenuView menuParent = (ActionMenuView) parent; - final ViewGroup.LayoutParams lp = actionView.getLayoutParams(); - if (!menuParent.checkLayoutParams(lp)) { - actionView.setLayoutParams(menuParent.generateLayoutParams(lp)); - } - return actionView; - } - - @Override - public void bindItemView(MenuItemImpl item, MenuView.ItemView itemView) { - itemView.initialize(item, 0); - - final ActionMenuView menuView = (ActionMenuView) mMenuView; - ActionMenuItemView actionItemView = (ActionMenuItemView) itemView; - actionItemView.setItemInvoker(menuView); - } - - @Override - public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) { - return item.isActionButton(); - } - - @Override - public void updateMenuView(boolean cleared) { - super.updateMenuView(cleared); - - if (mMenu != null) { - final ArrayList actionItems = mMenu.getActionItems(); - final int count = actionItems.size(); - for (int i = 0; i < count; i++) { - final ActionProvider provider = actionItems.get(i).getActionProvider(); - if (provider != null) { - provider.setSubUiVisibilityListener(this); - } - } - } - - final ArrayList nonActionItems = mMenu != null ? - mMenu.getNonActionItems() : null; - - boolean hasOverflow = false; - if (mReserveOverflow && nonActionItems != null) { - final int count = nonActionItems.size(); - if (count == 1) { - hasOverflow = !nonActionItems.get(0).isActionViewExpanded(); - } else { - hasOverflow = count > 0; - } - } - - if (hasOverflow) { - if (mOverflowButton == null) { - mOverflowButton = new OverflowMenuButton(mSystemContext); - } - ViewGroup parent = (ViewGroup) mOverflowButton.getParent(); - if (parent != mMenuView) { - if (parent != null) { - parent.removeView(mOverflowButton); - } - ActionMenuView menuView = (ActionMenuView) mMenuView; - menuView.addView(mOverflowButton, menuView.generateOverflowButtonLayoutParams()); - } - } else if (mOverflowButton != null && mOverflowButton.getParent() == mMenuView) { - ((ViewGroup) mMenuView).removeView(mOverflowButton); - } - - ((ActionMenuView) mMenuView).setOverflowReserved(mReserveOverflow); - } - - @Override - public boolean filterLeftoverView(ViewGroup parent, int childIndex) { - if (parent.getChildAt(childIndex) == mOverflowButton) return false; - return super.filterLeftoverView(parent, childIndex); - } - - public boolean onSubMenuSelected(SubMenuBuilder subMenu) { - if (!subMenu.hasVisibleItems()) return false; - - SubMenuBuilder topSubMenu = subMenu; - while (topSubMenu.getParentMenu() != mMenu) { - topSubMenu = (SubMenuBuilder) topSubMenu.getParentMenu(); - } - View anchor = findViewForItem(topSubMenu.getItem()); - if (anchor == null) { - if (mOverflowButton == null) return false; - anchor = mOverflowButton; - } - - mOpenSubMenuId = subMenu.getItem().getItemId(); - mActionButtonPopup = new ActionButtonSubmenu(mContext, subMenu); - mActionButtonPopup.setAnchorView(anchor); - mActionButtonPopup.show(); - super.onSubMenuSelected(subMenu); - return true; - } - - private View findViewForItem(MenuItem item) { - final ViewGroup parent = (ViewGroup) mMenuView; - if (parent == null) return null; - - final int count = parent.getChildCount(); - for (int i = 0; i < count; i++) { - final View child = parent.getChildAt(i); - if (child instanceof MenuView.ItemView && - ((MenuView.ItemView) child).getItemData() == item) { - return child; - } - } - return null; - } - - /** - * Display the overflow menu if one is present. - * @return true if the overflow menu was shown, false otherwise. - */ - public boolean showOverflowMenu() { - if (mReserveOverflow && !isOverflowMenuShowing() && mMenu != null && mMenuView != null && - mPostedOpenRunnable == null && !mMenu.getNonActionItems().isEmpty()) { - OverflowPopup popup = new OverflowPopup(mContext, mMenu, mOverflowButton, true); - mPostedOpenRunnable = new OpenOverflowRunnable(popup); - // Post this for later; we might still need a layout for the anchor to be right. - ((View) mMenuView).post(mPostedOpenRunnable); - - // ActionMenuPresenter uses null as a callback argument here - // to indicate overflow is opening. - super.onSubMenuSelected(null); - - return true; - } - return false; - } - - /** - * Hide the overflow menu if it is currently showing. - * - * @return true if the overflow menu was hidden, false otherwise. - */ - public boolean hideOverflowMenu() { - if (mPostedOpenRunnable != null && mMenuView != null) { - ((View) mMenuView).removeCallbacks(mPostedOpenRunnable); - mPostedOpenRunnable = null; - return true; - } - - MenuPopupHelper popup = mOverflowPopup; - if (popup != null) { - popup.dismiss(); - return true; - } - return false; - } - - /** - * Dismiss all popup menus - overflow and submenus. - * @return true if popups were dismissed, false otherwise. (This can be because none were open.) - */ - public boolean dismissPopupMenus() { - boolean result = hideOverflowMenu(); - result |= hideSubMenus(); - return result; - } - - /** - * Dismiss all submenu popups. - * - * @return true if popups were dismissed, false otherwise. (This can be because none were open.) - */ - public boolean hideSubMenus() { - if (mActionButtonPopup != null) { - mActionButtonPopup.dismiss(); - return true; - } - return false; - } - - /** - * @return true if the overflow menu is currently showing - */ - public boolean isOverflowMenuShowing() { - return mOverflowPopup != null && mOverflowPopup.isShowing(); - } - - /** - * @return true if space has been reserved in the action menu for an overflow item. - */ - public boolean isOverflowReserved() { - return mReserveOverflow; - } - - public boolean flagActionItems() { - final ArrayList visibleItems = mMenu.getVisibleItems(); - final int itemsSize = visibleItems.size(); - int maxActions = mMaxItems; - int widthLimit = mActionItemWidthLimit; - final int querySpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - final ViewGroup parent = (ViewGroup) mMenuView; - - int requiredItems = 0; - int requestedItems = 0; - int firstActionWidth = 0; - boolean hasOverflow = false; - for (int i = 0; i < itemsSize; i++) { - MenuItemImpl item = visibleItems.get(i); - if (item.requiresActionButton()) { - requiredItems++; - } else if (item.requestsActionButton()) { - requestedItems++; - } else { - hasOverflow = true; - } - if (mExpandedActionViewsExclusive && item.isActionViewExpanded()) { - // Overflow everything if we have an expanded action view and we're - // space constrained. - maxActions = 0; - } - } - - // Reserve a spot for the overflow item if needed. - if (mReserveOverflow && - (hasOverflow || requiredItems + requestedItems > maxActions)) { - maxActions--; - } - maxActions -= requiredItems; - - final SparseBooleanArray seenGroups = mActionButtonGroups; - seenGroups.clear(); - - int cellSize = 0; - int cellsRemaining = 0; - if (mStrictWidthLimit) { - cellsRemaining = widthLimit / mMinCellSize; - final int cellSizeRemaining = widthLimit % mMinCellSize; - cellSize = mMinCellSize + cellSizeRemaining / cellsRemaining; - } - - // Flag as many more requested items as will fit. - for (int i = 0; i < itemsSize; i++) { - MenuItemImpl item = visibleItems.get(i); - - if (item.requiresActionButton()) { - View v = getItemView(item, mScrapActionButtonView, parent); - if (mScrapActionButtonView == null) { - mScrapActionButtonView = v; - } - if (mStrictWidthLimit) { - cellsRemaining -= ActionMenuView.measureChildForCells(v, - cellSize, cellsRemaining, querySpec, 0); - } else { - v.measure(querySpec, querySpec); - } - final int measuredWidth = v.getMeasuredWidth(); - widthLimit -= measuredWidth; - if (firstActionWidth == 0) { - firstActionWidth = measuredWidth; - } - final int groupId = item.getGroupId(); - if (groupId != 0) { - seenGroups.put(groupId, true); - } - item.setIsActionButton(true); - } else if (item.requestsActionButton()) { - // Items in a group with other items that already have an action slot - // can break the max actions rule, but not the width limit. - final int groupId = item.getGroupId(); - final boolean inGroup = seenGroups.get(groupId); - boolean isAction = (maxActions > 0 || inGroup) && widthLimit > 0 && - (!mStrictWidthLimit || cellsRemaining > 0); - - if (isAction) { - View v = getItemView(item, mScrapActionButtonView, parent); - if (mScrapActionButtonView == null) { - mScrapActionButtonView = v; - } - if (mStrictWidthLimit) { - final int cells = ActionMenuView.measureChildForCells(v, - cellSize, cellsRemaining, querySpec, 0); - cellsRemaining -= cells; - if (cells == 0) { - isAction = false; - } - } else { - v.measure(querySpec, querySpec); - } - final int measuredWidth = v.getMeasuredWidth(); - widthLimit -= measuredWidth; - if (firstActionWidth == 0) { - firstActionWidth = measuredWidth; - } - - if (mStrictWidthLimit) { - isAction &= widthLimit >= 0; - } else { - // Did this push the entire first item past the limit? - isAction &= widthLimit + firstActionWidth > 0; - } - } - - if (isAction && groupId != 0) { - seenGroups.put(groupId, true); - } else if (inGroup) { - // We broke the width limit. Demote the whole group, they all overflow now. - seenGroups.put(groupId, false); - for (int j = 0; j < i; j++) { - MenuItemImpl areYouMyGroupie = visibleItems.get(j); - if (areYouMyGroupie.getGroupId() == groupId) { - // Give back the action slot - if (areYouMyGroupie.isActionButton()) maxActions++; - areYouMyGroupie.setIsActionButton(false); - } - } - } - - if (isAction) maxActions--; - - item.setIsActionButton(isAction); - } - } - return true; - } - - @Override - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - dismissPopupMenus(); - super.onCloseMenu(menu, allMenusAreClosing); - } - - @Override - public Parcelable onSaveInstanceState() { - SavedState state = new SavedState(); - state.openSubMenuId = mOpenSubMenuId; - return state; - } - - @Override - public void onRestoreInstanceState(Parcelable state) { - SavedState saved = (SavedState) state; - if (saved.openSubMenuId > 0) { - MenuItem item = mMenu.findItem(saved.openSubMenuId); - if (item != null) { - SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); - onSubMenuSelected(subMenu); - } - } - } - - @Override - public void onSubUiVisibilityChanged(boolean isVisible) { - if (isVisible) { - // Not a submenu, but treat it like one. - super.onSubMenuSelected(null); - } else { - mMenu.close(false); - } - } - - private static class SavedState implements Parcelable { - public int openSubMenuId; - - SavedState() { - } - - SavedState(Parcel in) { - openSubMenuId = in.readInt(); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(openSubMenuId); - } - - @SuppressWarnings("unused") - public static final Parcelable.Creator CREATOR - = new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; - } - - private class OverflowMenuButton extends ImageButton implements ActionMenuChildView, View_HasStateListenerSupport { - private final Set mListeners = new HashSet(); - - public OverflowMenuButton(Context context) { - super(context, null, R.attr.actionOverflowButtonStyle); - - setClickable(true); - setFocusable(true); - setVisibility(VISIBLE); - setEnabled(true); - } - - @Override - public boolean performClick() { - if (super.performClick()) { - return true; - } - - playSoundEffect(SoundEffectConstants.CLICK); - showOverflowMenu(); - return true; - } - - public boolean needsDividerBefore() { - return false; - } - - public boolean needsDividerAfter() { - return false; - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - for (View_OnAttachStateChangeListener listener : mListeners) { - listener.onViewAttachedToWindow(this); - } - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - for (View_OnAttachStateChangeListener listener : mListeners) { - listener.onViewDetachedFromWindow(this); - } - } - - @Override - public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { - mListeners.add(listener); - } - - @Override - public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { - mListeners.remove(listener); - } - } - - private class OverflowPopup extends MenuPopupHelper { - public OverflowPopup(Context context, MenuBuilder menu, View anchorView, - boolean overflowOnly) { - super(context, menu, anchorView, overflowOnly); - setCallback(mPopupPresenterCallback); - } - - @Override - public void onDismiss() { - super.onDismiss(); - mMenu.close(); - mOverflowPopup = null; - } - } - - private class ActionButtonSubmenu extends MenuPopupHelper { - //UNUSED private SubMenuBuilder mSubMenu; - - public ActionButtonSubmenu(Context context, SubMenuBuilder subMenu) { - super(context, subMenu); - //UNUSED mSubMenu = subMenu; - - MenuItemImpl item = (MenuItemImpl) subMenu.getItem(); - if (!item.isActionButton()) { - // Give a reasonable anchor to nested submenus. - setAnchorView(mOverflowButton == null ? (View) mMenuView : mOverflowButton); - } - - setCallback(mPopupPresenterCallback); - - boolean preserveIconSpacing = false; - final int count = subMenu.size(); - for (int i = 0; i < count; i++) { - MenuItem childItem = subMenu.getItem(i); - if (childItem.isVisible() && childItem.getIcon() != null) { - preserveIconSpacing = true; - break; - } - } - setForceShowIcon(preserveIconSpacing); - } - - @Override - public void onDismiss() { - super.onDismiss(); - mActionButtonPopup = null; - mOpenSubMenuId = 0; - } - } - - private class PopupPresenterCallback implements MenuPresenter.Callback { - - @Override - public boolean onOpenSubMenu(MenuBuilder subMenu) { - if (subMenu == null) return false; - - mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId(); - return false; - } - - @Override - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - if (menu instanceof SubMenuBuilder) { - ((SubMenuBuilder) menu).getRootMenu().close(false); - } - } - } - - private class OpenOverflowRunnable implements Runnable { - private OverflowPopup mPopup; - - public OpenOverflowRunnable(OverflowPopup popup) { - mPopup = popup; - } - - public void run() { - mMenu.changeMenuMode(); - final View menuView = (View) mMenuView; - if (menuView != null && menuView.getWindowToken() != null && mPopup.tryShow()) { - mOverflowPopup = mPopup; - } - mPostedOpenRunnable = null; - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuView.java deleted file mode 100644 index e090677a..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuView.java +++ /dev/null @@ -1,572 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.actionbarsherlock.internal.view.menu; - -import android.content.Context; -import android.content.res.Configuration; -import android.graphics.Canvas; -import android.os.Build; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.view.accessibility.AccessibilityEvent; -import android.widget.LinearLayout; -import com.actionbarsherlock.internal.widget.IcsLinearLayout; - -/** - * @hide - */ -public class ActionMenuView extends IcsLinearLayout implements MenuBuilder.ItemInvoker, MenuView { - //UNUSED private static final String TAG = "ActionMenuView"; - private static final boolean IS_FROYO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; - - static final int MIN_CELL_SIZE = 56; // dips - static final int GENERATED_ITEM_PADDING = 4; // dips - - private MenuBuilder mMenu; - - private boolean mReserveOverflow; - private ActionMenuPresenter mPresenter; - private boolean mFormatItems; - private int mFormatItemsWidth; - private int mMinCellSize; - private int mGeneratedItemPadding; - //UNUSED private int mMeasuredExtraWidth; - - private boolean mFirst = true; - - public ActionMenuView(Context context) { - this(context, null); - } - - public ActionMenuView(Context context, AttributeSet attrs) { - super(context, attrs); - setBaselineAligned(false); - final float density = context.getResources().getDisplayMetrics().density; - mMinCellSize = (int) (MIN_CELL_SIZE * density); - mGeneratedItemPadding = (int) (GENERATED_ITEM_PADDING * density); - } - - public void setPresenter(ActionMenuPresenter presenter) { - mPresenter = presenter; - } - - public boolean isExpandedFormat() { - return mFormatItems; - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - if (IS_FROYO) { - super.onConfigurationChanged(newConfig); - } - mPresenter.updateMenuView(false); - - if (mPresenter != null && mPresenter.isOverflowMenuShowing()) { - mPresenter.hideOverflowMenu(); - mPresenter.showOverflowMenu(); - } - } - - @Override - protected void onDraw(Canvas canvas) { - //Need to trigger a relayout since we may have been added extremely - //late in the initial rendering (e.g., when contained in a ViewPager). - //See: https://github.com/JakeWharton/ActionBarSherlock/issues/272 - if (!IS_FROYO && mFirst) { - mFirst = false; - requestLayout(); - return; - } - super.onDraw(canvas); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - // If we've been given an exact size to match, apply special formatting during layout. - final boolean wasFormatted = mFormatItems; - mFormatItems = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY; - - if (wasFormatted != mFormatItems) { - mFormatItemsWidth = 0; // Reset this when switching modes - } - - // Special formatting can change whether items can fit as action buttons. - // Kick the menu and update presenters when this changes. - final int widthSize = MeasureSpec.getMode(widthMeasureSpec); - if (mFormatItems && mMenu != null && widthSize != mFormatItemsWidth) { - mFormatItemsWidth = widthSize; - mMenu.onItemsChanged(true); - } - - if (mFormatItems) { - onMeasureExactFormat(widthMeasureSpec, heightMeasureSpec); - } else { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - } - - private void onMeasureExactFormat(int widthMeasureSpec, int heightMeasureSpec) { - // We already know the width mode is EXACTLY if we're here. - final int heightMode = MeasureSpec.getMode(heightMeasureSpec); - int widthSize = MeasureSpec.getSize(widthMeasureSpec); - int heightSize = MeasureSpec.getSize(heightMeasureSpec); - - final int widthPadding = getPaddingLeft() + getPaddingRight(); - final int heightPadding = getPaddingTop() + getPaddingBottom(); - - widthSize -= widthPadding; - - // Divide the view into cells. - final int cellCount = widthSize / mMinCellSize; - final int cellSizeRemaining = widthSize % mMinCellSize; - - if (cellCount == 0) { - // Give up, nothing fits. - setMeasuredDimension(widthSize, 0); - return; - } - - final int cellSize = mMinCellSize + cellSizeRemaining / cellCount; - - int cellsRemaining = cellCount; - int maxChildHeight = 0; - int maxCellsUsed = 0; - int expandableItemCount = 0; - int visibleItemCount = 0; - boolean hasOverflow = false; - - // This is used as a bitfield to locate the smallest items present. Assumes childCount < 64. - long smallestItemsAt = 0; - - final int childCount = getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = getChildAt(i); - if (child.getVisibility() == GONE) continue; - - final boolean isGeneratedItem = child instanceof ActionMenuItemView; - visibleItemCount++; - - if (isGeneratedItem) { - // Reset padding for generated menu item views; it may change below - // and views are recycled. - child.setPadding(mGeneratedItemPadding, 0, mGeneratedItemPadding, 0); - } - - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - lp.expanded = false; - lp.extraPixels = 0; - lp.cellsUsed = 0; - lp.expandable = false; - lp.leftMargin = 0; - lp.rightMargin = 0; - lp.preventEdgeOffset = isGeneratedItem && ((ActionMenuItemView) child).hasText(); - - // Overflow always gets 1 cell. No more, no less. - final int cellsAvailable = lp.isOverflowButton ? 1 : cellsRemaining; - - final int cellsUsed = measureChildForCells(child, cellSize, cellsAvailable, - heightMeasureSpec, heightPadding); - - maxCellsUsed = Math.max(maxCellsUsed, cellsUsed); - if (lp.expandable) expandableItemCount++; - if (lp.isOverflowButton) hasOverflow = true; - - cellsRemaining -= cellsUsed; - maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight()); - if (cellsUsed == 1) smallestItemsAt |= (1 << i); - } - - // When we have overflow and a single expanded (text) item, we want to try centering it - // visually in the available space even though overflow consumes some of it. - final boolean centerSingleExpandedItem = hasOverflow && visibleItemCount == 2; - - // Divide space for remaining cells if we have items that can expand. - // Try distributing whole leftover cells to smaller items first. - - boolean needsExpansion = false; - while (expandableItemCount > 0 && cellsRemaining > 0) { - int minCells = Integer.MAX_VALUE; - long minCellsAt = 0; // Bit locations are indices of relevant child views - int minCellsItemCount = 0; - for (int i = 0; i < childCount; i++) { - final View child = getChildAt(i); - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - - // Don't try to expand items that shouldn't. - if (!lp.expandable) continue; - - // Mark indices of children that can receive an extra cell. - if (lp.cellsUsed < minCells) { - minCells = lp.cellsUsed; - minCellsAt = 1 << i; - minCellsItemCount = 1; - } else if (lp.cellsUsed == minCells) { - minCellsAt |= 1 << i; - minCellsItemCount++; - } - } - - // Items that get expanded will always be in the set of smallest items when we're done. - smallestItemsAt |= minCellsAt; - - if (minCellsItemCount > cellsRemaining) break; // Couldn't expand anything evenly. Stop. - - // We have enough cells, all minimum size items will be incremented. - minCells++; - - for (int i = 0; i < childCount; i++) { - final View child = getChildAt(i); - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - if ((minCellsAt & (1 << i)) == 0) { - // If this item is already at our small item count, mark it for later. - if (lp.cellsUsed == minCells) smallestItemsAt |= 1 << i; - continue; - } - - if (centerSingleExpandedItem && lp.preventEdgeOffset && cellsRemaining == 1) { - // Add padding to this item such that it centers. - child.setPadding(mGeneratedItemPadding + cellSize, 0, mGeneratedItemPadding, 0); - } - lp.cellsUsed++; - lp.expanded = true; - cellsRemaining--; - } - - needsExpansion = true; - } - - // Divide any space left that wouldn't divide along cell boundaries - // evenly among the smallest items - - final boolean singleItem = !hasOverflow && visibleItemCount == 1; - if (cellsRemaining > 0 && smallestItemsAt != 0 && - (cellsRemaining < visibleItemCount - 1 || singleItem || maxCellsUsed > 1)) { - float expandCount = Long.bitCount(smallestItemsAt); - - if (!singleItem) { - // The items at the far edges may only expand by half in order to pin to either side. - if ((smallestItemsAt & 1) != 0) { - LayoutParams lp = (LayoutParams) getChildAt(0).getLayoutParams(); - if (!lp.preventEdgeOffset) expandCount -= 0.5f; - } - if ((smallestItemsAt & (1 << (childCount - 1))) != 0) { - LayoutParams lp = ((LayoutParams) getChildAt(childCount - 1).getLayoutParams()); - if (!lp.preventEdgeOffset) expandCount -= 0.5f; - } - } - - final int extraPixels = expandCount > 0 ? - (int) (cellsRemaining * cellSize / expandCount) : 0; - - for (int i = 0; i < childCount; i++) { - if ((smallestItemsAt & (1 << i)) == 0) continue; - - final View child = getChildAt(i); - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - if (child instanceof ActionMenuItemView) { - // If this is one of our views, expand and measure at the larger size. - lp.extraPixels = extraPixels; - lp.expanded = true; - if (i == 0 && !lp.preventEdgeOffset) { - // First item gets part of its new padding pushed out of sight. - // The last item will get this implicitly from layout. - lp.leftMargin = -extraPixels / 2; - } - needsExpansion = true; - } else if (lp.isOverflowButton) { - lp.extraPixels = extraPixels; - lp.expanded = true; - lp.rightMargin = -extraPixels / 2; - needsExpansion = true; - } else { - // If we don't know what it is, give it some margins instead - // and let it center within its space. We still want to pin - // against the edges. - if (i != 0) { - lp.leftMargin = extraPixels / 2; - } - if (i != childCount - 1) { - lp.rightMargin = extraPixels / 2; - } - } - } - - cellsRemaining = 0; - } - - // Remeasure any items that have had extra space allocated to them. - if (needsExpansion) { - int heightSpec = MeasureSpec.makeMeasureSpec(heightSize - heightPadding, heightMode); - for (int i = 0; i < childCount; i++) { - final View child = getChildAt(i); - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - - if (!lp.expanded) continue; - - final int width = lp.cellsUsed * cellSize + lp.extraPixels; - child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightSpec); - } - } - - if (heightMode != MeasureSpec.EXACTLY) { - heightSize = maxChildHeight; - } - - setMeasuredDimension(widthSize, heightSize); - //UNUSED mMeasuredExtraWidth = cellsRemaining * cellSize; - } - - /** - * Measure a child view to fit within cell-based formatting. The child's width - * will be measured to a whole multiple of cellSize. - * - *

Sets the expandable and cellsUsed fields of LayoutParams. - * - * @param child Child to measure - * @param cellSize Size of one cell - * @param cellsRemaining Number of cells remaining that this view can expand to fill - * @param parentHeightMeasureSpec MeasureSpec used by the parent view - * @param parentHeightPadding Padding present in the parent view - * @return Number of cells this child was measured to occupy - */ - static int measureChildForCells(View child, int cellSize, int cellsRemaining, - int parentHeightMeasureSpec, int parentHeightPadding) { - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - - final int childHeightSize = MeasureSpec.getSize(parentHeightMeasureSpec) - - parentHeightPadding; - final int childHeightMode = MeasureSpec.getMode(parentHeightMeasureSpec); - final int childHeightSpec = MeasureSpec.makeMeasureSpec(childHeightSize, childHeightMode); - - int cellsUsed = 0; - if (cellsRemaining > 0) { - final int childWidthSpec = MeasureSpec.makeMeasureSpec( - cellSize * cellsRemaining, MeasureSpec.AT_MOST); - child.measure(childWidthSpec, childHeightSpec); - - final int measuredWidth = child.getMeasuredWidth(); - cellsUsed = measuredWidth / cellSize; - if (measuredWidth % cellSize != 0) cellsUsed++; - } - - final ActionMenuItemView itemView = child instanceof ActionMenuItemView ? - (ActionMenuItemView) child : null; - final boolean expandable = !lp.isOverflowButton && itemView != null && itemView.hasText(); - lp.expandable = expandable; - - lp.cellsUsed = cellsUsed; - final int targetWidth = cellsUsed * cellSize; - child.measure(MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY), - childHeightSpec); - return cellsUsed; - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - if (!mFormatItems) { - super.onLayout(changed, left, top, right, bottom); - return; - } - - final int childCount = getChildCount(); - final int midVertical = (top + bottom) / 2; - final int dividerWidth = 0;//getDividerWidth(); - int overflowWidth = 0; - //UNUSED int nonOverflowWidth = 0; - int nonOverflowCount = 0; - int widthRemaining = right - left - getPaddingRight() - getPaddingLeft(); - boolean hasOverflow = false; - for (int i = 0; i < childCount; i++) { - final View v = getChildAt(i); - if (v.getVisibility() == GONE) { - continue; - } - - LayoutParams p = (LayoutParams) v.getLayoutParams(); - if (p.isOverflowButton) { - overflowWidth = v.getMeasuredWidth(); - if (hasDividerBeforeChildAt(i)) { - overflowWidth += dividerWidth; - } - - int height = v.getMeasuredHeight(); - int r = getWidth() - getPaddingRight() - p.rightMargin; - int l = r - overflowWidth; - int t = midVertical - (height / 2); - int b = t + height; - v.layout(l, t, r, b); - - widthRemaining -= overflowWidth; - hasOverflow = true; - } else { - final int size = v.getMeasuredWidth() + p.leftMargin + p.rightMargin; - //UNUSED nonOverflowWidth += size; - widthRemaining -= size; - //if (hasDividerBeforeChildAt(i)) { - //UNUSED nonOverflowWidth += dividerWidth; - //} - nonOverflowCount++; - } - } - - if (childCount == 1 && !hasOverflow) { - // Center a single child - final View v = getChildAt(0); - final int width = v.getMeasuredWidth(); - final int height = v.getMeasuredHeight(); - final int midHorizontal = (right - left) / 2; - final int l = midHorizontal - width / 2; - final int t = midVertical - height / 2; - v.layout(l, t, l + width, t + height); - return; - } - - final int spacerCount = nonOverflowCount - (hasOverflow ? 0 : 1); - final int spacerSize = Math.max(0, spacerCount > 0 ? widthRemaining / spacerCount : 0); - - int startLeft = getPaddingLeft(); - for (int i = 0; i < childCount; i++) { - final View v = getChildAt(i); - final LayoutParams lp = (LayoutParams) v.getLayoutParams(); - if (v.getVisibility() == GONE || lp.isOverflowButton) { - continue; - } - - startLeft += lp.leftMargin; - int width = v.getMeasuredWidth(); - int height = v.getMeasuredHeight(); - int t = midVertical - height / 2; - v.layout(startLeft, t, startLeft + width, t + height); - startLeft += width + lp.rightMargin + spacerSize; - } - } - - @Override - public void onDetachedFromWindow() { - super.onDetachedFromWindow(); - mPresenter.dismissPopupMenus(); - } - - public boolean isOverflowReserved() { - return mReserveOverflow; - } - - public void setOverflowReserved(boolean reserveOverflow) { - mReserveOverflow = reserveOverflow; - } - - @Override - protected LayoutParams generateDefaultLayoutParams() { - LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.WRAP_CONTENT); - params.gravity = Gravity.CENTER_VERTICAL; - return params; - } - - @Override - public LayoutParams generateLayoutParams(AttributeSet attrs) { - return new LayoutParams(getContext(), attrs); - } - - @Override - protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { - if (p instanceof LayoutParams) { - LayoutParams result = new LayoutParams((LayoutParams) p); - if (result.gravity <= Gravity.NO_GRAVITY) { - result.gravity = Gravity.CENTER_VERTICAL; - } - return result; - } - return generateDefaultLayoutParams(); - } - - @Override - protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { - return p != null && p instanceof LayoutParams; - } - - public LayoutParams generateOverflowButtonLayoutParams() { - LayoutParams result = generateDefaultLayoutParams(); - result.isOverflowButton = true; - return result; - } - - public boolean invokeItem(MenuItemImpl item) { - return mMenu.performItemAction(item, 0); - } - - public int getWindowAnimations() { - return 0; - } - - public void initialize(MenuBuilder menu) { - mMenu = menu; - } - - //@Override - protected boolean hasDividerBeforeChildAt(int childIndex) { - final View childBefore = getChildAt(childIndex - 1); - final View child = getChildAt(childIndex); - boolean result = false; - if (childIndex < getChildCount() && childBefore instanceof ActionMenuChildView) { - result |= ((ActionMenuChildView) childBefore).needsDividerAfter(); - } - if (childIndex > 0 && child instanceof ActionMenuChildView) { - result |= ((ActionMenuChildView) child).needsDividerBefore(); - } - return result; - } - - public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { - return false; - } - - public interface ActionMenuChildView { - public boolean needsDividerBefore(); - public boolean needsDividerAfter(); - } - - public static class LayoutParams extends LinearLayout.LayoutParams { - public boolean isOverflowButton; - public int cellsUsed; - public int extraPixels; - public boolean expandable; - public boolean preventEdgeOffset; - - public boolean expanded; - - public LayoutParams(Context c, AttributeSet attrs) { - super(c, attrs); - } - - public LayoutParams(LayoutParams other) { - super((LinearLayout.LayoutParams) other); - isOverflowButton = other.isOverflowButton; - } - - public LayoutParams(int width, int height) { - super(width, height); - isOverflowButton = false; - } - - public LayoutParams(int width, int height, boolean isOverflowButton) { - super(width, height); - this.isOverflowButton = isOverflowButton; - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.java deleted file mode 100644 index 6da26f2a..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import java.util.ArrayList; -import android.content.Context; -import android.os.Build; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -/** - * Base class for MenuPresenters that have a consistent container view and item - * views. Behaves similarly to an AdapterView in that existing item views will - * be reused if possible when items change. - */ -public abstract class BaseMenuPresenter implements MenuPresenter { - private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; - - protected Context mSystemContext; - protected Context mContext; - protected MenuBuilder mMenu; - protected LayoutInflater mSystemInflater; - protected LayoutInflater mInflater; - private Callback mCallback; - - private int mMenuLayoutRes; - private int mItemLayoutRes; - - protected MenuView mMenuView; - - private int mId; - - /** - * Construct a new BaseMenuPresenter. - * - * @param context Context for generating system-supplied views - * @param menuLayoutRes Layout resource ID for the menu container view - * @param itemLayoutRes Layout resource ID for a single item view - */ - public BaseMenuPresenter(Context context, int menuLayoutRes, int itemLayoutRes) { - mSystemContext = context; - mSystemInflater = LayoutInflater.from(context); - mMenuLayoutRes = menuLayoutRes; - mItemLayoutRes = itemLayoutRes; - } - - @Override - public void initForMenu(Context context, MenuBuilder menu) { - mContext = context; - mInflater = LayoutInflater.from(mContext); - mMenu = menu; - } - - @Override - public MenuView getMenuView(ViewGroup root) { - if (mMenuView == null) { - mMenuView = (MenuView) mSystemInflater.inflate(mMenuLayoutRes, root, false); - mMenuView.initialize(mMenu); - updateMenuView(true); - } - - return mMenuView; - } - - /** - * Reuses item views when it can - */ - public void updateMenuView(boolean cleared) { - final ViewGroup parent = (ViewGroup) mMenuView; - if (parent == null) return; - - int childIndex = 0; - if (mMenu != null) { - mMenu.flagActionItems(); - ArrayList visibleItems = mMenu.getVisibleItems(); - final int itemCount = visibleItems.size(); - for (int i = 0; i < itemCount; i++) { - MenuItemImpl item = visibleItems.get(i); - if (shouldIncludeItem(childIndex, item)) { - final View convertView = parent.getChildAt(childIndex); - final MenuItemImpl oldItem = convertView instanceof MenuView.ItemView ? - ((MenuView.ItemView) convertView).getItemData() : null; - final View itemView = getItemView(item, convertView, parent); - if (item != oldItem) { - // Don't let old states linger with new data. - itemView.setPressed(false); - if (IS_HONEYCOMB) itemView.jumpDrawablesToCurrentState(); - } - if (itemView != convertView) { - addItemView(itemView, childIndex); - } - childIndex++; - } - } - } - - // Remove leftover views. - while (childIndex < parent.getChildCount()) { - if (!filterLeftoverView(parent, childIndex)) { - childIndex++; - } - } - } - - /** - * Add an item view at the given index. - * - * @param itemView View to add - * @param childIndex Index within the parent to insert at - */ - protected void addItemView(View itemView, int childIndex) { - final ViewGroup currentParent = (ViewGroup) itemView.getParent(); - if (currentParent != null) { - currentParent.removeView(itemView); - } - ((ViewGroup) mMenuView).addView(itemView, childIndex); - } - - /** - * Filter the child view at index and remove it if appropriate. - * @param parent Parent to filter from - * @param childIndex Index to filter - * @return true if the child view at index was removed - */ - protected boolean filterLeftoverView(ViewGroup parent, int childIndex) { - parent.removeViewAt(childIndex); - return true; - } - - public void setCallback(Callback cb) { - mCallback = cb; - } - - /** - * Create a new item view that can be re-bound to other item data later. - * - * @return The new item view - */ - public MenuView.ItemView createItemView(ViewGroup parent) { - return (MenuView.ItemView) mSystemInflater.inflate(mItemLayoutRes, parent, false); - } - - /** - * Prepare an item view for use. See AdapterView for the basic idea at work here. - * This may require creating a new item view, but well-behaved implementations will - * re-use the view passed as convertView if present. The returned view will be populated - * with data from the item parameter. - * - * @param item Item to present - * @param convertView Existing view to reuse - * @param parent Intended parent view - use for inflation. - * @return View that presents the requested menu item - */ - public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) { - MenuView.ItemView itemView; - if (convertView instanceof MenuView.ItemView) { - itemView = (MenuView.ItemView) convertView; - } else { - itemView = createItemView(parent); - } - bindItemView(item, itemView); - return (View) itemView; - } - - /** - * Bind item data to an existing item view. - * - * @param item Item to bind - * @param itemView View to populate with item data - */ - public abstract void bindItemView(MenuItemImpl item, MenuView.ItemView itemView); - - /** - * Filter item by child index and item data. - * - * @param childIndex Indended presentation index of this item - * @param item Item to present - * @return true if this item should be included in this menu presentation; false otherwise - */ - public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) { - return true; - } - - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - if (mCallback != null) { - mCallback.onCloseMenu(menu, allMenusAreClosing); - } - } - - public boolean onSubMenuSelected(SubMenuBuilder menu) { - if (mCallback != null) { - return mCallback.onOpenSubMenu(menu); - } - return false; - } - - public boolean flagActionItems() { - return false; - } - - public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { - return false; - } - - public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { - return false; - } - - public int getId() { - return mId; - } - - public void setId(int id) { - mId = id; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ListMenuItemView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ListMenuItemView.java deleted file mode 100644 index ac25c373..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ListMenuItemView.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import com.actionbarsherlock.R; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.RadioButton; -import android.widget.TextView; - -/** - * The item view for each item in the ListView-based MenuViews. - */ -public class ListMenuItemView extends LinearLayout implements MenuView.ItemView { - private MenuItemImpl mItemData; - - private ImageView mIconView; - private RadioButton mRadioButton; - private TextView mTitleView; - private CheckBox mCheckBox; - private TextView mShortcutView; - - private Drawable mBackground; - private int mTextAppearance; - private Context mTextAppearanceContext; - private boolean mPreserveIconSpacing; - - //UNUSED private int mMenuType; - - private LayoutInflater mInflater; - - private boolean mForceShowIcon; - - final Context mContext; - - public ListMenuItemView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs); - mContext = context; - - TypedArray a = - context.obtainStyledAttributes( - attrs, R.styleable.SherlockMenuView, defStyle, 0); - - mBackground = a.getDrawable(R.styleable.SherlockMenuView_itemBackground); - mTextAppearance = a.getResourceId(R.styleable. - SherlockMenuView_itemTextAppearance, -1); - mPreserveIconSpacing = a.getBoolean( - R.styleable.SherlockMenuView_preserveIconSpacing, false); - mTextAppearanceContext = context; - - a.recycle(); - } - - public ListMenuItemView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - - setBackgroundDrawable(mBackground); - - mTitleView = (TextView) findViewById(R.id.abs__title); - if (mTextAppearance != -1) { - mTitleView.setTextAppearance(mTextAppearanceContext, - mTextAppearance); - } - - mShortcutView = (TextView) findViewById(R.id.abs__shortcut); - } - - public void initialize(MenuItemImpl itemData, int menuType) { - mItemData = itemData; - //UNUSED mMenuType = menuType; - - setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE); - - setTitle(itemData.getTitleForItemView(this)); - setCheckable(itemData.isCheckable()); - setShortcut(itemData.shouldShowShortcut(), itemData.getShortcut()); - setIcon(itemData.getIcon()); - setEnabled(itemData.isEnabled()); - } - - public void setForceShowIcon(boolean forceShow) { - mPreserveIconSpacing = mForceShowIcon = forceShow; - } - - public void setTitle(CharSequence title) { - if (title != null) { - mTitleView.setText(title); - - if (mTitleView.getVisibility() != VISIBLE) mTitleView.setVisibility(VISIBLE); - } else { - if (mTitleView.getVisibility() != GONE) mTitleView.setVisibility(GONE); - } - } - - public MenuItemImpl getItemData() { - return mItemData; - } - - public void setCheckable(boolean checkable) { - - if (!checkable && mRadioButton == null && mCheckBox == null) { - return; - } - - if (mRadioButton == null) { - insertRadioButton(); - } - if (mCheckBox == null) { - insertCheckBox(); - } - - // Depending on whether its exclusive check or not, the checkbox or - // radio button will be the one in use (and the other will be otherCompoundButton) - final CompoundButton compoundButton; - final CompoundButton otherCompoundButton; - - if (mItemData.isExclusiveCheckable()) { - compoundButton = mRadioButton; - otherCompoundButton = mCheckBox; - } else { - compoundButton = mCheckBox; - otherCompoundButton = mRadioButton; - } - - if (checkable) { - compoundButton.setChecked(mItemData.isChecked()); - - final int newVisibility = checkable ? VISIBLE : GONE; - if (compoundButton.getVisibility() != newVisibility) { - compoundButton.setVisibility(newVisibility); - } - - // Make sure the other compound button isn't visible - if (otherCompoundButton.getVisibility() != GONE) { - otherCompoundButton.setVisibility(GONE); - } - } else { - mCheckBox.setVisibility(GONE); - mRadioButton.setVisibility(GONE); - } - } - - public void setChecked(boolean checked) { - CompoundButton compoundButton; - - if (mItemData.isExclusiveCheckable()) { - if (mRadioButton == null) { - insertRadioButton(); - } - compoundButton = mRadioButton; - } else { - if (mCheckBox == null) { - insertCheckBox(); - } - compoundButton = mCheckBox; - } - - compoundButton.setChecked(checked); - } - - public void setShortcut(boolean showShortcut, char shortcutKey) { - final int newVisibility = (showShortcut && mItemData.shouldShowShortcut()) - ? VISIBLE : GONE; - - if (newVisibility == VISIBLE) { - mShortcutView.setText(mItemData.getShortcutLabel()); - } - - if (mShortcutView.getVisibility() != newVisibility) { - mShortcutView.setVisibility(newVisibility); - } - } - - public void setIcon(Drawable icon) { - final boolean showIcon = mItemData.shouldShowIcon() || mForceShowIcon; - if (!showIcon && !mPreserveIconSpacing) { - return; - } - - if (mIconView == null && icon == null && !mPreserveIconSpacing) { - return; - } - - if (mIconView == null) { - insertIconView(); - } - - if (icon != null || mPreserveIconSpacing) { - mIconView.setImageDrawable(showIcon ? icon : null); - - if (mIconView.getVisibility() != VISIBLE) { - mIconView.setVisibility(VISIBLE); - } - } else { - mIconView.setVisibility(GONE); - } - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - if (mIconView != null && mPreserveIconSpacing) { - // Enforce minimum icon spacing - ViewGroup.LayoutParams lp = getLayoutParams(); - LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); - if (lp.height > 0 && iconLp.width <= 0) { - iconLp.width = lp.height; - } - } - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - - private void insertIconView() { - LayoutInflater inflater = getInflater(); - mIconView = (ImageView) inflater.inflate(R.layout.abs__list_menu_item_icon, - this, false); - addView(mIconView, 0); - } - - private void insertRadioButton() { - LayoutInflater inflater = getInflater(); - mRadioButton = - (RadioButton) inflater.inflate(R.layout.abs__list_menu_item_radio, - this, false); - addView(mRadioButton); - } - - private void insertCheckBox() { - LayoutInflater inflater = getInflater(); - mCheckBox = - (CheckBox) inflater.inflate(R.layout.abs__list_menu_item_checkbox, - this, false); - addView(mCheckBox); - } - - public boolean prefersCondensedTitle() { - return false; - } - - public boolean showsIcon() { - return mForceShowIcon; - } - - private LayoutInflater getInflater() { - if (mInflater == null) { - mInflater = LayoutInflater.from(mContext); - } - return mInflater; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuBuilder.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuBuilder.java deleted file mode 100644 index 179b8f03..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuBuilder.java +++ /dev/null @@ -1,1335 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.os.Parcelable; -import android.util.SparseArray; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.KeyCharacterMap; -import android.view.KeyEvent; -import android.view.View; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -/** - * Implementation of the {@link android.view.Menu} interface for creating a - * standard menu UI. - */ -public class MenuBuilder implements Menu { - //UNUSED private static final String TAG = "MenuBuilder"; - - private static final String PRESENTER_KEY = "android:menu:presenters"; - private static final String ACTION_VIEW_STATES_KEY = "android:menu:actionviewstates"; - private static final String EXPANDED_ACTION_VIEW_ID = "android:menu:expandedactionview"; - - private static final int[] sCategoryToOrder = new int[] { - 1, /* No category */ - 4, /* CONTAINER */ - 5, /* SYSTEM */ - 3, /* SECONDARY */ - 2, /* ALTERNATIVE */ - 0, /* SELECTED_ALTERNATIVE */ - }; - - private final Context mContext; - private final Resources mResources; - - /** - * Whether the shortcuts should be qwerty-accessible. Use isQwertyMode() - * instead of accessing this directly. - */ - private boolean mQwertyMode; - - /** - * Whether the shortcuts should be visible on menus. Use isShortcutsVisible() - * instead of accessing this directly. - */ - private boolean mShortcutsVisible; - - /** - * Callback that will receive the various menu-related events generated by - * this class. Use getCallback to get a reference to the callback. - */ - private Callback mCallback; - - /** Contains all of the items for this menu */ - private ArrayList mItems; - - /** Contains only the items that are currently visible. This will be created/refreshed from - * {@link #getVisibleItems()} */ - private ArrayList mVisibleItems; - /** - * Whether or not the items (or any one item's shown state) has changed since it was last - * fetched from {@link #getVisibleItems()} - */ - private boolean mIsVisibleItemsStale; - - /** - * Contains only the items that should appear in the Action Bar, if present. - */ - private ArrayList mActionItems; - /** - * Contains items that should NOT appear in the Action Bar, if present. - */ - private ArrayList mNonActionItems; - - /** - * Whether or not the items (or any one item's action state) has changed since it was - * last fetched. - */ - private boolean mIsActionItemsStale; - - /** - * Default value for how added items should show in the action list. - */ - private int mDefaultShowAsAction = MenuItem.SHOW_AS_ACTION_NEVER; - - /** - * Current use case is Context Menus: As Views populate the context menu, each one has - * extra information that should be passed along. This is the current menu info that - * should be set on all items added to this menu. - */ - private ContextMenuInfo mCurrentMenuInfo; - - /** Header title for menu types that have a header (context and submenus) */ - CharSequence mHeaderTitle; - /** Header icon for menu types that have a header and support icons (context) */ - Drawable mHeaderIcon; - /** Header custom view for menu types that have a header and support custom views (context) */ - View mHeaderView; - - /** - * Contains the state of the View hierarchy for all menu views when the menu - * was frozen. - */ - //UNUSED private SparseArray mFrozenViewStates; - - /** - * Prevents onItemsChanged from doing its junk, useful for batching commands - * that may individually call onItemsChanged. - */ - private boolean mPreventDispatchingItemsChanged = false; - private boolean mItemsChangedWhileDispatchPrevented = false; - - private boolean mOptionalIconsVisible = false; - - private boolean mIsClosing = false; - - private ArrayList mTempShortcutItemList = new ArrayList(); - - private CopyOnWriteArrayList> mPresenters = - new CopyOnWriteArrayList>(); - - /** - * Currently expanded menu item; must be collapsed when we clear. - */ - private MenuItemImpl mExpandedItem; - - /** - * Called by menu to notify of close and selection changes. - */ - public interface Callback { - /** - * Called when a menu item is selected. - * @param menu The menu that is the parent of the item - * @param item The menu item that is selected - * @return whether the menu item selection was handled - */ - public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item); - - /** - * Called when the mode of the menu changes (for example, from icon to expanded). - * - * @param menu the menu that has changed modes - */ - public void onMenuModeChange(MenuBuilder menu); - } - - /** - * Called by menu items to execute their associated action - */ - public interface ItemInvoker { - public boolean invokeItem(MenuItemImpl item); - } - - public MenuBuilder(Context context) { - mContext = context; - mResources = context.getResources(); - - mItems = new ArrayList(); - - mVisibleItems = new ArrayList(); - mIsVisibleItemsStale = true; - - mActionItems = new ArrayList(); - mNonActionItems = new ArrayList(); - mIsActionItemsStale = true; - - setShortcutsVisibleInner(true); - } - - public MenuBuilder setDefaultShowAsAction(int defaultShowAsAction) { - mDefaultShowAsAction = defaultShowAsAction; - return this; - } - - /** - * Add a presenter to this menu. This will only hold a WeakReference; - * you do not need to explicitly remove a presenter, but you can using - * {@link #removeMenuPresenter(MenuPresenter)}. - * - * @param presenter The presenter to add - */ - public void addMenuPresenter(MenuPresenter presenter) { - mPresenters.add(new WeakReference(presenter)); - presenter.initForMenu(mContext, this); - mIsActionItemsStale = true; - } - - /** - * Remove a presenter from this menu. That presenter will no longer - * receive notifications of updates to this menu's data. - * - * @param presenter The presenter to remove - */ - public void removeMenuPresenter(MenuPresenter presenter) { - for (WeakReference ref : mPresenters) { - final MenuPresenter item = ref.get(); - if (item == null || item == presenter) { - mPresenters.remove(ref); - } - } - } - - private void dispatchPresenterUpdate(boolean cleared) { - if (mPresenters.isEmpty()) return; - - stopDispatchingItemsChanged(); - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else { - presenter.updateMenuView(cleared); - } - } - startDispatchingItemsChanged(); - } - - private boolean dispatchSubMenuSelected(SubMenuBuilder subMenu) { - if (mPresenters.isEmpty()) return false; - - boolean result = false; - - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else if (!result) { - result = presenter.onSubMenuSelected(subMenu); - } - } - return result; - } - - private void dispatchSaveInstanceState(Bundle outState) { - if (mPresenters.isEmpty()) return; - - SparseArray presenterStates = new SparseArray(); - - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else { - final int id = presenter.getId(); - if (id > 0) { - final Parcelable state = presenter.onSaveInstanceState(); - if (state != null) { - presenterStates.put(id, state); - } - } - } - } - - outState.putSparseParcelableArray(PRESENTER_KEY, presenterStates); - } - - private void dispatchRestoreInstanceState(Bundle state) { - SparseArray presenterStates = state.getSparseParcelableArray(PRESENTER_KEY); - - if (presenterStates == null || mPresenters.isEmpty()) return; - - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else { - final int id = presenter.getId(); - if (id > 0) { - Parcelable parcel = presenterStates.get(id); - if (parcel != null) { - presenter.onRestoreInstanceState(parcel); - } - } - } - } - } - - public void savePresenterStates(Bundle outState) { - dispatchSaveInstanceState(outState); - } - - public void restorePresenterStates(Bundle state) { - dispatchRestoreInstanceState(state); - } - - public void saveActionViewStates(Bundle outStates) { - SparseArray viewStates = null; - - final int itemCount = size(); - for (int i = 0; i < itemCount; i++) { - final MenuItem item = getItem(i); - final View v = item.getActionView(); - if (v != null && v.getId() != View.NO_ID) { - if (viewStates == null) { - viewStates = new SparseArray(); - } - v.saveHierarchyState(viewStates); - if (item.isActionViewExpanded()) { - outStates.putInt(EXPANDED_ACTION_VIEW_ID, item.getItemId()); - } - } - if (item.hasSubMenu()) { - final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); - subMenu.saveActionViewStates(outStates); - } - } - - if (viewStates != null) { - outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates); - } - } - - public void restoreActionViewStates(Bundle states) { - if (states == null) { - return; - } - - SparseArray viewStates = states.getSparseParcelableArray( - getActionViewStatesKey()); - - final int itemCount = size(); - for (int i = 0; i < itemCount; i++) { - final MenuItem item = getItem(i); - final View v = item.getActionView(); - if (v != null && v.getId() != View.NO_ID) { - v.restoreHierarchyState(viewStates); - } - if (item.hasSubMenu()) { - final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); - subMenu.restoreActionViewStates(states); - } - } - - final int expandedId = states.getInt(EXPANDED_ACTION_VIEW_ID); - if (expandedId > 0) { - MenuItem itemToExpand = findItem(expandedId); - if (itemToExpand != null) { - itemToExpand.expandActionView(); - } - } - } - - protected String getActionViewStatesKey() { - return ACTION_VIEW_STATES_KEY; - } - - public void setCallback(Callback cb) { - mCallback = cb; - } - - /** - * Adds an item to the menu. The other add methods funnel to this. - */ - private MenuItem addInternal(int group, int id, int categoryOrder, CharSequence title) { - final int ordering = getOrdering(categoryOrder); - - final MenuItemImpl item = new MenuItemImpl(this, group, id, categoryOrder, - ordering, title, mDefaultShowAsAction); - - if (mCurrentMenuInfo != null) { - // Pass along the current menu info - item.setMenuInfo(mCurrentMenuInfo); - } - - mItems.add(findInsertIndex(mItems, ordering), item); - onItemsChanged(true); - - return item; - } - - public MenuItem add(CharSequence title) { - return addInternal(0, 0, 0, title); - } - - public MenuItem add(int titleRes) { - return addInternal(0, 0, 0, mResources.getString(titleRes)); - } - - public MenuItem add(int group, int id, int categoryOrder, CharSequence title) { - return addInternal(group, id, categoryOrder, title); - } - - public MenuItem add(int group, int id, int categoryOrder, int title) { - return addInternal(group, id, categoryOrder, mResources.getString(title)); - } - - public SubMenu addSubMenu(CharSequence title) { - return addSubMenu(0, 0, 0, title); - } - - public SubMenu addSubMenu(int titleRes) { - return addSubMenu(0, 0, 0, mResources.getString(titleRes)); - } - - public SubMenu addSubMenu(int group, int id, int categoryOrder, CharSequence title) { - final MenuItemImpl item = (MenuItemImpl) addInternal(group, id, categoryOrder, title); - final SubMenuBuilder subMenu = new SubMenuBuilder(mContext, this, item); - item.setSubMenu(subMenu); - - return subMenu; - } - - public SubMenu addSubMenu(int group, int id, int categoryOrder, int title) { - return addSubMenu(group, id, categoryOrder, mResources.getString(title)); - } - - public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller, - Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { - PackageManager pm = mContext.getPackageManager(); - final List lri = - pm.queryIntentActivityOptions(caller, specifics, intent, 0); - final int N = lri != null ? lri.size() : 0; - - if ((flags & FLAG_APPEND_TO_GROUP) == 0) { - removeGroup(group); - } - - for (int i=0; i= 0) { - outSpecificItems[ri.specificIndex] = item; - } - } - - return N; - } - - public void removeItem(int id) { - removeItemAtInt(findItemIndex(id), true); - } - - public void removeGroup(int group) { - final int i = findGroupIndex(group); - - if (i >= 0) { - final int maxRemovable = mItems.size() - i; - int numRemoved = 0; - while ((numRemoved++ < maxRemovable) && (mItems.get(i).getGroupId() == group)) { - // Don't force update for each one, this method will do it at the end - removeItemAtInt(i, false); - } - - // Notify menu views - onItemsChanged(true); - } - } - - /** - * Remove the item at the given index and optionally forces menu views to - * update. - * - * @param index The index of the item to be removed. If this index is - * invalid an exception is thrown. - * @param updateChildrenOnMenuViews Whether to force update on menu views. - * Please make sure you eventually call this after your batch of - * removals. - */ - private void removeItemAtInt(int index, boolean updateChildrenOnMenuViews) { - if ((index < 0) || (index >= mItems.size())) return; - - mItems.remove(index); - - if (updateChildrenOnMenuViews) onItemsChanged(true); - } - - public void removeItemAt(int index) { - removeItemAtInt(index, true); - } - - public void clearAll() { - mPreventDispatchingItemsChanged = true; - clear(); - clearHeader(); - mPreventDispatchingItemsChanged = false; - mItemsChangedWhileDispatchPrevented = false; - onItemsChanged(true); - } - - public void clear() { - if (mExpandedItem != null) { - collapseItemActionView(mExpandedItem); - } - mItems.clear(); - - onItemsChanged(true); - } - - void setExclusiveItemChecked(MenuItem item) { - final int group = item.getGroupId(); - - final int N = mItems.size(); - for (int i = 0; i < N; i++) { - MenuItemImpl curItem = mItems.get(i); - if (curItem.getGroupId() == group) { - if (!curItem.isExclusiveCheckable()) continue; - if (!curItem.isCheckable()) continue; - - // Check the item meant to be checked, uncheck the others (that are in the group) - curItem.setCheckedInt(curItem == item); - } - } - } - - public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { - final int N = mItems.size(); - - for (int i = 0; i < N; i++) { - MenuItemImpl item = mItems.get(i); - if (item.getGroupId() == group) { - item.setExclusiveCheckable(exclusive); - item.setCheckable(checkable); - } - } - } - - public void setGroupVisible(int group, boolean visible) { - final int N = mItems.size(); - - // We handle the notification of items being changed ourselves, so we use setVisibleInt rather - // than setVisible and at the end notify of items being changed - - boolean changedAtLeastOneItem = false; - for (int i = 0; i < N; i++) { - MenuItemImpl item = mItems.get(i); - if (item.getGroupId() == group) { - if (item.setVisibleInt(visible)) changedAtLeastOneItem = true; - } - } - - if (changedAtLeastOneItem) onItemsChanged(true); - } - - public void setGroupEnabled(int group, boolean enabled) { - final int N = mItems.size(); - - for (int i = 0; i < N; i++) { - MenuItemImpl item = mItems.get(i); - if (item.getGroupId() == group) { - item.setEnabled(enabled); - } - } - } - - public boolean hasVisibleItems() { - final int size = size(); - - for (int i = 0; i < size; i++) { - MenuItemImpl item = mItems.get(i); - if (item.isVisible()) { - return true; - } - } - - return false; - } - - public MenuItem findItem(int id) { - final int size = size(); - for (int i = 0; i < size; i++) { - MenuItemImpl item = mItems.get(i); - if (item.getItemId() == id) { - return item; - } else if (item.hasSubMenu()) { - MenuItem possibleItem = item.getSubMenu().findItem(id); - - if (possibleItem != null) { - return possibleItem; - } - } - } - - return null; - } - - public int findItemIndex(int id) { - final int size = size(); - - for (int i = 0; i < size; i++) { - MenuItemImpl item = mItems.get(i); - if (item.getItemId() == id) { - return i; - } - } - - return -1; - } - - public int findGroupIndex(int group) { - return findGroupIndex(group, 0); - } - - public int findGroupIndex(int group, int start) { - final int size = size(); - - if (start < 0) { - start = 0; - } - - for (int i = start; i < size; i++) { - final MenuItemImpl item = mItems.get(i); - - if (item.getGroupId() == group) { - return i; - } - } - - return -1; - } - - public int size() { - return mItems.size(); - } - - /** {@inheritDoc} */ - public MenuItem getItem(int index) { - return mItems.get(index); - } - - public boolean isShortcutKey(int keyCode, KeyEvent event) { - return findItemWithShortcutForKey(keyCode, event) != null; - } - - public void setQwertyMode(boolean isQwerty) { - mQwertyMode = isQwerty; - - onItemsChanged(false); - } - - /** - * Returns the ordering across all items. This will grab the category from - * the upper bits, find out how to order the category with respect to other - * categories, and combine it with the lower bits. - * - * @param categoryOrder The category order for a particular item (if it has - * not been or/add with a category, the default category is - * assumed). - * @return An ordering integer that can be used to order this item across - * all the items (even from other categories). - */ - private static int getOrdering(int categoryOrder) { - final int index = (categoryOrder & CATEGORY_MASK) >> CATEGORY_SHIFT; - - if (index < 0 || index >= sCategoryToOrder.length) { - throw new IllegalArgumentException("order does not contain a valid category."); - } - - return (sCategoryToOrder[index] << CATEGORY_SHIFT) | (categoryOrder & USER_MASK); - } - - /** - * @return whether the menu shortcuts are in qwerty mode or not - */ - boolean isQwertyMode() { - return mQwertyMode; - } - - /** - * Sets whether the shortcuts should be visible on menus. Devices without hardware - * key input will never make shortcuts visible even if this method is passed 'true'. - * - * @param shortcutsVisible Whether shortcuts should be visible (if true and a - * menu item does not have a shortcut defined, that item will - * still NOT show a shortcut) - */ - public void setShortcutsVisible(boolean shortcutsVisible) { - if (mShortcutsVisible == shortcutsVisible) return; - - setShortcutsVisibleInner(shortcutsVisible); - onItemsChanged(false); - } - - private void setShortcutsVisibleInner(boolean shortcutsVisible) { - mShortcutsVisible = shortcutsVisible - && mResources.getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS - && mResources.getBoolean( - R.bool.abs__config_showMenuShortcutsWhenKeyboardPresent); - } - - /** - * @return Whether shortcuts should be visible on menus. - */ - public boolean isShortcutsVisible() { - return mShortcutsVisible; - } - - Resources getResources() { - return mResources; - } - - public Context getContext() { - return mContext; - } - - boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) { - return mCallback != null && mCallback.onMenuItemSelected(menu, item); - } - - /** - * Dispatch a mode change event to this menu's callback. - */ - public void changeMenuMode() { - if (mCallback != null) { - mCallback.onMenuModeChange(this); - } - } - - private static int findInsertIndex(ArrayList items, int ordering) { - for (int i = items.size() - 1; i >= 0; i--) { - MenuItemImpl item = items.get(i); - if (item.getOrdering() <= ordering) { - return i + 1; - } - } - - return 0; - } - - public boolean performShortcut(int keyCode, KeyEvent event, int flags) { - final MenuItemImpl item = findItemWithShortcutForKey(keyCode, event); - - boolean handled = false; - - if (item != null) { - handled = performItemAction(item, flags); - } - - if ((flags & FLAG_ALWAYS_PERFORM_CLOSE) != 0) { - close(true); - } - - return handled; - } - - /* - * This function will return all the menu and sub-menu items that can - * be directly (the shortcut directly corresponds) and indirectly - * (the ALT-enabled char corresponds to the shortcut) associated - * with the keyCode. - */ - @SuppressWarnings("deprecation") - void findItemsWithShortcutForKey(List items, int keyCode, KeyEvent event) { - final boolean qwerty = isQwertyMode(); - final int metaState = event.getMetaState(); - final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData(); - // Get the chars associated with the keyCode (i.e using any chording combo) - final boolean isKeyCodeMapped = event.getKeyData(possibleChars); - // The delete key is not mapped to '\b' so we treat it specially - if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) { - return; - } - - // Look for an item whose shortcut is this key. - final int N = mItems.size(); - for (int i = 0; i < N; i++) { - MenuItemImpl item = mItems.get(i); - if (item.hasSubMenu()) { - ((MenuBuilder)item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event); - } - final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut(); - if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) && - (shortcutChar != 0) && - (shortcutChar == possibleChars.meta[0] - || shortcutChar == possibleChars.meta[2] - || (qwerty && shortcutChar == '\b' && - keyCode == KeyEvent.KEYCODE_DEL)) && - item.isEnabled()) { - items.add(item); - } - } - } - - /* - * We want to return the menu item associated with the key, but if there is no - * ambiguity (i.e. there is only one menu item corresponding to the key) we want - * to return it even if it's not an exact match; this allow the user to - * _not_ use the ALT key for example, making the use of shortcuts slightly more - * user-friendly. An example is on the G1, '!' and '1' are on the same key, and - * in Gmail, Menu+1 will trigger Menu+! (the actual shortcut). - * - * On the other hand, if two (or more) shortcuts corresponds to the same key, - * we have to only return the exact match. - */ - @SuppressWarnings("deprecation") - MenuItemImpl findItemWithShortcutForKey(int keyCode, KeyEvent event) { - // Get all items that can be associated directly or indirectly with the keyCode - ArrayList items = mTempShortcutItemList; - items.clear(); - findItemsWithShortcutForKey(items, keyCode, event); - - if (items.isEmpty()) { - return null; - } - - final int metaState = event.getMetaState(); - final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData(); - // Get the chars associated with the keyCode (i.e using any chording combo) - event.getKeyData(possibleChars); - - // If we have only one element, we can safely returns it - final int size = items.size(); - if (size == 1) { - return items.get(0); - } - - final boolean qwerty = isQwertyMode(); - // If we found more than one item associated with the key, - // we have to return the exact match - for (int i = 0; i < size; i++) { - final MenuItemImpl item = items.get(i); - final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : - item.getNumericShortcut(); - if ((shortcutChar == possibleChars.meta[0] && - (metaState & KeyEvent.META_ALT_ON) == 0) - || (shortcutChar == possibleChars.meta[2] && - (metaState & KeyEvent.META_ALT_ON) != 0) - || (qwerty && shortcutChar == '\b' && - keyCode == KeyEvent.KEYCODE_DEL)) { - return item; - } - } - return null; - } - - public boolean performIdentifierAction(int id, int flags) { - // Look for an item whose identifier is the id. - return performItemAction(findItem(id), flags); - } - - public boolean performItemAction(MenuItem item, int flags) { - MenuItemImpl itemImpl = (MenuItemImpl) item; - - if (itemImpl == null || !itemImpl.isEnabled()) { - return false; - } - - boolean invoked = itemImpl.invoke(); - - if (itemImpl.hasCollapsibleActionView()) { - invoked |= itemImpl.expandActionView(); - if (invoked) close(true); - } else if (item.hasSubMenu()) { - close(false); - - final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); - final ActionProvider provider = item.getActionProvider(); - if (provider != null && provider.hasSubMenu()) { - provider.onPrepareSubMenu(subMenu); - } - invoked |= dispatchSubMenuSelected(subMenu); - if (!invoked) close(true); - } else { - if ((flags & FLAG_PERFORM_NO_CLOSE) == 0) { - close(true); - } - } - - return invoked; - } - - /** - * Closes the visible menu. - * - * @param allMenusAreClosing Whether the menus are completely closing (true), - * or whether there is another menu coming in this menu's place - * (false). For example, if the menu is closing because a - * sub menu is about to be shown, allMenusAreClosing - * is false. - */ - final void close(boolean allMenusAreClosing) { - if (mIsClosing) return; - - mIsClosing = true; - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else { - presenter.onCloseMenu(this, allMenusAreClosing); - } - } - mIsClosing = false; - } - - /** {@inheritDoc} */ - public void close() { - close(true); - } - - /** - * Called when an item is added or removed. - * - * @param structureChanged true if the menu structure changed, - * false if only item properties changed. - * (Visibility is a structural property since it affects layout.) - */ - void onItemsChanged(boolean structureChanged) { - if (!mPreventDispatchingItemsChanged) { - if (structureChanged) { - mIsVisibleItemsStale = true; - mIsActionItemsStale = true; - } - - dispatchPresenterUpdate(structureChanged); - } else { - mItemsChangedWhileDispatchPrevented = true; - } - } - - /** - * Stop dispatching item changed events to presenters until - * {@link #startDispatchingItemsChanged()} is called. Useful when - * many menu operations are going to be performed as a batch. - */ - public void stopDispatchingItemsChanged() { - if (!mPreventDispatchingItemsChanged) { - mPreventDispatchingItemsChanged = true; - mItemsChangedWhileDispatchPrevented = false; - } - } - - public void startDispatchingItemsChanged() { - mPreventDispatchingItemsChanged = false; - - if (mItemsChangedWhileDispatchPrevented) { - mItemsChangedWhileDispatchPrevented = false; - onItemsChanged(true); - } - } - - /** - * Called by {@link MenuItemImpl} when its visible flag is changed. - * @param item The item that has gone through a visibility change. - */ - void onItemVisibleChanged(MenuItemImpl item) { - // Notify of items being changed - mIsVisibleItemsStale = true; - onItemsChanged(true); - } - - /** - * Called by {@link MenuItemImpl} when its action request status is changed. - * @param item The item that has gone through a change in action request status. - */ - void onItemActionRequestChanged(MenuItemImpl item) { - // Notify of items being changed - mIsActionItemsStale = true; - onItemsChanged(true); - } - - ArrayList getVisibleItems() { - if (!mIsVisibleItemsStale) return mVisibleItems; - - // Refresh the visible items - mVisibleItems.clear(); - - final int itemsSize = mItems.size(); - MenuItemImpl item; - for (int i = 0; i < itemsSize; i++) { - item = mItems.get(i); - if (item.isVisible()) mVisibleItems.add(item); - } - - mIsVisibleItemsStale = false; - mIsActionItemsStale = true; - - return mVisibleItems; - } - - /** - * This method determines which menu items get to be 'action items' that will appear - * in an action bar and which items should be 'overflow items' in a secondary menu. - * The rules are as follows: - * - *

Items are considered for inclusion in the order specified within the menu. - * There is a limit of mMaxActionItems as a total count, optionally including the overflow - * menu button itself. This is a soft limit; if an item shares a group ID with an item - * previously included as an action item, the new item will stay with its group and become - * an action item itself even if it breaks the max item count limit. This is done to - * limit the conceptual complexity of the items presented within an action bar. Only a few - * unrelated concepts should be presented to the user in this space, and groups are treated - * as a single concept. - * - *

There is also a hard limit of consumed measurable space: mActionWidthLimit. This - * limit may be broken by a single item that exceeds the remaining space, but no further - * items may be added. If an item that is part of a group cannot fit within the remaining - * measured width, the entire group will be demoted to overflow. This is done to ensure room - * for navigation and other affordances in the action bar as well as reduce general UI clutter. - * - *

The space freed by demoting a full group cannot be consumed by future menu items. - * Once items begin to overflow, all future items become overflow items as well. This is - * to avoid inadvertent reordering that may break the app's intended design. - */ - public void flagActionItems() { - if (!mIsActionItemsStale) { - return; - } - - // Presenters flag action items as needed. - boolean flagged = false; - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else { - flagged |= presenter.flagActionItems(); - } - } - - if (flagged) { - mActionItems.clear(); - mNonActionItems.clear(); - ArrayList visibleItems = getVisibleItems(); - final int itemsSize = visibleItems.size(); - for (int i = 0; i < itemsSize; i++) { - MenuItemImpl item = visibleItems.get(i); - if (item.isActionButton()) { - mActionItems.add(item); - } else { - mNonActionItems.add(item); - } - } - } else { - // Nobody flagged anything, everything is a non-action item. - // (This happens during a first pass with no action-item presenters.) - mActionItems.clear(); - mNonActionItems.clear(); - mNonActionItems.addAll(getVisibleItems()); - } - mIsActionItemsStale = false; - } - - ArrayList getActionItems() { - flagActionItems(); - return mActionItems; - } - - ArrayList getNonActionItems() { - flagActionItems(); - return mNonActionItems; - } - - public void clearHeader() { - mHeaderIcon = null; - mHeaderTitle = null; - mHeaderView = null; - - onItemsChanged(false); - } - - private void setHeaderInternal(final int titleRes, final CharSequence title, final int iconRes, - final Drawable icon, final View view) { - final Resources r = getResources(); - - if (view != null) { - mHeaderView = view; - - // If using a custom view, then the title and icon aren't used - mHeaderTitle = null; - mHeaderIcon = null; - } else { - if (titleRes > 0) { - mHeaderTitle = r.getText(titleRes); - } else if (title != null) { - mHeaderTitle = title; - } - - if (iconRes > 0) { - mHeaderIcon = r.getDrawable(iconRes); - } else if (icon != null) { - mHeaderIcon = icon; - } - - // If using the title or icon, then a custom view isn't used - mHeaderView = null; - } - - // Notify of change - onItemsChanged(false); - } - - /** - * Sets the header's title. This replaces the header view. Called by the - * builder-style methods of subclasses. - * - * @param title The new title. - * @return This MenuBuilder so additional setters can be called. - */ - protected MenuBuilder setHeaderTitleInt(CharSequence title) { - setHeaderInternal(0, title, 0, null, null); - return this; - } - - /** - * Sets the header's title. This replaces the header view. Called by the - * builder-style methods of subclasses. - * - * @param titleRes The new title (as a resource ID). - * @return This MenuBuilder so additional setters can be called. - */ - protected MenuBuilder setHeaderTitleInt(int titleRes) { - setHeaderInternal(titleRes, null, 0, null, null); - return this; - } - - /** - * Sets the header's icon. This replaces the header view. Called by the - * builder-style methods of subclasses. - * - * @param icon The new icon. - * @return This MenuBuilder so additional setters can be called. - */ - protected MenuBuilder setHeaderIconInt(Drawable icon) { - setHeaderInternal(0, null, 0, icon, null); - return this; - } - - /** - * Sets the header's icon. This replaces the header view. Called by the - * builder-style methods of subclasses. - * - * @param iconRes The new icon (as a resource ID). - * @return This MenuBuilder so additional setters can be called. - */ - protected MenuBuilder setHeaderIconInt(int iconRes) { - setHeaderInternal(0, null, iconRes, null, null); - return this; - } - - /** - * Sets the header's view. This replaces the title and icon. Called by the - * builder-style methods of subclasses. - * - * @param view The new view. - * @return This MenuBuilder so additional setters can be called. - */ - protected MenuBuilder setHeaderViewInt(View view) { - setHeaderInternal(0, null, 0, null, view); - return this; - } - - public CharSequence getHeaderTitle() { - return mHeaderTitle; - } - - public Drawable getHeaderIcon() { - return mHeaderIcon; - } - - public View getHeaderView() { - return mHeaderView; - } - - /** - * Gets the root menu (if this is a submenu, find its root menu). - * @return The root menu. - */ - public MenuBuilder getRootMenu() { - return this; - } - - /** - * Sets the current menu info that is set on all items added to this menu - * (until this is called again with different menu info, in which case that - * one will be added to all subsequent item additions). - * - * @param menuInfo The extra menu information to add. - */ - public void setCurrentMenuInfo(ContextMenuInfo menuInfo) { - mCurrentMenuInfo = menuInfo; - } - - void setOptionalIconsVisible(boolean visible) { - mOptionalIconsVisible = visible; - } - - boolean getOptionalIconsVisible() { - return mOptionalIconsVisible; - } - - public boolean expandItemActionView(MenuItemImpl item) { - if (mPresenters.isEmpty()) return false; - - boolean expanded = false; - - stopDispatchingItemsChanged(); - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else if ((expanded = presenter.expandItemActionView(this, item))) { - break; - } - } - startDispatchingItemsChanged(); - - if (expanded) { - mExpandedItem = item; - } - return expanded; - } - - public boolean collapseItemActionView(MenuItemImpl item) { - if (mPresenters.isEmpty() || mExpandedItem != item) return false; - - boolean collapsed = false; - - stopDispatchingItemsChanged(); - for (WeakReference ref : mPresenters) { - final MenuPresenter presenter = ref.get(); - if (presenter == null) { - mPresenters.remove(ref); - } else if ((collapsed = presenter.collapseItemActionView(this, item))) { - break; - } - } - startDispatchingItemsChanged(); - - if (collapsed) { - mExpandedItem = null; - } - return collapsed; - } - - public MenuItemImpl getExpandedItem() { - return mExpandedItem; - } - - public boolean bindNativeOverflow(android.view.Menu menu, android.view.MenuItem.OnMenuItemClickListener listener, HashMap map) { - final List nonActionItems = getNonActionItems(); - if (nonActionItems == null || nonActionItems.size() == 0) { - return false; - } - - boolean visible = false; - menu.clear(); - for (MenuItemImpl nonActionItem : nonActionItems) { - if (!nonActionItem.isVisible()) { - continue; - } - visible = true; - - android.view.MenuItem nativeItem; - if (nonActionItem.hasSubMenu()) { - android.view.SubMenu nativeSub = menu.addSubMenu(nonActionItem.getGroupId(), nonActionItem.getItemId(), - nonActionItem.getOrder(), nonActionItem.getTitle()); - - SubMenuBuilder subMenu = (SubMenuBuilder)nonActionItem.getSubMenu(); - for (MenuItemImpl subItem : subMenu.getVisibleItems()) { - android.view.MenuItem nativeSubItem = nativeSub.add(subItem.getGroupId(), subItem.getItemId(), - subItem.getOrder(), subItem.getTitle()); - - nativeSubItem.setIcon(subItem.getIcon()); - nativeSubItem.setOnMenuItemClickListener(listener); - nativeSubItem.setEnabled(subItem.isEnabled()); - nativeSubItem.setIntent(subItem.getIntent()); - nativeSubItem.setNumericShortcut(subItem.getNumericShortcut()); - nativeSubItem.setAlphabeticShortcut(subItem.getAlphabeticShortcut()); - nativeSubItem.setTitleCondensed(subItem.getTitleCondensed()); - nativeSubItem.setCheckable(subItem.isCheckable()); - nativeSubItem.setChecked(subItem.isChecked()); - - if (subItem.isExclusiveCheckable()) { - nativeSub.setGroupCheckable(subItem.getGroupId(), true, true); - } - - map.put(nativeSubItem, subItem); - } - - nativeItem = nativeSub.getItem(); - } else { - nativeItem = menu.add(nonActionItem.getGroupId(), nonActionItem.getItemId(), - nonActionItem.getOrder(), nonActionItem.getTitle()); - } - nativeItem.setIcon(nonActionItem.getIcon()); - nativeItem.setOnMenuItemClickListener(listener); - nativeItem.setEnabled(nonActionItem.isEnabled()); - nativeItem.setIntent(nonActionItem.getIntent()); - nativeItem.setNumericShortcut(nonActionItem.getNumericShortcut()); - nativeItem.setAlphabeticShortcut(nonActionItem.getAlphabeticShortcut()); - nativeItem.setTitleCondensed(nonActionItem.getTitleCondensed()); - nativeItem.setCheckable(nonActionItem.isCheckable()); - nativeItem.setChecked(nonActionItem.isChecked()); - - if (nonActionItem.isExclusiveCheckable()) { - menu.setGroupCheckable(nonActionItem.getGroupId(), true, true); - } - - map.put(nativeItem, nonActionItem); - } - return visible; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemImpl.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemImpl.java deleted file mode 100644 index f5359fb4..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemImpl.java +++ /dev/null @@ -1,647 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import android.content.ActivityNotFoundException; -import android.content.Context; -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.util.Log; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewDebug; -import android.widget.LinearLayout; - -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -/** - * @hide - */ -public final class MenuItemImpl implements MenuItem { - private static final String TAG = "MenuItemImpl"; - - private static final int SHOW_AS_ACTION_MASK = SHOW_AS_ACTION_NEVER | - SHOW_AS_ACTION_IF_ROOM | - SHOW_AS_ACTION_ALWAYS; - - private final int mId; - private final int mGroup; - private final int mCategoryOrder; - private final int mOrdering; - private CharSequence mTitle; - private CharSequence mTitleCondensed; - private Intent mIntent; - private char mShortcutNumericChar; - private char mShortcutAlphabeticChar; - - /** The icon's drawable which is only created as needed */ - private Drawable mIconDrawable; - /** - * The icon's resource ID which is used to get the Drawable when it is - * needed (if the Drawable isn't already obtained--only one of the two is - * needed). - */ - private int mIconResId = NO_ICON; - - /** The menu to which this item belongs */ - private MenuBuilder mMenu; - /** If this item should launch a sub menu, this is the sub menu to launch */ - private SubMenuBuilder mSubMenu; - - private Runnable mItemCallback; - private MenuItem.OnMenuItemClickListener mClickListener; - - private int mFlags = ENABLED; - private static final int CHECKABLE = 0x00000001; - private static final int CHECKED = 0x00000002; - private static final int EXCLUSIVE = 0x00000004; - private static final int HIDDEN = 0x00000008; - private static final int ENABLED = 0x00000010; - private static final int IS_ACTION = 0x00000020; - - private int mShowAsAction = SHOW_AS_ACTION_NEVER; - - private View mActionView; - private ActionProvider mActionProvider; - private OnActionExpandListener mOnActionExpandListener; - private boolean mIsActionViewExpanded = false; - - /** Used for the icon resource ID if this item does not have an icon */ - static final int NO_ICON = 0; - - /** - * Current use case is for context menu: Extra information linked to the - * View that added this item to the context menu. - */ - private ContextMenuInfo mMenuInfo; - - private static String sPrependShortcutLabel; - private static String sEnterShortcutLabel; - private static String sDeleteShortcutLabel; - private static String sSpaceShortcutLabel; - - - /** - * Instantiates this menu item. - * - * @param menu - * @param group Item ordering grouping control. The item will be added after - * all other items whose order is <= this number, and before any - * that are larger than it. This can also be used to define - * groups of items for batch state changes. Normally use 0. - * @param id Unique item ID. Use 0 if you do not need a unique ID. - * @param categoryOrder The ordering for this item. - * @param title The text to display for the item. - */ - MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering, - CharSequence title, int showAsAction) { - - /* TODO if (sPrependShortcutLabel == null) { - // This is instantiated from the UI thread, so no chance of sync issues - sPrependShortcutLabel = menu.getContext().getResources().getString( - com.android.internal.R.string.prepend_shortcut_label); - sEnterShortcutLabel = menu.getContext().getResources().getString( - com.android.internal.R.string.menu_enter_shortcut_label); - sDeleteShortcutLabel = menu.getContext().getResources().getString( - com.android.internal.R.string.menu_delete_shortcut_label); - sSpaceShortcutLabel = menu.getContext().getResources().getString( - com.android.internal.R.string.menu_space_shortcut_label); - }*/ - - mMenu = menu; - mId = id; - mGroup = group; - mCategoryOrder = categoryOrder; - mOrdering = ordering; - mTitle = title; - mShowAsAction = showAsAction; - } - - /** - * Invokes the item by calling various listeners or callbacks. - * - * @return true if the invocation was handled, false otherwise - */ - public boolean invoke() { - if (mClickListener != null && - mClickListener.onMenuItemClick(this)) { - return true; - } - - if (mMenu.dispatchMenuItemSelected(mMenu.getRootMenu(), this)) { - return true; - } - - if (mItemCallback != null) { - mItemCallback.run(); - return true; - } - - if (mIntent != null) { - try { - mMenu.getContext().startActivity(mIntent); - return true; - } catch (ActivityNotFoundException e) { - Log.e(TAG, "Can't find activity to handle intent; ignoring", e); - } - } - - if (mActionProvider != null && mActionProvider.onPerformDefaultAction()) { - return true; - } - - return false; - } - - public boolean isEnabled() { - return (mFlags & ENABLED) != 0; - } - - public MenuItem setEnabled(boolean enabled) { - if (enabled) { - mFlags |= ENABLED; - } else { - mFlags &= ~ENABLED; - } - - mMenu.onItemsChanged(false); - - return this; - } - - public int getGroupId() { - return mGroup; - } - - @ViewDebug.CapturedViewProperty - public int getItemId() { - return mId; - } - - public int getOrder() { - return mCategoryOrder; - } - - public int getOrdering() { - return mOrdering; - } - - public Intent getIntent() { - return mIntent; - } - - public MenuItem setIntent(Intent intent) { - mIntent = intent; - return this; - } - - Runnable getCallback() { - return mItemCallback; - } - - public MenuItem setCallback(Runnable callback) { - mItemCallback = callback; - return this; - } - - public char getAlphabeticShortcut() { - return mShortcutAlphabeticChar; - } - - public MenuItem setAlphabeticShortcut(char alphaChar) { - if (mShortcutAlphabeticChar == alphaChar) return this; - - mShortcutAlphabeticChar = Character.toLowerCase(alphaChar); - - mMenu.onItemsChanged(false); - - return this; - } - - public char getNumericShortcut() { - return mShortcutNumericChar; - } - - public MenuItem setNumericShortcut(char numericChar) { - if (mShortcutNumericChar == numericChar) return this; - - mShortcutNumericChar = numericChar; - - mMenu.onItemsChanged(false); - - return this; - } - - public MenuItem setShortcut(char numericChar, char alphaChar) { - mShortcutNumericChar = numericChar; - mShortcutAlphabeticChar = Character.toLowerCase(alphaChar); - - mMenu.onItemsChanged(false); - - return this; - } - - /** - * @return The active shortcut (based on QWERTY-mode of the menu). - */ - char getShortcut() { - return (mMenu.isQwertyMode() ? mShortcutAlphabeticChar : mShortcutNumericChar); - } - - /** - * @return The label to show for the shortcut. This includes the chording - * key (for example 'Menu+a'). Also, any non-human readable - * characters should be human readable (for example 'Menu+enter'). - */ - String getShortcutLabel() { - - char shortcut = getShortcut(); - if (shortcut == 0) { - return ""; - } - - StringBuilder sb = new StringBuilder(sPrependShortcutLabel); - switch (shortcut) { - - case '\n': - sb.append(sEnterShortcutLabel); - break; - - case '\b': - sb.append(sDeleteShortcutLabel); - break; - - case ' ': - sb.append(sSpaceShortcutLabel); - break; - - default: - sb.append(shortcut); - break; - } - - return sb.toString(); - } - - /** - * @return Whether this menu item should be showing shortcuts (depends on - * whether the menu should show shortcuts and whether this item has - * a shortcut defined) - */ - boolean shouldShowShortcut() { - // Show shortcuts if the menu is supposed to show shortcuts AND this item has a shortcut - return mMenu.isShortcutsVisible() && (getShortcut() != 0); - } - - public SubMenu getSubMenu() { - return mSubMenu; - } - - public boolean hasSubMenu() { - return mSubMenu != null; - } - - void setSubMenu(SubMenuBuilder subMenu) { - mSubMenu = subMenu; - - subMenu.setHeaderTitle(getTitle()); - } - - @ViewDebug.CapturedViewProperty - public CharSequence getTitle() { - return mTitle; - } - - /** - * Gets the title for a particular {@link ItemView} - * - * @param itemView The ItemView that is receiving the title - * @return Either the title or condensed title based on what the ItemView - * prefers - */ - CharSequence getTitleForItemView(MenuView.ItemView itemView) { - return ((itemView != null) && itemView.prefersCondensedTitle()) - ? getTitleCondensed() - : getTitle(); - } - - public MenuItem setTitle(CharSequence title) { - mTitle = title; - - mMenu.onItemsChanged(false); - - if (mSubMenu != null) { - mSubMenu.setHeaderTitle(title); - } - - return this; - } - - public MenuItem setTitle(int title) { - return setTitle(mMenu.getContext().getString(title)); - } - - public CharSequence getTitleCondensed() { - return mTitleCondensed != null ? mTitleCondensed : mTitle; - } - - public MenuItem setTitleCondensed(CharSequence title) { - mTitleCondensed = title; - - // Could use getTitle() in the loop below, but just cache what it would do here - if (title == null) { - title = mTitle; - } - - mMenu.onItemsChanged(false); - - return this; - } - - public Drawable getIcon() { - if (mIconDrawable != null) { - return mIconDrawable; - } - - if (mIconResId != NO_ICON) { - return mMenu.getResources().getDrawable(mIconResId); - } - - return null; - } - - public MenuItem setIcon(Drawable icon) { - mIconResId = NO_ICON; - mIconDrawable = icon; - mMenu.onItemsChanged(false); - - return this; - } - - public MenuItem setIcon(int iconResId) { - mIconDrawable = null; - mIconResId = iconResId; - - // If we have a view, we need to push the Drawable to them - mMenu.onItemsChanged(false); - - return this; - } - - public boolean isCheckable() { - return (mFlags & CHECKABLE) == CHECKABLE; - } - - public MenuItem setCheckable(boolean checkable) { - final int oldFlags = mFlags; - mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0); - if (oldFlags != mFlags) { - mMenu.onItemsChanged(false); - } - - return this; - } - - public void setExclusiveCheckable(boolean exclusive) { - mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0); - } - - public boolean isExclusiveCheckable() { - return (mFlags & EXCLUSIVE) != 0; - } - - public boolean isChecked() { - return (mFlags & CHECKED) == CHECKED; - } - - public MenuItem setChecked(boolean checked) { - if ((mFlags & EXCLUSIVE) != 0) { - // Call the method on the Menu since it knows about the others in this - // exclusive checkable group - mMenu.setExclusiveItemChecked(this); - } else { - setCheckedInt(checked); - } - - return this; - } - - void setCheckedInt(boolean checked) { - final int oldFlags = mFlags; - mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0); - if (oldFlags != mFlags) { - mMenu.onItemsChanged(false); - } - } - - public boolean isVisible() { - return (mFlags & HIDDEN) == 0; - } - - /** - * Changes the visibility of the item. This method DOES NOT notify the - * parent menu of a change in this item, so this should only be called from - * methods that will eventually trigger this change. If unsure, use {@link #setVisible(boolean)} - * instead. - * - * @param shown Whether to show (true) or hide (false). - * @return Whether the item's shown state was changed - */ - boolean setVisibleInt(boolean shown) { - final int oldFlags = mFlags; - mFlags = (mFlags & ~HIDDEN) | (shown ? 0 : HIDDEN); - return oldFlags != mFlags; - } - - public MenuItem setVisible(boolean shown) { - // Try to set the shown state to the given state. If the shown state was changed - // (i.e. the previous state isn't the same as given state), notify the parent menu that - // the shown state has changed for this item - if (setVisibleInt(shown)) mMenu.onItemVisibleChanged(this); - - return this; - } - - public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener clickListener) { - mClickListener = clickListener; - return this; - } - - @Override - public String toString() { - return mTitle.toString(); - } - - void setMenuInfo(ContextMenuInfo menuInfo) { - mMenuInfo = menuInfo; - } - - public ContextMenuInfo getMenuInfo() { - return mMenuInfo; - } - - public void actionFormatChanged() { - mMenu.onItemActionRequestChanged(this); - } - - /** - * @return Whether the menu should show icons for menu items. - */ - public boolean shouldShowIcon() { - return mMenu.getOptionalIconsVisible(); - } - - public boolean isActionButton() { - return (mFlags & IS_ACTION) == IS_ACTION; - } - - public boolean requestsActionButton() { - return (mShowAsAction & SHOW_AS_ACTION_IF_ROOM) == SHOW_AS_ACTION_IF_ROOM; - } - - public boolean requiresActionButton() { - return (mShowAsAction & SHOW_AS_ACTION_ALWAYS) == SHOW_AS_ACTION_ALWAYS; - } - - public void setIsActionButton(boolean isActionButton) { - if (isActionButton) { - mFlags |= IS_ACTION; - } else { - mFlags &= ~IS_ACTION; - } - } - - public boolean showsTextAsAction() { - return (mShowAsAction & SHOW_AS_ACTION_WITH_TEXT) == SHOW_AS_ACTION_WITH_TEXT; - } - - public void setShowAsAction(int actionEnum) { - switch (actionEnum & SHOW_AS_ACTION_MASK) { - case SHOW_AS_ACTION_ALWAYS: - case SHOW_AS_ACTION_IF_ROOM: - case SHOW_AS_ACTION_NEVER: - // Looks good! - break; - - default: - // Mutually exclusive options selected! - throw new IllegalArgumentException("SHOW_AS_ACTION_ALWAYS, SHOW_AS_ACTION_IF_ROOM," - + " and SHOW_AS_ACTION_NEVER are mutually exclusive."); - } - mShowAsAction = actionEnum; - mMenu.onItemActionRequestChanged(this); - } - - public MenuItem setActionView(View view) { - mActionView = view; - mActionProvider = null; - if (view != null && view.getId() == View.NO_ID && mId > 0) { - view.setId(mId); - } - mMenu.onItemActionRequestChanged(this); - return this; - } - - public MenuItem setActionView(int resId) { - final Context context = mMenu.getContext(); - final LayoutInflater inflater = LayoutInflater.from(context); - setActionView(inflater.inflate(resId, new LinearLayout(context), false)); - return this; - } - - public View getActionView() { - if (mActionView != null) { - return mActionView; - } else if (mActionProvider != null) { - mActionView = mActionProvider.onCreateActionView(); - return mActionView; - } else { - return null; - } - } - - public ActionProvider getActionProvider() { - return mActionProvider; - } - - public MenuItem setActionProvider(ActionProvider actionProvider) { - mActionView = null; - mActionProvider = actionProvider; - mMenu.onItemsChanged(true); // Measurement can be changed - return this; - } - - @Override - public MenuItem setShowAsActionFlags(int actionEnum) { - setShowAsAction(actionEnum); - return this; - } - - @Override - public boolean expandActionView() { - if ((mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) == 0 || mActionView == null) { - return false; - } - - if (mOnActionExpandListener == null || - mOnActionExpandListener.onMenuItemActionExpand(this)) { - return mMenu.expandItemActionView(this); - } - - return false; - } - - @Override - public boolean collapseActionView() { - if ((mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) == 0) { - return false; - } - if (mActionView == null) { - // We're already collapsed if we have no action view. - return true; - } - - if (mOnActionExpandListener == null || - mOnActionExpandListener.onMenuItemActionCollapse(this)) { - return mMenu.collapseItemActionView(this); - } - - return false; - } - - @Override - public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { - mOnActionExpandListener = listener; - return this; - } - - public boolean hasCollapsibleActionView() { - return (mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) != 0 && mActionView != null; - } - - public void setActionViewExpanded(boolean isExpanded) { - mIsActionViewExpanded = isExpanded; - mMenu.onItemsChanged(false); - } - - public boolean isActionViewExpanded() { - return mIsActionViewExpanded; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.java deleted file mode 100644 index 907a7aa0..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.java +++ /dev/null @@ -1,292 +0,0 @@ -package com.actionbarsherlock.internal.view.menu; - -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.view.View; -import android.view.ContextMenu.ContextMenuInfo; -import com.actionbarsherlock.internal.view.ActionProviderWrapper; -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -public class MenuItemWrapper implements MenuItem, android.view.MenuItem.OnMenuItemClickListener { - private final android.view.MenuItem mNativeItem; - private SubMenu mSubMenu = null; - private OnMenuItemClickListener mMenuItemClickListener = null; - private OnActionExpandListener mActionExpandListener = null; - private android.view.MenuItem.OnActionExpandListener mNativeActionExpandListener = null; - - - public MenuItemWrapper(android.view.MenuItem nativeItem) { - if (nativeItem == null) { - throw new IllegalStateException("Wrapped menu item cannot be null."); - } - mNativeItem = nativeItem; - } - - - @Override - public int getItemId() { - return mNativeItem.getItemId(); - } - - @Override - public int getGroupId() { - return mNativeItem.getGroupId(); - } - - @Override - public int getOrder() { - return mNativeItem.getOrder(); - } - - @Override - public MenuItem setTitle(CharSequence title) { - mNativeItem.setTitle(title); - return this; - } - - @Override - public MenuItem setTitle(int title) { - mNativeItem.setTitle(title); - return this; - } - - @Override - public CharSequence getTitle() { - return mNativeItem.getTitle(); - } - - @Override - public MenuItem setTitleCondensed(CharSequence title) { - mNativeItem.setTitleCondensed(title); - return this; - } - - @Override - public CharSequence getTitleCondensed() { - return mNativeItem.getTitleCondensed(); - } - - @Override - public MenuItem setIcon(Drawable icon) { - mNativeItem.setIcon(icon); - return this; - } - - @Override - public MenuItem setIcon(int iconRes) { - mNativeItem.setIcon(iconRes); - return this; - } - - @Override - public Drawable getIcon() { - return mNativeItem.getIcon(); - } - - @Override - public MenuItem setIntent(Intent intent) { - mNativeItem.setIntent(intent); - return this; - } - - @Override - public Intent getIntent() { - return mNativeItem.getIntent(); - } - - @Override - public MenuItem setShortcut(char numericChar, char alphaChar) { - mNativeItem.setShortcut(numericChar, alphaChar); - return this; - } - - @Override - public MenuItem setNumericShortcut(char numericChar) { - mNativeItem.setNumericShortcut(numericChar); - return this; - } - - @Override - public char getNumericShortcut() { - return mNativeItem.getNumericShortcut(); - } - - @Override - public MenuItem setAlphabeticShortcut(char alphaChar) { - mNativeItem.setAlphabeticShortcut(alphaChar); - return this; - } - - @Override - public char getAlphabeticShortcut() { - return mNativeItem.getAlphabeticShortcut(); - } - - @Override - public MenuItem setCheckable(boolean checkable) { - mNativeItem.setCheckable(checkable); - return this; - } - - @Override - public boolean isCheckable() { - return mNativeItem.isCheckable(); - } - - @Override - public MenuItem setChecked(boolean checked) { - mNativeItem.setChecked(checked); - return this; - } - - @Override - public boolean isChecked() { - return mNativeItem.isChecked(); - } - - @Override - public MenuItem setVisible(boolean visible) { - mNativeItem.setVisible(visible); - return this; - } - - @Override - public boolean isVisible() { - return mNativeItem.isVisible(); - } - - @Override - public MenuItem setEnabled(boolean enabled) { - mNativeItem.setEnabled(enabled); - return this; - } - - @Override - public boolean isEnabled() { - return mNativeItem.isEnabled(); - } - - @Override - public boolean hasSubMenu() { - return mNativeItem.hasSubMenu(); - } - - @Override - public SubMenu getSubMenu() { - if (hasSubMenu() && (mSubMenu == null)) { - mSubMenu = new SubMenuWrapper(mNativeItem.getSubMenu()); - } - return mSubMenu; - } - - @Override - public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { - mMenuItemClickListener = menuItemClickListener; - //Register ourselves as the listener to proxy - mNativeItem.setOnMenuItemClickListener(this); - return this; - } - - @Override - public boolean onMenuItemClick(android.view.MenuItem item) { - if (mMenuItemClickListener != null) { - return mMenuItemClickListener.onMenuItemClick(this); - } - return false; - } - - @Override - public ContextMenuInfo getMenuInfo() { - return mNativeItem.getMenuInfo(); - } - - @Override - public void setShowAsAction(int actionEnum) { - mNativeItem.setShowAsAction(actionEnum); - } - - @Override - public MenuItem setShowAsActionFlags(int actionEnum) { - mNativeItem.setShowAsActionFlags(actionEnum); - return this; - } - - @Override - public MenuItem setActionView(View view) { - mNativeItem.setActionView(view); - return this; - } - - @Override - public MenuItem setActionView(int resId) { - mNativeItem.setActionView(resId); - return this; - } - - @Override - public View getActionView() { - return mNativeItem.getActionView(); - } - - @Override - public MenuItem setActionProvider(ActionProvider actionProvider) { - mNativeItem.setActionProvider(new ActionProviderWrapper(actionProvider)); - return this; - } - - @Override - public ActionProvider getActionProvider() { - android.view.ActionProvider nativeProvider = mNativeItem.getActionProvider(); - if (nativeProvider != null && nativeProvider instanceof ActionProviderWrapper) { - return ((ActionProviderWrapper)nativeProvider).unwrap(); - } - return null; - } - - @Override - public boolean expandActionView() { - return mNativeItem.expandActionView(); - } - - @Override - public boolean collapseActionView() { - return mNativeItem.collapseActionView(); - } - - @Override - public boolean isActionViewExpanded() { - return mNativeItem.isActionViewExpanded(); - } - - @Override - public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { - mActionExpandListener = listener; - - if (mNativeActionExpandListener == null) { - mNativeActionExpandListener = new android.view.MenuItem.OnActionExpandListener() { - @Override - public boolean onMenuItemActionExpand(android.view.MenuItem menuItem) { - if (mActionExpandListener != null) { - return mActionExpandListener.onMenuItemActionExpand(MenuItemWrapper.this); - } - return false; - } - - @Override - public boolean onMenuItemActionCollapse(android.view.MenuItem menuItem) { - if (mActionExpandListener != null) { - return mActionExpandListener.onMenuItemActionCollapse(MenuItemWrapper.this); - } - return false; - } - }; - - //Register our inner-class as the listener to proxy method calls - mNativeItem.setOnActionExpandListener(mNativeActionExpandListener); - } - - return this; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.java deleted file mode 100644 index f030de31..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import java.util.ArrayList; -import android.content.Context; -import android.content.res.Resources; -import android.database.DataSetObserver; -import android.os.Parcelable; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.MeasureSpec; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.widget.AdapterView; -import android.widget.BaseAdapter; -import android.widget.FrameLayout; -import android.widget.ListAdapter; -import android.widget.PopupWindow; -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.view.View_HasStateListenerSupport; -import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener; -import com.actionbarsherlock.internal.widget.IcsListPopupWindow; -import com.actionbarsherlock.view.MenuItem; - -/** - * Presents a menu as a small, simple popup anchored to another view. - * @hide - */ -public class MenuPopupHelper implements AdapterView.OnItemClickListener, View.OnKeyListener, - ViewTreeObserver.OnGlobalLayoutListener, PopupWindow.OnDismissListener, - View_OnAttachStateChangeListener, MenuPresenter { - //UNUSED private static final String TAG = "MenuPopupHelper"; - - static final int ITEM_LAYOUT = R.layout.abs__popup_menu_item_layout; - - private Context mContext; - private LayoutInflater mInflater; - private IcsListPopupWindow mPopup; - private MenuBuilder mMenu; - private int mPopupMaxWidth; - private View mAnchorView; - private boolean mOverflowOnly; - private ViewTreeObserver mTreeObserver; - - private MenuAdapter mAdapter; - - private Callback mPresenterCallback; - - boolean mForceShowIcon; - - private ViewGroup mMeasureParent; - - public MenuPopupHelper(Context context, MenuBuilder menu) { - this(context, menu, null, false); - } - - public MenuPopupHelper(Context context, MenuBuilder menu, View anchorView) { - this(context, menu, anchorView, false); - } - - public MenuPopupHelper(Context context, MenuBuilder menu, - View anchorView, boolean overflowOnly) { - mContext = context; - mInflater = LayoutInflater.from(context); - mMenu = menu; - mOverflowOnly = overflowOnly; - - final Resources res = context.getResources(); - mPopupMaxWidth = Math.max(res.getDisplayMetrics().widthPixels / 2, - res.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth)); - - mAnchorView = anchorView; - - menu.addMenuPresenter(this); - } - - public void setAnchorView(View anchor) { - mAnchorView = anchor; - } - - public void setForceShowIcon(boolean forceShow) { - mForceShowIcon = forceShow; - } - - public void show() { - if (!tryShow()) { - throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor"); - } - } - - public boolean tryShow() { - mPopup = new IcsListPopupWindow(mContext, null, R.attr.popupMenuStyle); - mPopup.setOnDismissListener(this); - mPopup.setOnItemClickListener(this); - - mAdapter = new MenuAdapter(mMenu); - mPopup.setAdapter(mAdapter); - mPopup.setModal(true); - - View anchor = mAnchorView; - if (anchor != null) { - final boolean addGlobalListener = mTreeObserver == null; - mTreeObserver = anchor.getViewTreeObserver(); // Refresh to latest - if (addGlobalListener) mTreeObserver.addOnGlobalLayoutListener(this); - ((View_HasStateListenerSupport)anchor).addOnAttachStateChangeListener(this); - mPopup.setAnchorView(anchor); - } else { - return false; - } - - mPopup.setContentWidth(Math.min(measureContentWidth(mAdapter), mPopupMaxWidth)); - mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); - mPopup.show(); - mPopup.getListView().setOnKeyListener(this); - return true; - } - - public void dismiss() { - if (isShowing()) { - mPopup.dismiss(); - } - } - - public void onDismiss() { - mPopup = null; - mMenu.close(); - if (mTreeObserver != null) { - if (!mTreeObserver.isAlive()) mTreeObserver = mAnchorView.getViewTreeObserver(); - mTreeObserver.removeGlobalOnLayoutListener(this); - mTreeObserver = null; - } - ((View_HasStateListenerSupport)mAnchorView).removeOnAttachStateChangeListener(this); - } - - public boolean isShowing() { - return mPopup != null && mPopup.isShowing(); - } - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - MenuAdapter adapter = mAdapter; - adapter.mAdapterMenu.performItemAction(adapter.getItem(position), 0); - } - - public boolean onKey(View v, int keyCode, KeyEvent event) { - if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) { - dismiss(); - return true; - } - return false; - } - - private int measureContentWidth(ListAdapter adapter) { - // Menus don't tend to be long, so this is more sane than it looks. - int width = 0; - View itemView = null; - int itemType = 0; - final int widthMeasureSpec = - MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - final int heightMeasureSpec = - MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - final int count = adapter.getCount(); - for (int i = 0; i < count; i++) { - final int positionType = adapter.getItemViewType(i); - if (positionType != itemType) { - itemType = positionType; - itemView = null; - } - if (mMeasureParent == null) { - mMeasureParent = new FrameLayout(mContext); - } - itemView = adapter.getView(i, itemView, mMeasureParent); - itemView.measure(widthMeasureSpec, heightMeasureSpec); - width = Math.max(width, itemView.getMeasuredWidth()); - } - return width; - } - - @Override - public void onGlobalLayout() { - if (isShowing()) { - final View anchor = mAnchorView; - if (anchor == null || !anchor.isShown()) { - dismiss(); - } else if (isShowing()) { - // Recompute window size and position - mPopup.show(); - } - } - } - - @Override - public void onViewAttachedToWindow(View v) { - } - - @Override - public void onViewDetachedFromWindow(View v) { - if (mTreeObserver != null) { - if (!mTreeObserver.isAlive()) mTreeObserver = v.getViewTreeObserver(); - mTreeObserver.removeGlobalOnLayoutListener(this); - } - ((View_HasStateListenerSupport)v).removeOnAttachStateChangeListener(this); - } - - @Override - public void initForMenu(Context context, MenuBuilder menu) { - // Don't need to do anything; we added as a presenter in the constructor. - } - - @Override - public MenuView getMenuView(ViewGroup root) { - throw new UnsupportedOperationException("MenuPopupHelpers manage their own views"); - } - - @Override - public void updateMenuView(boolean cleared) { - if (mAdapter != null) mAdapter.notifyDataSetChanged(); - } - - @Override - public void setCallback(Callback cb) { - mPresenterCallback = cb; - } - - @Override - public boolean onSubMenuSelected(SubMenuBuilder subMenu) { - if (subMenu.hasVisibleItems()) { - MenuPopupHelper subPopup = new MenuPopupHelper(mContext, subMenu, mAnchorView, false); - subPopup.setCallback(mPresenterCallback); - - boolean preserveIconSpacing = false; - final int count = subMenu.size(); - for (int i = 0; i < count; i++) { - MenuItem childItem = subMenu.getItem(i); - if (childItem.isVisible() && childItem.getIcon() != null) { - preserveIconSpacing = true; - break; - } - } - subPopup.setForceShowIcon(preserveIconSpacing); - - if (subPopup.tryShow()) { - if (mPresenterCallback != null) { - mPresenterCallback.onOpenSubMenu(subMenu); - } - return true; - } - } - return false; - } - - @Override - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - // Only care about the (sub)menu we're presenting. - if (menu != mMenu) return; - - dismiss(); - if (mPresenterCallback != null) { - mPresenterCallback.onCloseMenu(menu, allMenusAreClosing); - } - } - - @Override - public boolean flagActionItems() { - return false; - } - - public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { - return false; - } - - public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { - return false; - } - - @Override - public int getId() { - return 0; - } - - @Override - public Parcelable onSaveInstanceState() { - return null; - } - - @Override - public void onRestoreInstanceState(Parcelable state) { - } - - private class MenuAdapter extends BaseAdapter { - private MenuBuilder mAdapterMenu; - private int mExpandedIndex = -1; - - public MenuAdapter(MenuBuilder menu) { - mAdapterMenu = menu; - registerDataSetObserver(new ExpandedIndexObserver()); - findExpandedIndex(); - } - - public int getCount() { - ArrayList items = mOverflowOnly ? - mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems(); - if (mExpandedIndex < 0) { - return items.size(); - } - return items.size() - 1; - } - - public MenuItemImpl getItem(int position) { - ArrayList items = mOverflowOnly ? - mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems(); - if (mExpandedIndex >= 0 && position >= mExpandedIndex) { - position++; - } - return items.get(position); - } - - public long getItemId(int position) { - // Since a menu item's ID is optional, we'll use the position as an - // ID for the item in the AdapterView - return position; - } - - public View getView(int position, View convertView, ViewGroup parent) { - if (convertView == null) { - convertView = mInflater.inflate(ITEM_LAYOUT, parent, false); - } - - MenuView.ItemView itemView = (MenuView.ItemView) convertView; - if (mForceShowIcon) { - ((ListMenuItemView) convertView).setForceShowIcon(true); - } - itemView.initialize(getItem(position), 0); - return convertView; - } - - void findExpandedIndex() { - final MenuItemImpl expandedItem = mMenu.getExpandedItem(); - if (expandedItem != null) { - final ArrayList items = mMenu.getNonActionItems(); - final int count = items.size(); - for (int i = 0; i < count; i++) { - final MenuItemImpl item = items.get(i); - if (item == expandedItem) { - mExpandedIndex = i; - return; - } - } - } - mExpandedIndex = -1; - } - } - - private class ExpandedIndexObserver extends DataSetObserver { - @Override - public void onChanged() { - mAdapter.findExpandedIndex(); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPresenter.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPresenter.java deleted file mode 100644 index c3f35472..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPresenter.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import android.content.Context; -import android.os.Parcelable; -import android.view.ViewGroup; - -/** - * A MenuPresenter is responsible for building views for a Menu object. - * It takes over some responsibility from the old style monolithic MenuBuilder class. - */ -public interface MenuPresenter { - /** - * Called by menu implementation to notify another component of open/close events. - */ - public interface Callback { - /** - * Called when a menu is closing. - * @param menu - * @param allMenusAreClosing - */ - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing); - - /** - * Called when a submenu opens. Useful for notifying the application - * of menu state so that it does not attempt to hide the action bar - * while a submenu is open or similar. - * - * @param subMenu Submenu currently being opened - * @return true if the Callback will handle presenting the submenu, false if - * the presenter should attempt to do so. - */ - public boolean onOpenSubMenu(MenuBuilder subMenu); - } - - /** - * Initialize this presenter for the given context and menu. - * This method is called by MenuBuilder when a presenter is - * added. See {@link MenuBuilder#addMenuPresenter(MenuPresenter)} - * - * @param context Context for this presenter; used for view creation and resource management - * @param menu Menu to host - */ - public void initForMenu(Context context, MenuBuilder menu); - - /** - * Retrieve a MenuView to display the menu specified in - * {@link #initForMenu(Context, Menu)}. - * - * @param root Intended parent of the MenuView. - * @return A freshly created MenuView. - */ - public MenuView getMenuView(ViewGroup root); - - /** - * Update the menu UI in response to a change. Called by - * MenuBuilder during the normal course of operation. - * - * @param cleared true if the menu was entirely cleared - */ - public void updateMenuView(boolean cleared); - - /** - * Set a callback object that will be notified of menu events - * related to this specific presentation. - * @param cb Callback that will be notified of future events - */ - public void setCallback(Callback cb); - - /** - * Called by Menu implementations to indicate that a submenu item - * has been selected. An active Callback should be notified, and - * if applicable the presenter should present the submenu. - * - * @param subMenu SubMenu being opened - * @return true if the the event was handled, false otherwise. - */ - public boolean onSubMenuSelected(SubMenuBuilder subMenu); - - /** - * Called by Menu implementations to indicate that a menu or submenu is - * closing. Presenter implementations should close the representation - * of the menu indicated as necessary and notify a registered callback. - * - * @param menu Menu or submenu that is closing. - * @param allMenusAreClosing True if all associated menus are closing. - */ - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing); - - /** - * Called by Menu implementations to flag items that will be shown as actions. - * @return true if this presenter changed the action status of any items. - */ - public boolean flagActionItems(); - - /** - * Called when a menu item with a collapsable action view should expand its action view. - * - * @param menu Menu containing the item to be expanded - * @param item Item to be expanded - * @return true if this presenter expanded the action view, false otherwise. - */ - public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item); - - /** - * Called when a menu item with a collapsable action view should collapse its action view. - * - * @param menu Menu containing the item to be collapsed - * @param item Item to be collapsed - * @return true if this presenter collapsed the action view, false otherwise. - */ - public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item); - - /** - * Returns an ID for determining how to save/restore instance state. - * @return a valid ID value. - */ - public int getId(); - - /** - * Returns a Parcelable describing the current state of the presenter. - * It will be passed to the {@link #onRestoreInstanceState(Parcelable)} - * method of the presenter sharing the same ID later. - * @return The saved instance state - */ - public Parcelable onSaveInstanceState(); - - /** - * Supplies the previously saved instance state to be restored. - * @param state The previously saved instance state - */ - public void onRestoreInstanceState(Parcelable state); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuView.java deleted file mode 100644 index 323ba2d8..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuView.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import android.graphics.drawable.Drawable; - -/** - * Minimal interface for a menu view. {@link #initialize(MenuBuilder)} must be called for the - * menu to be functional. - * - * @hide - */ -public interface MenuView { - /** - * Initializes the menu to the given menu. This should be called after the - * view is inflated. - * - * @param menu The menu that this MenuView should display. - */ - public void initialize(MenuBuilder menu); - - /** - * Returns the default animations to be used for this menu when entering/exiting. - * @return A resource ID for the default animations to be used for this menu. - */ - public int getWindowAnimations(); - - /** - * Minimal interface for a menu item view. {@link #initialize(MenuItemImpl, int)} must be called - * for the item to be functional. - */ - public interface ItemView { - /** - * Initializes with the provided MenuItemData. This should be called after the view is - * inflated. - * @param itemData The item that this ItemView should display. - * @param menuType The type of this menu, one of - * {@link MenuBuilder#TYPE_ICON}, {@link MenuBuilder#TYPE_EXPANDED}, - * {@link MenuBuilder#TYPE_DIALOG}). - */ - public void initialize(MenuItemImpl itemData, int menuType); - - /** - * Gets the item data that this view is displaying. - * @return the item data, or null if there is not one - */ - public MenuItemImpl getItemData(); - - /** - * Sets the title of the item view. - * @param title The title to set. - */ - public void setTitle(CharSequence title); - - /** - * Sets the enabled state of the item view. - * @param enabled Whether the item view should be enabled. - */ - public void setEnabled(boolean enabled); - - /** - * Displays the checkbox for the item view. This does not ensure the item view will be - * checked, for that use {@link #setChecked}. - * @param checkable Whether to display the checkbox or to hide it - */ - public void setCheckable(boolean checkable); - - /** - * Checks the checkbox for the item view. If the checkbox is hidden, it will NOT be - * made visible, call {@link #setCheckable(boolean)} for that. - * @param checked Whether the checkbox should be checked - */ - public void setChecked(boolean checked); - - /** - * Sets the shortcut for the item. - * @param showShortcut Whether a shortcut should be shown(if false, the value of - * shortcutKey should be ignored). - * @param shortcutKey The shortcut key that should be shown on the ItemView. - */ - public void setShortcut(boolean showShortcut, char shortcutKey); - - /** - * Set the icon of this item view. - * @param icon The icon of this item. null to hide the icon. - */ - public void setIcon(Drawable icon); - - /** - * Whether this item view prefers displaying the condensed title rather - * than the normal title. If a condensed title is not available, the - * normal title will be used. - * - * @return Whether this item view prefers displaying the condensed - * title. - */ - public boolean prefersCondensedTitle(); - - /** - * Whether this item view shows an icon. - * - * @return Whether this item view shows an icon. - */ - public boolean showsIcon(); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuWrapper.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuWrapper.java deleted file mode 100644 index 64fc4aea..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuWrapper.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.actionbarsherlock.internal.view.menu; - -import java.util.WeakHashMap; -import android.content.ComponentName; -import android.content.Intent; -import android.view.KeyEvent; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -public class MenuWrapper implements Menu { - private final android.view.Menu mNativeMenu; - - private final WeakHashMap mNativeMap = - new WeakHashMap(); - - - public MenuWrapper(android.view.Menu nativeMenu) { - mNativeMenu = nativeMenu; - } - - public android.view.Menu unwrap() { - return mNativeMenu; - } - - private MenuItem addInternal(android.view.MenuItem nativeItem) { - MenuItem item = new MenuItemWrapper(nativeItem); - mNativeMap.put(nativeItem, item); - return item; - } - - @Override - public MenuItem add(CharSequence title) { - return addInternal(mNativeMenu.add(title)); - } - - @Override - public MenuItem add(int titleRes) { - return addInternal(mNativeMenu.add(titleRes)); - } - - @Override - public MenuItem add(int groupId, int itemId, int order, CharSequence title) { - return addInternal(mNativeMenu.add(groupId, itemId, order, title)); - } - - @Override - public MenuItem add(int groupId, int itemId, int order, int titleRes) { - return addInternal(mNativeMenu.add(groupId, itemId, order, titleRes)); - } - - private SubMenu addInternal(android.view.SubMenu nativeSubMenu) { - SubMenu subMenu = new SubMenuWrapper(nativeSubMenu); - android.view.MenuItem nativeItem = nativeSubMenu.getItem(); - MenuItem item = subMenu.getItem(); - mNativeMap.put(nativeItem, item); - return subMenu; - } - - @Override - public SubMenu addSubMenu(CharSequence title) { - return addInternal(mNativeMenu.addSubMenu(title)); - } - - @Override - public SubMenu addSubMenu(int titleRes) { - return addInternal(mNativeMenu.addSubMenu(titleRes)); - } - - @Override - public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { - return addInternal(mNativeMenu.addSubMenu(groupId, itemId, order, title)); - } - - @Override - public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { - return addInternal(mNativeMenu.addSubMenu(groupId, itemId, order, titleRes)); - } - - @Override - public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { - android.view.MenuItem[] nativeOutItems = new android.view.MenuItem[outSpecificItems.length]; - int result = mNativeMenu.addIntentOptions(groupId, itemId, order, caller, specifics, intent, flags, nativeOutItems); - for (int i = 0, length = outSpecificItems.length; i < length; i++) { - outSpecificItems[i] = new MenuItemWrapper(nativeOutItems[i]); - } - return result; - } - - @Override - public void removeItem(int id) { - mNativeMenu.removeItem(id); - } - - @Override - public void removeGroup(int groupId) { - mNativeMenu.removeGroup(groupId); - } - - @Override - public void clear() { - mNativeMap.clear(); - mNativeMenu.clear(); - } - - @Override - public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { - mNativeMenu.setGroupCheckable(group, checkable, exclusive); - } - - @Override - public void setGroupVisible(int group, boolean visible) { - mNativeMenu.setGroupVisible(group, visible); - } - - @Override - public void setGroupEnabled(int group, boolean enabled) { - mNativeMenu.setGroupEnabled(group, enabled); - } - - @Override - public boolean hasVisibleItems() { - return mNativeMenu.hasVisibleItems(); - } - - @Override - public MenuItem findItem(int id) { - android.view.MenuItem nativeItem = mNativeMenu.findItem(id); - return findItem(nativeItem); - } - - public MenuItem findItem(android.view.MenuItem nativeItem) { - if (nativeItem == null) { - return null; - } - - MenuItem wrapped = mNativeMap.get(nativeItem); - if (wrapped != null) { - return wrapped; - } - - return addInternal(nativeItem); - } - - @Override - public int size() { - return mNativeMenu.size(); - } - - @Override - public MenuItem getItem(int index) { - android.view.MenuItem nativeItem = mNativeMenu.getItem(index); - return findItem(nativeItem); - } - - @Override - public void close() { - mNativeMenu.close(); - } - - @Override - public boolean performShortcut(int keyCode, KeyEvent event, int flags) { - return mNativeMenu.performShortcut(keyCode, event, flags); - } - - @Override - public boolean isShortcutKey(int keyCode, KeyEvent event) { - return mNativeMenu.isShortcutKey(keyCode, event); - } - - @Override - public boolean performIdentifierAction(int id, int flags) { - return mNativeMenu.performIdentifierAction(id, flags); - } - - @Override - public void setQwertyMode(boolean isQwerty) { - mNativeMenu.setQwertyMode(isQwerty); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.java deleted file mode 100644 index 6679cf38..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.view.menu; - -import android.content.Context; -import android.graphics.drawable.Drawable; -import android.view.View; - -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -/** - * The model for a sub menu, which is an extension of the menu. Most methods are proxied to - * the parent menu. - */ -public class SubMenuBuilder extends MenuBuilder implements SubMenu { - private MenuBuilder mParentMenu; - private MenuItemImpl mItem; - - public SubMenuBuilder(Context context, MenuBuilder parentMenu, MenuItemImpl item) { - super(context); - - mParentMenu = parentMenu; - mItem = item; - } - - @Override - public void setQwertyMode(boolean isQwerty) { - mParentMenu.setQwertyMode(isQwerty); - } - - @Override - public boolean isQwertyMode() { - return mParentMenu.isQwertyMode(); - } - - @Override - public void setShortcutsVisible(boolean shortcutsVisible) { - mParentMenu.setShortcutsVisible(shortcutsVisible); - } - - @Override - public boolean isShortcutsVisible() { - return mParentMenu.isShortcutsVisible(); - } - - public Menu getParentMenu() { - return mParentMenu; - } - - public MenuItem getItem() { - return mItem; - } - - @Override - public void setCallback(Callback callback) { - mParentMenu.setCallback(callback); - } - - @Override - public MenuBuilder getRootMenu() { - return mParentMenu; - } - - @Override - boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) { - return super.dispatchMenuItemSelected(menu, item) || - mParentMenu.dispatchMenuItemSelected(menu, item); - } - - public SubMenu setIcon(Drawable icon) { - mItem.setIcon(icon); - return this; - } - - public SubMenu setIcon(int iconRes) { - mItem.setIcon(iconRes); - return this; - } - - public SubMenu setHeaderIcon(Drawable icon) { - return (SubMenu) super.setHeaderIconInt(icon); - } - - public SubMenu setHeaderIcon(int iconRes) { - return (SubMenu) super.setHeaderIconInt(iconRes); - } - - public SubMenu setHeaderTitle(CharSequence title) { - return (SubMenu) super.setHeaderTitleInt(title); - } - - public SubMenu setHeaderTitle(int titleRes) { - return (SubMenu) super.setHeaderTitleInt(titleRes); - } - - public SubMenu setHeaderView(View view) { - return (SubMenu) super.setHeaderViewInt(view); - } - - @Override - public boolean expandItemActionView(MenuItemImpl item) { - return mParentMenu.expandItemActionView(item); - } - - @Override - public boolean collapseItemActionView(MenuItemImpl item) { - return mParentMenu.collapseItemActionView(item); - } - - @Override - public String getActionViewStatesKey() { - final int itemId = mItem != null ? mItem.getItemId() : 0; - if (itemId == 0) { - return null; - } - return super.getActionViewStatesKey() + ":" + itemId; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.java deleted file mode 100644 index 7d307acb..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.actionbarsherlock.internal.view.menu; - -import android.graphics.drawable.Drawable; -import android.view.View; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.SubMenu; - -public class SubMenuWrapper extends MenuWrapper implements SubMenu { - private final android.view.SubMenu mNativeSubMenu; - private MenuItem mItem = null; - - public SubMenuWrapper(android.view.SubMenu nativeSubMenu) { - super(nativeSubMenu); - mNativeSubMenu = nativeSubMenu; - } - - - @Override - public SubMenu setHeaderTitle(int titleRes) { - mNativeSubMenu.setHeaderTitle(titleRes); - return this; - } - - @Override - public SubMenu setHeaderTitle(CharSequence title) { - mNativeSubMenu.setHeaderTitle(title); - return this; - } - - @Override - public SubMenu setHeaderIcon(int iconRes) { - mNativeSubMenu.setHeaderIcon(iconRes); - return this; - } - - @Override - public SubMenu setHeaderIcon(Drawable icon) { - mNativeSubMenu.setHeaderIcon(icon); - return this; - } - - @Override - public SubMenu setHeaderView(View view) { - mNativeSubMenu.setHeaderView(view); - return this; - } - - @Override - public void clearHeader() { - mNativeSubMenu.clearHeader(); - } - - @Override - public SubMenu setIcon(int iconRes) { - mNativeSubMenu.setIcon(iconRes); - return this; - } - - @Override - public SubMenu setIcon(Drawable icon) { - mNativeSubMenu.setIcon(icon); - return this; - } - - @Override - public MenuItem getItem() { - if (mItem == null) { - mItem = new MenuItemWrapper(mNativeSubMenu.getItem()); - } - return mItem; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/AbsActionBarView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/AbsActionBarView.java deleted file mode 100644 index 3a4a4467..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/AbsActionBarView.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.content.res.Configuration; -import android.content.res.TypedArray; -import android.os.Build; -import android.util.AttributeSet; -import android.view.View; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.Interpolator; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; -import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; -import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; -import com.actionbarsherlock.internal.nineoldandroids.view.NineViewGroup; -import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; -import com.actionbarsherlock.internal.view.menu.ActionMenuView; - -import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; - -public abstract class AbsActionBarView extends NineViewGroup { - protected ActionMenuView mMenuView; - protected ActionMenuPresenter mActionMenuPresenter; - protected ActionBarContainer mSplitView; - protected boolean mSplitActionBar; - protected boolean mSplitWhenNarrow; - protected int mContentHeight; - - final Context mContext; - - protected Animator mVisibilityAnim; - protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); - - private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); - - private static final int FADE_DURATION = 200; - - public AbsActionBarView(Context context) { - super(context); - mContext = context; - } - - public AbsActionBarView(Context context, AttributeSet attrs) { - super(context, attrs); - mContext = context; - } - - public AbsActionBarView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mContext = context; - } - - /* - * Must be public so we can dispatch pre-2.2 via ActionBarImpl. - */ - @Override - public void onConfigurationChanged(Configuration newConfig) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { - super.onConfigurationChanged(newConfig); - } else if (mMenuView != null) { - mMenuView.onConfigurationChanged(newConfig); - } - - // Action bar can change size on configuration changes. - // Reread the desired height from the theme-specified style. - TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, - R.attr.actionBarStyle, 0); - setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); - a.recycle(); - if (mSplitWhenNarrow) { - setSplitActionBar(getResources_getBoolean(getContext(), - R.bool.abs__split_action_bar_is_narrow)); - } - if (mActionMenuPresenter != null) { - mActionMenuPresenter.onConfigurationChanged(newConfig); - } - } - - /** - * Sets whether the bar should be split right now, no questions asked. - * @param split true if the bar should split - */ - public void setSplitActionBar(boolean split) { - mSplitActionBar = split; - } - - /** - * Sets whether the bar should split if we enter a narrow screen configuration. - * @param splitWhenNarrow true if the bar should check to split after a config change - */ - public void setSplitWhenNarrow(boolean splitWhenNarrow) { - mSplitWhenNarrow = splitWhenNarrow; - } - - public void setContentHeight(int height) { - mContentHeight = height; - requestLayout(); - } - - public int getContentHeight() { - return mContentHeight; - } - - public void setSplitView(ActionBarContainer splitView) { - mSplitView = splitView; - } - - /** - * @return Current visibility or if animating, the visibility being animated to. - */ - public int getAnimatedVisibility() { - if (mVisibilityAnim != null) { - return mVisAnimListener.mFinalVisibility; - } - return getVisibility(); - } - - public void animateToVisibility(int visibility) { - if (mVisibilityAnim != null) { - mVisibilityAnim.cancel(); - } - if (visibility == VISIBLE) { - if (getVisibility() != VISIBLE) { - setAlpha(0); - if (mSplitView != null && mMenuView != null) { - mMenuView.setAlpha(0); - } - } - ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); - anim.setDuration(FADE_DURATION); - anim.setInterpolator(sAlphaInterpolator); - if (mSplitView != null && mMenuView != null) { - AnimatorSet set = new AnimatorSet(); - ObjectAnimator splitAnim = ObjectAnimator.ofFloat(mMenuView, "alpha", 1); - splitAnim.setDuration(FADE_DURATION); - set.addListener(mVisAnimListener.withFinalVisibility(visibility)); - set.play(anim).with(splitAnim); - set.start(); - } else { - anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); - anim.start(); - } - } else { - ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); - anim.setDuration(FADE_DURATION); - anim.setInterpolator(sAlphaInterpolator); - if (mSplitView != null && mMenuView != null) { - AnimatorSet set = new AnimatorSet(); - ObjectAnimator splitAnim = ObjectAnimator.ofFloat(mMenuView, "alpha", 0); - splitAnim.setDuration(FADE_DURATION); - set.addListener(mVisAnimListener.withFinalVisibility(visibility)); - set.play(anim).with(splitAnim); - set.start(); - } else { - anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); - anim.start(); - } - } - } - - @Override - public void setVisibility(int visibility) { - if (mVisibilityAnim != null) { - mVisibilityAnim.end(); - } - super.setVisibility(visibility); - } - - public boolean showOverflowMenu() { - if (mActionMenuPresenter != null) { - return mActionMenuPresenter.showOverflowMenu(); - } - return false; - } - - public void postShowOverflowMenu() { - post(new Runnable() { - public void run() { - showOverflowMenu(); - } - }); - } - - public boolean hideOverflowMenu() { - if (mActionMenuPresenter != null) { - return mActionMenuPresenter.hideOverflowMenu(); - } - return false; - } - - public boolean isOverflowMenuShowing() { - if (mActionMenuPresenter != null) { - return mActionMenuPresenter.isOverflowMenuShowing(); - } - return false; - } - - public boolean isOverflowReserved() { - return mActionMenuPresenter != null && mActionMenuPresenter.isOverflowReserved(); - } - - public void dismissPopupMenus() { - if (mActionMenuPresenter != null) { - mActionMenuPresenter.dismissPopupMenus(); - } - } - - protected int measureChildView(View child, int availableWidth, int childSpecHeight, - int spacing) { - child.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), - childSpecHeight); - - availableWidth -= child.getMeasuredWidth(); - availableWidth -= spacing; - - return Math.max(0, availableWidth); - } - - protected int positionChild(View child, int x, int y, int contentHeight) { - int childWidth = child.getMeasuredWidth(); - int childHeight = child.getMeasuredHeight(); - int childTop = y + (contentHeight - childHeight) / 2; - - child.layout(x, childTop, x + childWidth, childTop + childHeight); - - return childWidth; - } - - protected int positionChildInverse(View child, int x, int y, int contentHeight) { - int childWidth = child.getMeasuredWidth(); - int childHeight = child.getMeasuredHeight(); - int childTop = y + (contentHeight - childHeight) / 2; - - child.layout(x - childWidth, childTop, x, childTop + childHeight); - - return childWidth; - } - - protected class VisibilityAnimListener implements Animator.AnimatorListener { - private boolean mCanceled = false; - int mFinalVisibility; - - public VisibilityAnimListener withFinalVisibility(int visibility) { - mFinalVisibility = visibility; - return this; - } - - @Override - public void onAnimationStart(Animator animation) { - setVisibility(VISIBLE); - mVisibilityAnim = animation; - mCanceled = false; - } - - @Override - public void onAnimationEnd(Animator animation) { - if (mCanceled) return; - - mVisibilityAnim = null; - setVisibility(mFinalVisibility); - if (mSplitView != null && mMenuView != null) { - mMenuView.setVisibility(mFinalVisibility); - } - } - - @Override - public void onAnimationCancel(Animator animation) { - mCanceled = true; - } - - @Override - public void onAnimationRepeat(Animator animation) { - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContainer.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContainer.java deleted file mode 100644 index 5e5aa286..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContainer.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout; - -/** - * This class acts as a container for the action bar view and action mode context views. - * It applies special styles as needed to help handle animated transitions between them. - * @hide - */ -public class ActionBarContainer extends NineFrameLayout { - private boolean mIsTransitioning; - private View mTabContainer; - private ActionBarView mActionBarView; - - private Drawable mBackground; - private Drawable mStackedBackground; - private Drawable mSplitBackground; - private boolean mIsSplit; - private boolean mIsStacked; - - public ActionBarContainer(Context context) { - this(context, null); - } - - public ActionBarContainer(Context context, AttributeSet attrs) { - super(context, attrs); - - setBackgroundDrawable(null); - - TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SherlockActionBar); - mBackground = a.getDrawable(R.styleable.SherlockActionBar_background); - mStackedBackground = a.getDrawable( - R.styleable.SherlockActionBar_backgroundStacked); - - if (getId() == R.id.abs__split_action_bar) { - mIsSplit = true; - mSplitBackground = a.getDrawable( - R.styleable.SherlockActionBar_backgroundSplit); - } - a.recycle(); - - setWillNotDraw(mIsSplit ? mSplitBackground == null : - mBackground == null && mStackedBackground == null); - } - - @Override - public void onFinishInflate() { - super.onFinishInflate(); - mActionBarView = (ActionBarView) findViewById(R.id.abs__action_bar); - } - - public void setPrimaryBackground(Drawable bg) { - mBackground = bg; - invalidate(); - } - - public void setStackedBackground(Drawable bg) { - mStackedBackground = bg; - invalidate(); - } - - public void setSplitBackground(Drawable bg) { - mSplitBackground = bg; - invalidate(); - } - - /** - * Set the action bar into a "transitioning" state. While transitioning - * the bar will block focus and touch from all of its descendants. This - * prevents the user from interacting with the bar while it is animating - * in or out. - * - * @param isTransitioning true if the bar is currently transitioning, false otherwise. - */ - public void setTransitioning(boolean isTransitioning) { - mIsTransitioning = isTransitioning; - setDescendantFocusability(isTransitioning ? FOCUS_BLOCK_DESCENDANTS - : FOCUS_AFTER_DESCENDANTS); - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - return mIsTransitioning || super.onInterceptTouchEvent(ev); - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - super.onTouchEvent(ev); - - // An action bar always eats touch events. - return true; - } - - @Override - public boolean onHoverEvent(MotionEvent ev) { - super.onHoverEvent(ev); - - // An action bar always eats hover events. - return true; - } - - public void setTabContainer(ScrollingTabContainerView tabView) { - if (mTabContainer != null) { - removeView(mTabContainer); - } - mTabContainer = tabView; - if (tabView != null) { - addView(tabView); - final ViewGroup.LayoutParams lp = tabView.getLayoutParams(); - lp.width = LayoutParams.MATCH_PARENT; - lp.height = LayoutParams.WRAP_CONTENT; - tabView.setAllowCollapse(false); - } - } - - public View getTabContainer() { - return mTabContainer; - } - - @Override - public void onDraw(Canvas canvas) { - if (getWidth() == 0 || getHeight() == 0) { - return; - } - - if (mIsSplit) { - if (mSplitBackground != null) mSplitBackground.draw(canvas); - } else { - if (mBackground != null) { - mBackground.draw(canvas); - } - if (mStackedBackground != null && mIsStacked) { - mStackedBackground.draw(canvas); - } - } - } - - //This causes the animation reflection to fail on pre-HC platforms - //@Override - //public android.view.ActionMode startActionModeForChild(View child, android.view.ActionMode.Callback callback) { - // // No starting an action mode for an action bar child! (Where would it go?) - // return null; - //} - - @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - if (mActionBarView == null) return; - - final LayoutParams lp = (LayoutParams) mActionBarView.getLayoutParams(); - final int actionBarViewHeight = mActionBarView.isCollapsed() ? 0 : - mActionBarView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; - - if (mTabContainer != null && mTabContainer.getVisibility() != GONE) { - final int mode = MeasureSpec.getMode(heightMeasureSpec); - if (mode == MeasureSpec.AT_MOST) { - final int maxHeight = MeasureSpec.getSize(heightMeasureSpec); - setMeasuredDimension(getMeasuredWidth(), - Math.min(actionBarViewHeight + mTabContainer.getMeasuredHeight(), - maxHeight)); - } - } - } - - @Override - public void onLayout(boolean changed, int l, int t, int r, int b) { - super.onLayout(changed, l, t, r, b); - - final boolean hasTabs = mTabContainer != null && mTabContainer.getVisibility() != GONE; - - if (mTabContainer != null && mTabContainer.getVisibility() != GONE) { - final int containerHeight = getMeasuredHeight(); - final int tabHeight = mTabContainer.getMeasuredHeight(); - - if ((mActionBarView.getDisplayOptions() & ActionBar.DISPLAY_SHOW_HOME) == 0) { - // Not showing home, put tabs on top. - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - - if (child == mTabContainer) continue; - - if (!mActionBarView.isCollapsed()) { - child.offsetTopAndBottom(tabHeight); - } - } - mTabContainer.layout(l, 0, r, tabHeight); - } else { - mTabContainer.layout(l, containerHeight - tabHeight, r, containerHeight); - } - } - - boolean needsInvalidate = false; - if (mIsSplit) { - if (mSplitBackground != null) { - mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); - needsInvalidate = true; - } - } else { - if (mBackground != null) { - mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(), - mActionBarView.getRight(), mActionBarView.getBottom()); - needsInvalidate = true; - } - if ((mIsStacked = hasTabs && mStackedBackground != null)) { - mStackedBackground.setBounds(mTabContainer.getLeft(), mTabContainer.getTop(), - mTabContainer.getRight(), mTabContainer.getBottom()); - needsInvalidate = true; - } - } - - if (needsInvalidate) { - invalidate(); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContextView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContextView.java deleted file mode 100644 index 9ec250f3..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContextView.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.drawable.Drawable; -import android.text.TextUtils; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.accessibility.AccessibilityEvent; -import android.view.animation.DecelerateInterpolator; -import android.widget.LinearLayout; -import android.widget.TextView; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; -import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener; -import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; -import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; -import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; -import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; -import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; -import com.actionbarsherlock.internal.view.menu.ActionMenuView; -import com.actionbarsherlock.internal.view.menu.MenuBuilder; -import com.actionbarsherlock.view.ActionMode; - -/** - * @hide - */ -public class ActionBarContextView extends AbsActionBarView implements AnimatorListener { - //UNUSED private static final String TAG = "ActionBarContextView"; - - private CharSequence mTitle; - private CharSequence mSubtitle; - - private NineLinearLayout mClose; - private View mCustomView; - private LinearLayout mTitleLayout; - private TextView mTitleView; - private TextView mSubtitleView; - private int mTitleStyleRes; - private int mSubtitleStyleRes; - private Drawable mSplitBackground; - - private Animator mCurrentAnimation; - private boolean mAnimateInOnLayout; - private int mAnimationMode; - - private static final int ANIMATE_IDLE = 0; - private static final int ANIMATE_IN = 1; - private static final int ANIMATE_OUT = 2; - - public ActionBarContextView(Context context) { - this(context, null); - } - - public ActionBarContextView(Context context, AttributeSet attrs) { - this(context, attrs, R.attr.actionModeStyle); - } - - public ActionBarContextView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionMode, defStyle, 0); - setBackgroundDrawable(a.getDrawable( - R.styleable.SherlockActionMode_background)); - mTitleStyleRes = a.getResourceId( - R.styleable.SherlockActionMode_titleTextStyle, 0); - mSubtitleStyleRes = a.getResourceId( - R.styleable.SherlockActionMode_subtitleTextStyle, 0); - - mContentHeight = a.getLayoutDimension( - R.styleable.SherlockActionMode_height, 0); - - mSplitBackground = a.getDrawable( - R.styleable.SherlockActionMode_backgroundSplit); - - a.recycle(); - } - - @Override - public void onDetachedFromWindow() { - super.onDetachedFromWindow(); - if (mActionMenuPresenter != null) { - mActionMenuPresenter.hideOverflowMenu(); - mActionMenuPresenter.hideSubMenus(); - } - } - - @Override - public void setSplitActionBar(boolean split) { - if (mSplitActionBar != split) { - if (mActionMenuPresenter != null) { - // Mode is already active; move everything over and adjust the menu itself. - final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.MATCH_PARENT); - if (!split) { - mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); - mMenuView.setBackgroundDrawable(null); - final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); - if (oldParent != null) oldParent.removeView(mMenuView); - addView(mMenuView, layoutParams); - } else { - // Allow full screen width in split mode. - mActionMenuPresenter.setWidthLimit( - getContext().getResources().getDisplayMetrics().widthPixels, true); - // No limit to the item count; use whatever will fit. - mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); - // Span the whole width - layoutParams.width = LayoutParams.MATCH_PARENT; - layoutParams.height = mContentHeight; - mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); - mMenuView.setBackgroundDrawable(mSplitBackground); - final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); - if (oldParent != null) oldParent.removeView(mMenuView); - mSplitView.addView(mMenuView, layoutParams); - } - } - super.setSplitActionBar(split); - } - } - - public void setContentHeight(int height) { - mContentHeight = height; - } - - public void setCustomView(View view) { - if (mCustomView != null) { - removeView(mCustomView); - } - mCustomView = view; - if (mTitleLayout != null) { - removeView(mTitleLayout); - mTitleLayout = null; - } - if (view != null) { - addView(view); - } - requestLayout(); - } - - public void setTitle(CharSequence title) { - mTitle = title; - initTitle(); - } - - public void setSubtitle(CharSequence subtitle) { - mSubtitle = subtitle; - initTitle(); - } - - public CharSequence getTitle() { - return mTitle; - } - - public CharSequence getSubtitle() { - return mSubtitle; - } - - private void initTitle() { - if (mTitleLayout == null) { - LayoutInflater inflater = LayoutInflater.from(getContext()); - inflater.inflate(R.layout.abs__action_bar_title_item, this); - mTitleLayout = (LinearLayout) getChildAt(getChildCount() - 1); - mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); - mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); - if (mTitleStyleRes != 0) { - mTitleView.setTextAppearance(mContext, mTitleStyleRes); - } - if (mSubtitleStyleRes != 0) { - mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); - } - } - - mTitleView.setText(mTitle); - mSubtitleView.setText(mSubtitle); - - final boolean hasTitle = !TextUtils.isEmpty(mTitle); - final boolean hasSubtitle = !TextUtils.isEmpty(mSubtitle); - mSubtitleView.setVisibility(hasSubtitle ? VISIBLE : GONE); - mTitleLayout.setVisibility(hasTitle || hasSubtitle ? VISIBLE : GONE); - if (mTitleLayout.getParent() == null) { - addView(mTitleLayout); - } - } - - public void initForMode(final ActionMode mode) { - if (mClose == null) { - LayoutInflater inflater = LayoutInflater.from(mContext); - mClose = (NineLinearLayout)inflater.inflate(R.layout.abs__action_mode_close_item, this, false); - addView(mClose); - } else if (mClose.getParent() == null) { - addView(mClose); - } - - View closeButton = mClose.findViewById(R.id.abs__action_mode_close_button); - closeButton.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - mode.finish(); - } - }); - - final MenuBuilder menu = (MenuBuilder) mode.getMenu(); - if (mActionMenuPresenter != null) { - mActionMenuPresenter.dismissPopupMenus(); - } - mActionMenuPresenter = new ActionMenuPresenter(mContext); - mActionMenuPresenter.setReserveOverflow(true); - - final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.MATCH_PARENT); - if (!mSplitActionBar) { - menu.addMenuPresenter(mActionMenuPresenter); - mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); - mMenuView.setBackgroundDrawable(null); - addView(mMenuView, layoutParams); - } else { - // Allow full screen width in split mode. - mActionMenuPresenter.setWidthLimit( - getContext().getResources().getDisplayMetrics().widthPixels, true); - // No limit to the item count; use whatever will fit. - mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); - // Span the whole width - layoutParams.width = LayoutParams.MATCH_PARENT; - layoutParams.height = mContentHeight; - menu.addMenuPresenter(mActionMenuPresenter); - mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); - mMenuView.setBackgroundDrawable(mSplitBackground); - mSplitView.addView(mMenuView, layoutParams); - } - - mAnimateInOnLayout = true; - } - - public void closeMode() { - if (mAnimationMode == ANIMATE_OUT) { - // Called again during close; just finish what we were doing. - return; - } - if (mClose == null) { - killMode(); - return; - } - - finishAnimation(); - mAnimationMode = ANIMATE_OUT; - mCurrentAnimation = makeOutAnimation(); - mCurrentAnimation.start(); - } - - private void finishAnimation() { - final Animator a = mCurrentAnimation; - if (a != null) { - mCurrentAnimation = null; - a.end(); - } - } - - public void killMode() { - finishAnimation(); - removeAllViews(); - if (mSplitView != null) { - mSplitView.removeView(mMenuView); - } - mCustomView = null; - mMenuView = null; - mAnimateInOnLayout = false; - } - - @Override - public boolean showOverflowMenu() { - if (mActionMenuPresenter != null) { - return mActionMenuPresenter.showOverflowMenu(); - } - return false; - } - - @Override - public boolean hideOverflowMenu() { - if (mActionMenuPresenter != null) { - return mActionMenuPresenter.hideOverflowMenu(); - } - return false; - } - - @Override - public boolean isOverflowMenuShowing() { - if (mActionMenuPresenter != null) { - return mActionMenuPresenter.isOverflowMenuShowing(); - } - return false; - } - - @Override - protected ViewGroup.LayoutParams generateDefaultLayoutParams() { - // Used by custom views if they don't supply layout params. Everything else - // added to an ActionBarContextView should have them already. - return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); - } - - @Override - public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { - return new MarginLayoutParams(getContext(), attrs); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - final int widthMode = MeasureSpec.getMode(widthMeasureSpec); - if (widthMode != MeasureSpec.EXACTLY) { - throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + - "with android:layout_width=\"match_parent\" (or fill_parent)"); - } - - final int heightMode = MeasureSpec.getMode(heightMeasureSpec); - if (heightMode == MeasureSpec.UNSPECIFIED) { - throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + - "with android:layout_height=\"wrap_content\""); - } - - final int contentWidth = MeasureSpec.getSize(widthMeasureSpec); - - int maxHeight = mContentHeight > 0 ? - mContentHeight : MeasureSpec.getSize(heightMeasureSpec); - - final int verticalPadding = getPaddingTop() + getPaddingBottom(); - int availableWidth = contentWidth - getPaddingLeft() - getPaddingRight(); - final int height = maxHeight - verticalPadding; - final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); - - if (mClose != null) { - availableWidth = measureChildView(mClose, availableWidth, childSpecHeight, 0); - MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); - availableWidth -= lp.leftMargin + lp.rightMargin; - } - - if (mMenuView != null && mMenuView.getParent() == this) { - availableWidth = measureChildView(mMenuView, availableWidth, - childSpecHeight, 0); - } - - if (mTitleLayout != null && mCustomView == null) { - availableWidth = measureChildView(mTitleLayout, availableWidth, childSpecHeight, 0); - } - - if (mCustomView != null) { - ViewGroup.LayoutParams lp = mCustomView.getLayoutParams(); - final int customWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? - MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; - final int customWidth = lp.width >= 0 ? - Math.min(lp.width, availableWidth) : availableWidth; - final int customHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? - MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; - final int customHeight = lp.height >= 0 ? - Math.min(lp.height, height) : height; - mCustomView.measure(MeasureSpec.makeMeasureSpec(customWidth, customWidthMode), - MeasureSpec.makeMeasureSpec(customHeight, customHeightMode)); - } - - if (mContentHeight <= 0) { - int measuredHeight = 0; - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - View v = getChildAt(i); - int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; - if (paddedViewHeight > measuredHeight) { - measuredHeight = paddedViewHeight; - } - } - setMeasuredDimension(contentWidth, measuredHeight); - } else { - setMeasuredDimension(contentWidth, maxHeight); - } - } - - private Animator makeInAnimation() { - mClose.setTranslationX(-mClose.getWidth() - - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); - ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", 0); - buttonAnimator.setDuration(200); - buttonAnimator.addListener(this); - buttonAnimator.setInterpolator(new DecelerateInterpolator()); - - AnimatorSet set = new AnimatorSet(); - AnimatorSet.Builder b = set.play(buttonAnimator); - - if (mMenuView != null) { - final int count = mMenuView.getChildCount(); - if (count > 0) { - for (int i = count - 1, j = 0; i >= 0; i--, j++) { - AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); - child.setScaleY(0); - ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0, 1); - a.setDuration(100); - a.setStartDelay(j * 70); - b.with(a); - } - } - } - - return set; - } - - private Animator makeOutAnimation() { - ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", - -mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); - buttonAnimator.setDuration(200); - buttonAnimator.addListener(this); - buttonAnimator.setInterpolator(new DecelerateInterpolator()); - - AnimatorSet set = new AnimatorSet(); - AnimatorSet.Builder b = set.play(buttonAnimator); - - if (mMenuView != null) { - final int count = mMenuView.getChildCount(); - if (count > 0) { - for (int i = 0; i < 0; i++) { - AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); - child.setScaleY(0); - ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0); - a.setDuration(100); - a.setStartDelay(i * 70); - b.with(a); - } - } - } - - return set; - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - int x = getPaddingLeft(); - final int y = getPaddingTop(); - final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); - - if (mClose != null && mClose.getVisibility() != GONE) { - MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); - x += lp.leftMargin; - x += positionChild(mClose, x, y, contentHeight); - x += lp.rightMargin; - - if (mAnimateInOnLayout) { - mAnimationMode = ANIMATE_IN; - mCurrentAnimation = makeInAnimation(); - mCurrentAnimation.start(); - mAnimateInOnLayout = false; - } - } - - if (mTitleLayout != null && mCustomView == null) { - x += positionChild(mTitleLayout, x, y, contentHeight); - } - - if (mCustomView != null) { - x += positionChild(mCustomView, x, y, contentHeight); - } - - x = r - l - getPaddingRight(); - - if (mMenuView != null) { - x -= positionChildInverse(mMenuView, x, y, contentHeight); - } - } - - @Override - public void onAnimationStart(Animator animation) { - } - - @Override - public void onAnimationEnd(Animator animation) { - if (mAnimationMode == ANIMATE_OUT) { - killMode(); - } - mAnimationMode = ANIMATE_IDLE; - } - - @Override - public void onAnimationCancel(Animator animation) { - } - - @Override - public void onAnimationRepeat(Animator animation) { - } - - @Override - public boolean shouldDelayChildPressedState() { - return false; - } - - @Override - public void onInitializeAccessibilityEvent(AccessibilityEvent event) { - if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { - // Action mode started - //TODO event.setSource(this); - event.setClassName(getClass().getName()); - event.setPackageName(getContext().getPackageName()); - event.setContentDescription(mTitle); - } else { - //TODO super.onInitializeAccessibilityEvent(event); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarView.java deleted file mode 100644 index 4636de17..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarView.java +++ /dev/null @@ -1,1548 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.widget; - -import org.xmlpull.v1.XmlPullParser; -import android.app.Activity; -import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.content.res.AssetManager; -import android.content.res.Configuration; -import android.content.res.TypedArray; -import android.content.res.XmlResourceParser; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.os.Parcel; -import android.os.Parcelable; -import android.text.TextUtils; -import android.util.AttributeSet; -import android.util.Log; -import android.view.Gravity; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewParent; -import android.view.accessibility.AccessibilityEvent; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.SpinnerAdapter; -import android.widget.TextView; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.app.ActionBar.OnNavigationListener; -import com.actionbarsherlock.internal.ActionBarSherlockCompat; -import com.actionbarsherlock.internal.view.menu.ActionMenuItem; -import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; -import com.actionbarsherlock.internal.view.menu.ActionMenuView; -import com.actionbarsherlock.internal.view.menu.MenuBuilder; -import com.actionbarsherlock.internal.view.menu.MenuItemImpl; -import com.actionbarsherlock.internal.view.menu.MenuPresenter; -import com.actionbarsherlock.internal.view.menu.MenuView; -import com.actionbarsherlock.internal.view.menu.SubMenuBuilder; -import com.actionbarsherlock.view.CollapsibleActionView; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.Window; - -import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; - -/** - * @hide - */ -public class ActionBarView extends AbsActionBarView { - private static final String TAG = "ActionBarView"; - private static final boolean DEBUG = false; - - /** - * Display options applied by default - */ - public static final int DISPLAY_DEFAULT = 0; - - /** - * Display options that require re-layout as opposed to a simple invalidate - */ - private static final int DISPLAY_RELAYOUT_MASK = - ActionBar.DISPLAY_SHOW_HOME | - ActionBar.DISPLAY_USE_LOGO | - ActionBar.DISPLAY_HOME_AS_UP | - ActionBar.DISPLAY_SHOW_CUSTOM | - ActionBar.DISPLAY_SHOW_TITLE; - - private static final int DEFAULT_CUSTOM_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; - - private int mNavigationMode; - private int mDisplayOptions = -1; - private CharSequence mTitle; - private CharSequence mSubtitle; - private Drawable mIcon; - private Drawable mLogo; - - private HomeView mHomeLayout; - private HomeView mExpandedHomeLayout; - private LinearLayout mTitleLayout; - private TextView mTitleView; - private TextView mSubtitleView; - private View mTitleUpView; - - private IcsSpinner mSpinner; - private IcsLinearLayout mListNavLayout; - private ScrollingTabContainerView mTabScrollView; - private View mCustomNavView; - private IcsProgressBar mProgressView; - private IcsProgressBar mIndeterminateProgressView; - - private int mProgressBarPadding; - private int mItemPadding; - - private int mTitleStyleRes; - private int mSubtitleStyleRes; - private int mProgressStyle; - private int mIndeterminateProgressStyle; - - private boolean mUserTitle; - private boolean mIncludeTabs; - private boolean mIsCollapsable; - private boolean mIsCollapsed; - - private MenuBuilder mOptionsMenu; - - private ActionBarContextView mContextView; - - private ActionMenuItem mLogoNavItem; - - private SpinnerAdapter mSpinnerAdapter; - private OnNavigationListener mCallback; - - //UNUSED private Runnable mTabSelector; - - private ExpandedActionViewMenuPresenter mExpandedMenuPresenter; - View mExpandedActionView; - - Window.Callback mWindowCallback; - - @SuppressWarnings("rawtypes") - private final IcsAdapterView.OnItemSelectedListener mNavItemSelectedListener = - new IcsAdapterView.OnItemSelectedListener() { - public void onItemSelected(IcsAdapterView parent, View view, int position, long id) { - if (mCallback != null) { - mCallback.onNavigationItemSelected(position, id); - } - } - public void onNothingSelected(IcsAdapterView parent) { - // Do nothing - } - }; - - private final OnClickListener mExpandedActionViewUpListener = new OnClickListener() { - @Override - public void onClick(View v) { - final MenuItemImpl item = mExpandedMenuPresenter.mCurrentExpandedItem; - if (item != null) { - item.collapseActionView(); - } - } - }; - - private final OnClickListener mUpClickListener = new OnClickListener() { - public void onClick(View v) { - mWindowCallback.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, mLogoNavItem); - } - }; - - public ActionBarView(Context context, AttributeSet attrs) { - super(context, attrs); - - // Background is always provided by the container. - setBackgroundResource(0); - - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionBar, - R.attr.actionBarStyle, 0); - - ApplicationInfo appInfo = context.getApplicationInfo(); - PackageManager pm = context.getPackageManager(); - mNavigationMode = a.getInt(R.styleable.SherlockActionBar_navigationMode, - ActionBar.NAVIGATION_MODE_STANDARD); - mTitle = a.getText(R.styleable.SherlockActionBar_title); - mSubtitle = a.getText(R.styleable.SherlockActionBar_subtitle); - - mLogo = a.getDrawable(R.styleable.SherlockActionBar_logo); - if (mLogo == null) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { - if (context instanceof Activity) { - //Even though native methods existed in API 9 and 10 they don't work - //so just parse the manifest to look for the logo pre-Honeycomb - final int resId = loadLogoFromManifest((Activity) context); - if (resId != 0) { - mLogo = context.getResources().getDrawable(resId); - } - } - } else { - if (context instanceof Activity) { - try { - mLogo = pm.getActivityLogo(((Activity) context).getComponentName()); - } catch (NameNotFoundException e) { - Log.e(TAG, "Activity component name not found!", e); - } - } - if (mLogo == null) { - mLogo = appInfo.loadLogo(pm); - } - } - } - - mIcon = a.getDrawable(R.styleable.SherlockActionBar_icon); - if (mIcon == null) { - if (context instanceof Activity) { - try { - mIcon = pm.getActivityIcon(((Activity) context).getComponentName()); - } catch (NameNotFoundException e) { - Log.e(TAG, "Activity component name not found!", e); - } - } - if (mIcon == null) { - mIcon = appInfo.loadIcon(pm); - } - } - - final LayoutInflater inflater = LayoutInflater.from(context); - - final int homeResId = a.getResourceId( - R.styleable.SherlockActionBar_homeLayout, - R.layout.abs__action_bar_home); - - mHomeLayout = (HomeView) inflater.inflate(homeResId, this, false); - - mExpandedHomeLayout = (HomeView) inflater.inflate(homeResId, this, false); - mExpandedHomeLayout.setUp(true); - mExpandedHomeLayout.setOnClickListener(mExpandedActionViewUpListener); - mExpandedHomeLayout.setContentDescription(getResources().getText( - R.string.abs__action_bar_up_description)); - - mTitleStyleRes = a.getResourceId(R.styleable.SherlockActionBar_titleTextStyle, 0); - mSubtitleStyleRes = a.getResourceId(R.styleable.SherlockActionBar_subtitleTextStyle, 0); - mProgressStyle = a.getResourceId(R.styleable.SherlockActionBar_progressBarStyle, 0); - mIndeterminateProgressStyle = a.getResourceId( - R.styleable.SherlockActionBar_indeterminateProgressStyle, 0); - - mProgressBarPadding = a.getDimensionPixelOffset(R.styleable.SherlockActionBar_progressBarPadding, 0); - mItemPadding = a.getDimensionPixelOffset(R.styleable.SherlockActionBar_itemPadding, 0); - - setDisplayOptions(a.getInt(R.styleable.SherlockActionBar_displayOptions, DISPLAY_DEFAULT)); - - final int customNavId = a.getResourceId(R.styleable.SherlockActionBar_customNavigationLayout, 0); - if (customNavId != 0) { - mCustomNavView = inflater.inflate(customNavId, this, false); - mNavigationMode = ActionBar.NAVIGATION_MODE_STANDARD; - setDisplayOptions(mDisplayOptions | ActionBar.DISPLAY_SHOW_CUSTOM); - } - - mContentHeight = a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0); - - a.recycle(); - - mLogoNavItem = new ActionMenuItem(context, 0, android.R.id.home, 0, 0, mTitle); - mHomeLayout.setOnClickListener(mUpClickListener); - mHomeLayout.setClickable(true); - mHomeLayout.setFocusable(true); - } - - /** - * Attempt to programmatically load the logo from the manifest file of an - * activity by using an XML pull parser. This should allow us to read the - * logo attribute regardless of the platform it is being run on. - * - * @param activity Activity instance. - * @return Logo resource ID. - */ - private static int loadLogoFromManifest(Activity activity) { - int logo = 0; - try { - final String thisPackage = activity.getClass().getName(); - if (DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage); - - final String packageName = activity.getApplicationInfo().packageName; - final AssetManager am = activity.createPackageContext(packageName, 0).getAssets(); - final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml"); - - int eventType = xml.getEventType(); - while (eventType != XmlPullParser.END_DOCUMENT) { - if (eventType == XmlPullParser.START_TAG) { - String name = xml.getName(); - - if ("application".equals(name)) { - //Check if the has the attribute - if (DEBUG) Log.d(TAG, "Got "); - - for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { - if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); - - if ("logo".equals(xml.getAttributeName(i))) { - logo = xml.getAttributeResourceValue(i, 0); - break; //out of for loop - } - } - } else if ("activity".equals(name)) { - //Check if the is us and has the attribute - if (DEBUG) Log.d(TAG, "Got "); - Integer activityLogo = null; - String activityPackage = null; - boolean isOurActivity = false; - - for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { - if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); - - //We need both uiOptions and name attributes - String attrName = xml.getAttributeName(i); - if ("logo".equals(attrName)) { - activityLogo = xml.getAttributeResourceValue(i, 0); - } else if ("name".equals(attrName)) { - activityPackage = ActionBarSherlockCompat.cleanActivityName(packageName, xml.getAttributeValue(i)); - if (!thisPackage.equals(activityPackage)) { - break; //on to the next - } - isOurActivity = true; - } - - //Make sure we have both attributes before processing - if ((activityLogo != null) && (activityPackage != null)) { - //Our activity, logo specified, override with our value - logo = activityLogo.intValue(); - } - } - if (isOurActivity) { - //If we matched our activity but it had no logo don't - //do any more processing of the manifest - break; - } - } - } - eventType = xml.nextToken(); - } - } catch (Exception e) { - e.printStackTrace(); - } - if (DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(logo)); - return logo; - } - - /* - * Must be public so we can dispatch pre-2.2 via ActionBarImpl. - */ - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - - mTitleView = null; - mSubtitleView = null; - mTitleUpView = null; - if (mTitleLayout != null && mTitleLayout.getParent() == this) { - removeView(mTitleLayout); - } - mTitleLayout = null; - if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0) { - initTitle(); - } - - if (mTabScrollView != null && mIncludeTabs) { - ViewGroup.LayoutParams lp = mTabScrollView.getLayoutParams(); - if (lp != null) { - lp.width = LayoutParams.WRAP_CONTENT; - lp.height = LayoutParams.MATCH_PARENT; - } - mTabScrollView.setAllowCollapse(true); - } - } - - /** - * Set the window callback used to invoke menu items; used for dispatching home button presses. - * @param cb Window callback to dispatch to - */ - public void setWindowCallback(Window.Callback cb) { - mWindowCallback = cb; - } - - @Override - public void onDetachedFromWindow() { - super.onDetachedFromWindow(); - //UNUSED removeCallbacks(mTabSelector); - if (mActionMenuPresenter != null) { - mActionMenuPresenter.hideOverflowMenu(); - mActionMenuPresenter.hideSubMenus(); - } - } - - @Override - public boolean shouldDelayChildPressedState() { - return false; - } - - public void initProgress() { - mProgressView = new IcsProgressBar(mContext, null, 0, mProgressStyle); - mProgressView.setId(R.id.abs__progress_horizontal); - mProgressView.setMax(10000); - addView(mProgressView); - } - - public void initIndeterminateProgress() { - mIndeterminateProgressView = new IcsProgressBar(mContext, null, 0, mIndeterminateProgressStyle); - mIndeterminateProgressView.setId(R.id.abs__progress_circular); - addView(mIndeterminateProgressView); - } - - @Override - public void setSplitActionBar(boolean splitActionBar) { - if (mSplitActionBar != splitActionBar) { - if (mMenuView != null) { - final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); - if (oldParent != null) { - oldParent.removeView(mMenuView); - } - if (splitActionBar) { - if (mSplitView != null) { - mSplitView.addView(mMenuView); - } - } else { - addView(mMenuView); - } - } - if (mSplitView != null) { - mSplitView.setVisibility(splitActionBar ? VISIBLE : GONE); - } - super.setSplitActionBar(splitActionBar); - } - } - - public boolean isSplitActionBar() { - return mSplitActionBar; - } - - public boolean hasEmbeddedTabs() { - return mIncludeTabs; - } - - public void setEmbeddedTabView(ScrollingTabContainerView tabs) { - if (mTabScrollView != null) { - removeView(mTabScrollView); - } - mTabScrollView = tabs; - mIncludeTabs = tabs != null; - if (mIncludeTabs && mNavigationMode == ActionBar.NAVIGATION_MODE_TABS) { - addView(mTabScrollView); - ViewGroup.LayoutParams lp = mTabScrollView.getLayoutParams(); - lp.width = LayoutParams.WRAP_CONTENT; - lp.height = LayoutParams.MATCH_PARENT; - tabs.setAllowCollapse(true); - } - } - - public void setCallback(OnNavigationListener callback) { - mCallback = callback; - } - - public void setMenu(Menu menu, MenuPresenter.Callback cb) { - if (menu == mOptionsMenu) return; - - if (mOptionsMenu != null) { - mOptionsMenu.removeMenuPresenter(mActionMenuPresenter); - mOptionsMenu.removeMenuPresenter(mExpandedMenuPresenter); - } - - MenuBuilder builder = (MenuBuilder) menu; - mOptionsMenu = builder; - if (mMenuView != null) { - final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); - if (oldParent != null) { - oldParent.removeView(mMenuView); - } - } - if (mActionMenuPresenter == null) { - mActionMenuPresenter = new ActionMenuPresenter(mContext); - mActionMenuPresenter.setCallback(cb); - mActionMenuPresenter.setId(R.id.abs__action_menu_presenter); - mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); - } - - ActionMenuView menuView; - final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.MATCH_PARENT); - if (!mSplitActionBar) { - mActionMenuPresenter.setExpandedActionViewsExclusive( - getResources_getBoolean(getContext(), - R.bool.abs__action_bar_expanded_action_views_exclusive)); - configPresenters(builder); - menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); - final ViewGroup oldParent = (ViewGroup) menuView.getParent(); - if (oldParent != null && oldParent != this) { - oldParent.removeView(menuView); - } - addView(menuView, layoutParams); - } else { - mActionMenuPresenter.setExpandedActionViewsExclusive(false); - // Allow full screen width in split mode. - mActionMenuPresenter.setWidthLimit( - getContext().getResources().getDisplayMetrics().widthPixels, true); - // No limit to the item count; use whatever will fit. - mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); - // Span the whole width - layoutParams.width = LayoutParams.MATCH_PARENT; - configPresenters(builder); - menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); - if (mSplitView != null) { - final ViewGroup oldParent = (ViewGroup) menuView.getParent(); - if (oldParent != null && oldParent != mSplitView) { - oldParent.removeView(menuView); - } - menuView.setVisibility(getAnimatedVisibility()); - mSplitView.addView(menuView, layoutParams); - } else { - // We'll add this later if we missed it this time. - menuView.setLayoutParams(layoutParams); - } - } - mMenuView = menuView; - } - - private void configPresenters(MenuBuilder builder) { - if (builder != null) { - builder.addMenuPresenter(mActionMenuPresenter); - builder.addMenuPresenter(mExpandedMenuPresenter); - } else { - mActionMenuPresenter.initForMenu(mContext, null); - mExpandedMenuPresenter.initForMenu(mContext, null); - mActionMenuPresenter.updateMenuView(true); - mExpandedMenuPresenter.updateMenuView(true); - } - } - - public boolean hasExpandedActionView() { - return mExpandedMenuPresenter != null && - mExpandedMenuPresenter.mCurrentExpandedItem != null; - } - - public void collapseActionView() { - final MenuItemImpl item = mExpandedMenuPresenter == null ? null : - mExpandedMenuPresenter.mCurrentExpandedItem; - if (item != null) { - item.collapseActionView(); - } - } - - public void setCustomNavigationView(View view) { - final boolean showCustom = (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0; - if (mCustomNavView != null && showCustom) { - removeView(mCustomNavView); - } - mCustomNavView = view; - if (mCustomNavView != null && showCustom) { - addView(mCustomNavView); - } - } - - public CharSequence getTitle() { - return mTitle; - } - - /** - * Set the action bar title. This will always replace or override window titles. - * @param title Title to set - * - * @see #setWindowTitle(CharSequence) - */ - public void setTitle(CharSequence title) { - mUserTitle = true; - setTitleImpl(title); - } - - /** - * Set the window title. A window title will always be replaced or overridden by a user title. - * @param title Title to set - * - * @see #setTitle(CharSequence) - */ - public void setWindowTitle(CharSequence title) { - if (!mUserTitle) { - setTitleImpl(title); - } - } - - private void setTitleImpl(CharSequence title) { - mTitle = title; - if (mTitleView != null) { - mTitleView.setText(title); - final boolean visible = mExpandedActionView == null && - (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0 && - (!TextUtils.isEmpty(mTitle) || !TextUtils.isEmpty(mSubtitle)); - mTitleLayout.setVisibility(visible ? VISIBLE : GONE); - } - if (mLogoNavItem != null) { - mLogoNavItem.setTitle(title); - } - } - - public CharSequence getSubtitle() { - return mSubtitle; - } - - public void setSubtitle(CharSequence subtitle) { - mSubtitle = subtitle; - if (mSubtitleView != null) { - mSubtitleView.setText(subtitle); - mSubtitleView.setVisibility(subtitle != null ? VISIBLE : GONE); - final boolean visible = mExpandedActionView == null && - (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0 && - (!TextUtils.isEmpty(mTitle) || !TextUtils.isEmpty(mSubtitle)); - mTitleLayout.setVisibility(visible ? VISIBLE : GONE); - } - } - - public void setHomeButtonEnabled(boolean enable) { - mHomeLayout.setEnabled(enable); - mHomeLayout.setFocusable(enable); - // Make sure the home button has an accurate content description for accessibility. - if (!enable) { - mHomeLayout.setContentDescription(null); - } else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) { - mHomeLayout.setContentDescription(mContext.getResources().getText( - R.string.abs__action_bar_up_description)); - } else { - mHomeLayout.setContentDescription(mContext.getResources().getText( - R.string.abs__action_bar_home_description)); - } - } - - public void setDisplayOptions(int options) { - final int flagsChanged = mDisplayOptions == -1 ? -1 : options ^ mDisplayOptions; - mDisplayOptions = options; - - if ((flagsChanged & DISPLAY_RELAYOUT_MASK) != 0) { - final boolean showHome = (options & ActionBar.DISPLAY_SHOW_HOME) != 0; - final int vis = showHome && mExpandedActionView == null ? VISIBLE : GONE; - mHomeLayout.setVisibility(vis); - - if ((flagsChanged & ActionBar.DISPLAY_HOME_AS_UP) != 0) { - final boolean setUp = (options & ActionBar.DISPLAY_HOME_AS_UP) != 0; - mHomeLayout.setUp(setUp); - - // Showing home as up implicitly enables interaction with it. - // In honeycomb it was always enabled, so make this transition - // a bit easier for developers in the common case. - // (It would be silly to show it as up without responding to it.) - if (setUp) { - setHomeButtonEnabled(true); - } - } - - if ((flagsChanged & ActionBar.DISPLAY_USE_LOGO) != 0) { - final boolean logoVis = mLogo != null && (options & ActionBar.DISPLAY_USE_LOGO) != 0; - mHomeLayout.setIcon(logoVis ? mLogo : mIcon); - } - - if ((flagsChanged & ActionBar.DISPLAY_SHOW_TITLE) != 0) { - if ((options & ActionBar.DISPLAY_SHOW_TITLE) != 0) { - initTitle(); - } else { - removeView(mTitleLayout); - } - } - - if (mTitleLayout != null && (flagsChanged & - (ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME)) != 0) { - final boolean homeAsUp = (mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0; - mTitleUpView.setVisibility(!showHome ? (homeAsUp ? VISIBLE : INVISIBLE) : GONE); - mTitleLayout.setEnabled(!showHome && homeAsUp); - } - - if ((flagsChanged & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { - if ((options & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { - addView(mCustomNavView); - } else { - removeView(mCustomNavView); - } - } - - requestLayout(); - } else { - invalidate(); - } - - // Make sure the home button has an accurate content description for accessibility. - if (!mHomeLayout.isEnabled()) { - mHomeLayout.setContentDescription(null); - } else if ((options & ActionBar.DISPLAY_HOME_AS_UP) != 0) { - mHomeLayout.setContentDescription(mContext.getResources().getText( - R.string.abs__action_bar_up_description)); - } else { - mHomeLayout.setContentDescription(mContext.getResources().getText( - R.string.abs__action_bar_home_description)); - } - } - - public void setIcon(Drawable icon) { - mIcon = icon; - if (icon != null && - ((mDisplayOptions & ActionBar.DISPLAY_USE_LOGO) == 0 || mLogo == null)) { - mHomeLayout.setIcon(icon); - } - } - - public void setIcon(int resId) { - setIcon(mContext.getResources().getDrawable(resId)); - } - - public void setLogo(Drawable logo) { - mLogo = logo; - if (logo != null && (mDisplayOptions & ActionBar.DISPLAY_USE_LOGO) != 0) { - mHomeLayout.setIcon(logo); - } - } - - public void setLogo(int resId) { - setLogo(mContext.getResources().getDrawable(resId)); - } - - public void setNavigationMode(int mode) { - final int oldMode = mNavigationMode; - if (mode != oldMode) { - switch (oldMode) { - case ActionBar.NAVIGATION_MODE_LIST: - if (mListNavLayout != null) { - removeView(mListNavLayout); - } - break; - case ActionBar.NAVIGATION_MODE_TABS: - if (mTabScrollView != null && mIncludeTabs) { - removeView(mTabScrollView); - } - } - - switch (mode) { - case ActionBar.NAVIGATION_MODE_LIST: - if (mSpinner == null) { - mSpinner = new IcsSpinner(mContext, null, - R.attr.actionDropDownStyle); - mListNavLayout = (IcsLinearLayout) LayoutInflater.from(mContext) - .inflate(R.layout.abs__action_bar_tab_bar_view, null); - LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( - LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); - params.gravity = Gravity.CENTER; - mListNavLayout.addView(mSpinner, params); - } - if (mSpinner.getAdapter() != mSpinnerAdapter) { - mSpinner.setAdapter(mSpinnerAdapter); - } - mSpinner.setOnItemSelectedListener(mNavItemSelectedListener); - addView(mListNavLayout); - break; - case ActionBar.NAVIGATION_MODE_TABS: - if (mTabScrollView != null && mIncludeTabs) { - addView(mTabScrollView); - } - break; - } - mNavigationMode = mode; - requestLayout(); - } - } - - public void setDropdownAdapter(SpinnerAdapter adapter) { - mSpinnerAdapter = adapter; - if (mSpinner != null) { - mSpinner.setAdapter(adapter); - } - } - - public SpinnerAdapter getDropdownAdapter() { - return mSpinnerAdapter; - } - - public void setDropdownSelectedPosition(int position) { - mSpinner.setSelection(position); - } - - public int getDropdownSelectedPosition() { - return mSpinner.getSelectedItemPosition(); - } - - public View getCustomNavigationView() { - return mCustomNavView; - } - - public int getNavigationMode() { - return mNavigationMode; - } - - public int getDisplayOptions() { - return mDisplayOptions; - } - - @Override - protected ViewGroup.LayoutParams generateDefaultLayoutParams() { - // Used by custom nav views if they don't supply layout params. Everything else - // added to an ActionBarView should have them already. - return new ActionBar.LayoutParams(DEFAULT_CUSTOM_GRAVITY); - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - - addView(mHomeLayout); - - if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { - final ViewParent parent = mCustomNavView.getParent(); - if (parent != this) { - if (parent instanceof ViewGroup) { - ((ViewGroup) parent).removeView(mCustomNavView); - } - addView(mCustomNavView); - } - } - } - - private void initTitle() { - if (mTitleLayout == null) { - LayoutInflater inflater = LayoutInflater.from(getContext()); - mTitleLayout = (LinearLayout) inflater.inflate(R.layout.abs__action_bar_title_item, - this, false); - mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); - mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); - mTitleUpView = mTitleLayout.findViewById(R.id.abs__up); - - mTitleLayout.setOnClickListener(mUpClickListener); - - if (mTitleStyleRes != 0) { - mTitleView.setTextAppearance(mContext, mTitleStyleRes); - } - if (mTitle != null) { - mTitleView.setText(mTitle); - } - - if (mSubtitleStyleRes != 0) { - mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); - } - if (mSubtitle != null) { - mSubtitleView.setText(mSubtitle); - mSubtitleView.setVisibility(VISIBLE); - } - - final boolean homeAsUp = (mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0; - final boolean showHome = (mDisplayOptions & ActionBar.DISPLAY_SHOW_HOME) != 0; - mTitleUpView.setVisibility(!showHome ? (homeAsUp ? VISIBLE : INVISIBLE) : GONE); - mTitleLayout.setEnabled(homeAsUp && !showHome); - } - - addView(mTitleLayout); - if (mExpandedActionView != null || - (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mSubtitle))) { - // Don't show while in expanded mode or with empty text - mTitleLayout.setVisibility(GONE); - } - } - - public void setContextView(ActionBarContextView view) { - mContextView = view; - } - - public void setCollapsable(boolean collapsable) { - mIsCollapsable = collapsable; - } - - public boolean isCollapsed() { - return mIsCollapsed; - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - final int childCount = getChildCount(); - if (mIsCollapsable) { - int visibleChildren = 0; - for (int i = 0; i < childCount; i++) { - final View child = getChildAt(i); - if (child.getVisibility() != GONE && - !(child == mMenuView && mMenuView.getChildCount() == 0)) { - visibleChildren++; - } - } - - if (visibleChildren == 0) { - // No size for an empty action bar when collapsable. - setMeasuredDimension(0, 0); - mIsCollapsed = true; - return; - } - } - mIsCollapsed = false; - - int widthMode = MeasureSpec.getMode(widthMeasureSpec); - if (widthMode != MeasureSpec.EXACTLY) { - throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + - "with android:layout_width=\"match_parent\" (or fill_parent)"); - } - - int heightMode = MeasureSpec.getMode(heightMeasureSpec); - if (heightMode != MeasureSpec.AT_MOST) { - throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + - "with android:layout_height=\"wrap_content\""); - } - - int contentWidth = MeasureSpec.getSize(widthMeasureSpec); - - int maxHeight = mContentHeight > 0 ? - mContentHeight : MeasureSpec.getSize(heightMeasureSpec); - - final int verticalPadding = getPaddingTop() + getPaddingBottom(); - final int paddingLeft = getPaddingLeft(); - final int paddingRight = getPaddingRight(); - final int height = maxHeight - verticalPadding; - final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); - - int availableWidth = contentWidth - paddingLeft - paddingRight; - int leftOfCenter = availableWidth / 2; - int rightOfCenter = leftOfCenter; - - HomeView homeLayout = mExpandedActionView != null ? mExpandedHomeLayout : mHomeLayout; - - if (homeLayout.getVisibility() != GONE) { - final ViewGroup.LayoutParams lp = homeLayout.getLayoutParams(); - int homeWidthSpec; - if (lp.width < 0) { - homeWidthSpec = MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST); - } else { - homeWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY); - } - homeLayout.measure(homeWidthSpec, - MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); - final int homeWidth = homeLayout.getMeasuredWidth() + homeLayout.getLeftOffset(); - availableWidth = Math.max(0, availableWidth - homeWidth); - leftOfCenter = Math.max(0, availableWidth - homeWidth); - } - - if (mMenuView != null && mMenuView.getParent() == this) { - availableWidth = measureChildView(mMenuView, availableWidth, - childSpecHeight, 0); - rightOfCenter = Math.max(0, rightOfCenter - mMenuView.getMeasuredWidth()); - } - - if (mIndeterminateProgressView != null && - mIndeterminateProgressView.getVisibility() != GONE) { - availableWidth = measureChildView(mIndeterminateProgressView, availableWidth, - childSpecHeight, 0); - rightOfCenter = Math.max(0, - rightOfCenter - mIndeterminateProgressView.getMeasuredWidth()); - } - - final boolean showTitle = mTitleLayout != null && mTitleLayout.getVisibility() != GONE && - (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0; - - if (mExpandedActionView == null) { - switch (mNavigationMode) { - case ActionBar.NAVIGATION_MODE_LIST: - if (mListNavLayout != null) { - final int itemPaddingSize = showTitle ? mItemPadding * 2 : mItemPadding; - availableWidth = Math.max(0, availableWidth - itemPaddingSize); - leftOfCenter = Math.max(0, leftOfCenter - itemPaddingSize); - mListNavLayout.measure( - MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), - MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); - final int listNavWidth = mListNavLayout.getMeasuredWidth(); - availableWidth = Math.max(0, availableWidth - listNavWidth); - leftOfCenter = Math.max(0, leftOfCenter - listNavWidth); - } - break; - case ActionBar.NAVIGATION_MODE_TABS: - if (mTabScrollView != null) { - final int itemPaddingSize = showTitle ? mItemPadding * 2 : mItemPadding; - availableWidth = Math.max(0, availableWidth - itemPaddingSize); - leftOfCenter = Math.max(0, leftOfCenter - itemPaddingSize); - mTabScrollView.measure( - MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), - MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); - final int tabWidth = mTabScrollView.getMeasuredWidth(); - availableWidth = Math.max(0, availableWidth - tabWidth); - leftOfCenter = Math.max(0, leftOfCenter - tabWidth); - } - break; - } - } - - View customView = null; - if (mExpandedActionView != null) { - customView = mExpandedActionView; - } else if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && - mCustomNavView != null) { - customView = mCustomNavView; - } - - if (customView != null) { - final ViewGroup.LayoutParams lp = generateLayoutParams(customView.getLayoutParams()); - final ActionBar.LayoutParams ablp = lp instanceof ActionBar.LayoutParams ? - (ActionBar.LayoutParams) lp : null; - - int horizontalMargin = 0; - int verticalMargin = 0; - if (ablp != null) { - horizontalMargin = ablp.leftMargin + ablp.rightMargin; - verticalMargin = ablp.topMargin + ablp.bottomMargin; - } - - // If the action bar is wrapping to its content height, don't allow a custom - // view to MATCH_PARENT. - int customNavHeightMode; - if (mContentHeight <= 0) { - customNavHeightMode = MeasureSpec.AT_MOST; - } else { - customNavHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? - MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; - } - final int customNavHeight = Math.max(0, - (lp.height >= 0 ? Math.min(lp.height, height) : height) - verticalMargin); - - final int customNavWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? - MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; - int customNavWidth = Math.max(0, - (lp.width >= 0 ? Math.min(lp.width, availableWidth) : availableWidth) - - horizontalMargin); - final int hgrav = (ablp != null ? ablp.gravity : DEFAULT_CUSTOM_GRAVITY) & - Gravity.HORIZONTAL_GRAVITY_MASK; - - // Centering a custom view is treated specially; we try to center within the whole - // action bar rather than in the available space. - if (hgrav == Gravity.CENTER_HORIZONTAL && lp.width == LayoutParams.MATCH_PARENT) { - customNavWidth = Math.min(leftOfCenter, rightOfCenter) * 2; - } - - customView.measure( - MeasureSpec.makeMeasureSpec(customNavWidth, customNavWidthMode), - MeasureSpec.makeMeasureSpec(customNavHeight, customNavHeightMode)); - availableWidth -= horizontalMargin + customView.getMeasuredWidth(); - } - - if (mExpandedActionView == null && showTitle) { - availableWidth = measureChildView(mTitleLayout, availableWidth, - MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY), 0); - leftOfCenter = Math.max(0, leftOfCenter - mTitleLayout.getMeasuredWidth()); - } - - if (mContentHeight <= 0) { - int measuredHeight = 0; - for (int i = 0; i < childCount; i++) { - View v = getChildAt(i); - int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; - if (paddedViewHeight > measuredHeight) { - measuredHeight = paddedViewHeight; - } - } - setMeasuredDimension(contentWidth, measuredHeight); - } else { - setMeasuredDimension(contentWidth, maxHeight); - } - - if (mContextView != null) { - mContextView.setContentHeight(getMeasuredHeight()); - } - - if (mProgressView != null && mProgressView.getVisibility() != GONE) { - mProgressView.measure(MeasureSpec.makeMeasureSpec( - contentWidth - mProgressBarPadding * 2, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST)); - } - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - int x = getPaddingLeft(); - final int y = getPaddingTop(); - final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); - - if (contentHeight <= 0) { - // Nothing to do if we can't see anything. - return; - } - - HomeView homeLayout = mExpandedActionView != null ? mExpandedHomeLayout : mHomeLayout; - if (homeLayout.getVisibility() != GONE) { - final int leftOffset = homeLayout.getLeftOffset(); - x += positionChild(homeLayout, x + leftOffset, y, contentHeight) + leftOffset; - } - - if (mExpandedActionView == null) { - final boolean showTitle = mTitleLayout != null && mTitleLayout.getVisibility() != GONE && - (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0; - if (showTitle) { - x += positionChild(mTitleLayout, x, y, contentHeight); - } - - switch (mNavigationMode) { - case ActionBar.NAVIGATION_MODE_STANDARD: - break; - case ActionBar.NAVIGATION_MODE_LIST: - if (mListNavLayout != null) { - if (showTitle) x += mItemPadding; - x += positionChild(mListNavLayout, x, y, contentHeight) + mItemPadding; - } - break; - case ActionBar.NAVIGATION_MODE_TABS: - if (mTabScrollView != null) { - if (showTitle) x += mItemPadding; - x += positionChild(mTabScrollView, x, y, contentHeight) + mItemPadding; - } - break; - } - } - - int menuLeft = r - l - getPaddingRight(); - if (mMenuView != null && mMenuView.getParent() == this) { - positionChildInverse(mMenuView, menuLeft, y, contentHeight); - menuLeft -= mMenuView.getMeasuredWidth(); - } - - if (mIndeterminateProgressView != null && - mIndeterminateProgressView.getVisibility() != GONE) { - positionChildInverse(mIndeterminateProgressView, menuLeft, y, contentHeight); - menuLeft -= mIndeterminateProgressView.getMeasuredWidth(); - } - - View customView = null; - if (mExpandedActionView != null) { - customView = mExpandedActionView; - } else if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && - mCustomNavView != null) { - customView = mCustomNavView; - } - if (customView != null) { - ViewGroup.LayoutParams lp = customView.getLayoutParams(); - final ActionBar.LayoutParams ablp = lp instanceof ActionBar.LayoutParams ? - (ActionBar.LayoutParams) lp : null; - - final int gravity = ablp != null ? ablp.gravity : DEFAULT_CUSTOM_GRAVITY; - final int navWidth = customView.getMeasuredWidth(); - - int topMargin = 0; - int bottomMargin = 0; - if (ablp != null) { - x += ablp.leftMargin; - menuLeft -= ablp.rightMargin; - topMargin = ablp.topMargin; - bottomMargin = ablp.bottomMargin; - } - - int hgravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; - // See if we actually have room to truly center; if not push against left or right. - if (hgravity == Gravity.CENTER_HORIZONTAL) { - final int centeredLeft = ((getRight() - getLeft()) - navWidth) / 2; - if (centeredLeft < x) { - hgravity = Gravity.LEFT; - } else if (centeredLeft + navWidth > menuLeft) { - hgravity = Gravity.RIGHT; - } - } else if (gravity == -1) { - hgravity = Gravity.LEFT; - } - - int xpos = 0; - switch (hgravity) { - case Gravity.CENTER_HORIZONTAL: - xpos = ((getRight() - getLeft()) - navWidth) / 2; - break; - case Gravity.LEFT: - xpos = x; - break; - case Gravity.RIGHT: - xpos = menuLeft - navWidth; - break; - } - - int vgravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; - - if (gravity == -1) { - vgravity = Gravity.CENTER_VERTICAL; - } - - int ypos = 0; - switch (vgravity) { - case Gravity.CENTER_VERTICAL: - final int paddedTop = getPaddingTop(); - final int paddedBottom = getBottom() - getTop() - getPaddingBottom(); - ypos = ((paddedBottom - paddedTop) - customView.getMeasuredHeight()) / 2; - break; - case Gravity.TOP: - ypos = getPaddingTop() + topMargin; - break; - case Gravity.BOTTOM: - ypos = getHeight() - getPaddingBottom() - customView.getMeasuredHeight() - - bottomMargin; - break; - } - final int customWidth = customView.getMeasuredWidth(); - customView.layout(xpos, ypos, xpos + customWidth, - ypos + customView.getMeasuredHeight()); - x += customWidth; - } - - if (mProgressView != null) { - mProgressView.bringToFront(); - final int halfProgressHeight = mProgressView.getMeasuredHeight() / 2; - mProgressView.layout(mProgressBarPadding, -halfProgressHeight, - mProgressBarPadding + mProgressView.getMeasuredWidth(), halfProgressHeight); - } - } - - @Override - public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { - return new ActionBar.LayoutParams(getContext(), attrs); - } - - @Override - public ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { - if (lp == null) { - lp = generateDefaultLayoutParams(); - } - return lp; - } - - @Override - public Parcelable onSaveInstanceState() { - Parcelable superState = super.onSaveInstanceState(); - SavedState state = new SavedState(superState); - - if (mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null) { - state.expandedMenuItemId = mExpandedMenuPresenter.mCurrentExpandedItem.getItemId(); - } - - state.isOverflowOpen = isOverflowMenuShowing(); - - return state; - } - - @Override - public void onRestoreInstanceState(Parcelable p) { - SavedState state = (SavedState) p; - - super.onRestoreInstanceState(state.getSuperState()); - - if (state.expandedMenuItemId != 0 && - mExpandedMenuPresenter != null && mOptionsMenu != null) { - final MenuItem item = mOptionsMenu.findItem(state.expandedMenuItemId); - if (item != null) { - item.expandActionView(); - } - } - - if (state.isOverflowOpen) { - postShowOverflowMenu(); - } - } - - static class SavedState extends BaseSavedState { - int expandedMenuItemId; - boolean isOverflowOpen; - - SavedState(Parcelable superState) { - super(superState); - } - - private SavedState(Parcel in) { - super(in); - expandedMenuItemId = in.readInt(); - isOverflowOpen = in.readInt() != 0; - } - - @Override - public void writeToParcel(Parcel out, int flags) { - super.writeToParcel(out, flags); - out.writeInt(expandedMenuItemId); - out.writeInt(isOverflowOpen ? 1 : 0); - } - - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; - } - - public static class HomeView extends FrameLayout { - private View mUpView; - private ImageView mIconView; - private int mUpWidth; - - public HomeView(Context context) { - this(context, null); - } - - public HomeView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public void setUp(boolean isUp) { - mUpView.setVisibility(isUp ? VISIBLE : GONE); - } - - public void setIcon(Drawable icon) { - mIconView.setImageDrawable(icon); - } - - @Override - public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { - onPopulateAccessibilityEvent(event); - return true; - } - - @Override - public void onPopulateAccessibilityEvent(AccessibilityEvent event) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - super.onPopulateAccessibilityEvent(event); - } - final CharSequence cdesc = getContentDescription(); - if (!TextUtils.isEmpty(cdesc)) { - event.getText().add(cdesc); - } - } - - @Override - public boolean dispatchHoverEvent(MotionEvent event) { - // Don't allow children to hover; we want this to be treated as a single component. - return onHoverEvent(event); - } - - @Override - protected void onFinishInflate() { - mUpView = findViewById(R.id.abs__up); - mIconView = (ImageView) findViewById(R.id.abs__home); - } - - public int getLeftOffset() { - return mUpView.getVisibility() == GONE ? mUpWidth : 0; - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - measureChildWithMargins(mUpView, widthMeasureSpec, 0, heightMeasureSpec, 0); - final LayoutParams upLp = (LayoutParams) mUpView.getLayoutParams(); - mUpWidth = upLp.leftMargin + mUpView.getMeasuredWidth() + upLp.rightMargin; - int width = mUpView.getVisibility() == GONE ? 0 : mUpWidth; - int height = upLp.topMargin + mUpView.getMeasuredHeight() + upLp.bottomMargin; - measureChildWithMargins(mIconView, widthMeasureSpec, width, heightMeasureSpec, 0); - final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); - width += iconLp.leftMargin + mIconView.getMeasuredWidth() + iconLp.rightMargin; - height = Math.max(height, - iconLp.topMargin + mIconView.getMeasuredHeight() + iconLp.bottomMargin); - - final int widthMode = MeasureSpec.getMode(widthMeasureSpec); - final int heightMode = MeasureSpec.getMode(heightMeasureSpec); - final int widthSize = MeasureSpec.getSize(widthMeasureSpec); - final int heightSize = MeasureSpec.getSize(heightMeasureSpec); - - switch (widthMode) { - case MeasureSpec.AT_MOST: - width = Math.min(width, widthSize); - break; - case MeasureSpec.EXACTLY: - width = widthSize; - break; - case MeasureSpec.UNSPECIFIED: - default: - break; - } - switch (heightMode) { - case MeasureSpec.AT_MOST: - height = Math.min(height, heightSize); - break; - case MeasureSpec.EXACTLY: - height = heightSize; - break; - case MeasureSpec.UNSPECIFIED: - default: - break; - } - setMeasuredDimension(width, height); - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - final int vCenter = (b - t) / 2; - //UNUSED int width = r - l; - int upOffset = 0; - if (mUpView.getVisibility() != GONE) { - final LayoutParams upLp = (LayoutParams) mUpView.getLayoutParams(); - final int upHeight = mUpView.getMeasuredHeight(); - final int upWidth = mUpView.getMeasuredWidth(); - final int upTop = vCenter - upHeight / 2; - mUpView.layout(0, upTop, upWidth, upTop + upHeight); - upOffset = upLp.leftMargin + upWidth + upLp.rightMargin; - //UNUSED width -= upOffset; - l += upOffset; - } - final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); - final int iconHeight = mIconView.getMeasuredHeight(); - final int iconWidth = mIconView.getMeasuredWidth(); - final int hCenter = (r - l) / 2; - final int iconLeft = upOffset + Math.max(iconLp.leftMargin, hCenter - iconWidth / 2); - final int iconTop = Math.max(iconLp.topMargin, vCenter - iconHeight / 2); - mIconView.layout(iconLeft, iconTop, iconLeft + iconWidth, iconTop + iconHeight); - } - } - - private class ExpandedActionViewMenuPresenter implements MenuPresenter { - MenuBuilder mMenu; - MenuItemImpl mCurrentExpandedItem; - - @Override - public void initForMenu(Context context, MenuBuilder menu) { - // Clear the expanded action view when menus change. - if (mMenu != null && mCurrentExpandedItem != null) { - mMenu.collapseItemActionView(mCurrentExpandedItem); - } - mMenu = menu; - } - - @Override - public MenuView getMenuView(ViewGroup root) { - return null; - } - - @Override - public void updateMenuView(boolean cleared) { - // Make sure the expanded item we have is still there. - if (mCurrentExpandedItem != null) { - boolean found = false; - - if (mMenu != null) { - final int count = mMenu.size(); - for (int i = 0; i < count; i++) { - final MenuItem item = mMenu.getItem(i); - if (item == mCurrentExpandedItem) { - found = true; - break; - } - } - } - - if (!found) { - // The item we had expanded disappeared. Collapse. - collapseItemActionView(mMenu, mCurrentExpandedItem); - } - } - } - - @Override - public void setCallback(Callback cb) { - } - - @Override - public boolean onSubMenuSelected(SubMenuBuilder subMenu) { - return false; - } - - @Override - public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { - } - - @Override - public boolean flagActionItems() { - return false; - } - - @Override - public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { - mExpandedActionView = item.getActionView(); - mExpandedHomeLayout.setIcon(mIcon.getConstantState().newDrawable(/* TODO getResources() */)); - mCurrentExpandedItem = item; - if (mExpandedActionView.getParent() != ActionBarView.this) { - addView(mExpandedActionView); - } - if (mExpandedHomeLayout.getParent() != ActionBarView.this) { - addView(mExpandedHomeLayout); - } - mHomeLayout.setVisibility(GONE); - if (mTitleLayout != null) mTitleLayout.setVisibility(GONE); - if (mTabScrollView != null) mTabScrollView.setVisibility(GONE); - if (mSpinner != null) mSpinner.setVisibility(GONE); - if (mCustomNavView != null) mCustomNavView.setVisibility(GONE); - requestLayout(); - item.setActionViewExpanded(true); - - if (mExpandedActionView instanceof CollapsibleActionView) { - ((CollapsibleActionView) mExpandedActionView).onActionViewExpanded(); - } - - return true; - } - - @Override - public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { - // Do this before detaching the actionview from the hierarchy, in case - // it needs to dismiss the soft keyboard, etc. - if (mExpandedActionView instanceof CollapsibleActionView) { - ((CollapsibleActionView) mExpandedActionView).onActionViewCollapsed(); - } - - removeView(mExpandedActionView); - removeView(mExpandedHomeLayout); - mExpandedActionView = null; - if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_HOME) != 0) { - mHomeLayout.setVisibility(VISIBLE); - } - if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0) { - if (mTitleLayout == null) { - initTitle(); - } else { - mTitleLayout.setVisibility(VISIBLE); - } - } - if (mTabScrollView != null && mNavigationMode == ActionBar.NAVIGATION_MODE_TABS) { - mTabScrollView.setVisibility(VISIBLE); - } - if (mSpinner != null && mNavigationMode == ActionBar.NAVIGATION_MODE_LIST) { - mSpinner.setVisibility(VISIBLE); - } - if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { - mCustomNavView.setVisibility(VISIBLE); - } - mExpandedHomeLayout.setIcon(null); - mCurrentExpandedItem = null; - requestLayout(); - item.setActionViewExpanded(false); - - return true; - } - - @Override - public int getId() { - return 0; - } - - @Override - public Parcelable onSaveInstanceState() { - return null; - } - - @Override - public void onRestoreInstanceState(Parcelable state) { - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingButton.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingButton.java deleted file mode 100644 index fa3698f3..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingButton.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.actionbarsherlock.internal.widget; - -import java.util.Locale; -import android.content.Context; -import android.content.res.TypedArray; -import android.os.Build; -import android.util.AttributeSet; -import android.widget.Button; - -public class CapitalizingButton extends Button { - private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; - private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; - - private static final int[] R_styleable_Button = new int[] { - android.R.attr.textAllCaps - }; - private static final int R_styleable_Button_textAllCaps = 0; - - private boolean mAllCaps; - - public CapitalizingButton(Context context, AttributeSet attrs) { - super(context, attrs); - - TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_Button); - mAllCaps = a.getBoolean(R_styleable_Button_textAllCaps, true); - a.recycle(); - } - - public void setTextCompat(CharSequence text) { - if (SANS_ICE_CREAM && mAllCaps && text != null) { - if (IS_GINGERBREAD) { - setText(text.toString().toUpperCase(Locale.ROOT)); - } else { - setText(text.toString().toUpperCase()); - } - } else { - setText(text); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingTextView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingTextView.java deleted file mode 100644 index 673ec554..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingTextView.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.actionbarsherlock.internal.widget; - -import java.util.Locale; -import android.content.Context; -import android.content.res.TypedArray; -import android.os.Build; -import android.util.AttributeSet; -import android.widget.TextView; - -public class CapitalizingTextView extends TextView { - private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; - private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; - - private static final int[] R_styleable_TextView = new int[] { - android.R.attr.textAllCaps - }; - private static final int R_styleable_TextView_textAllCaps = 0; - - private boolean mAllCaps; - - public CapitalizingTextView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public CapitalizingTextView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - - TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_TextView, defStyle, 0); - mAllCaps = a.getBoolean(R_styleable_TextView_textAllCaps, true); - a.recycle(); - } - - public void setTextCompat(CharSequence text) { - if (SANS_ICE_CREAM && mAllCaps && text != null) { - if (IS_GINGERBREAD) { - setText(text.toString().toUpperCase(Locale.ROOT)); - } else { - setText(text.toString().toUpperCase()); - } - } else { - setText(text); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.java deleted file mode 100644 index ad1b4f0a..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.actionbarsherlock.internal.widget; - -import static android.view.View.MeasureSpec.EXACTLY; -import android.content.Context; -import android.content.res.TypedArray; -import android.util.AttributeSet; -import android.util.DisplayMetrics; -import android.util.TypedValue; -import android.widget.LinearLayout; -import com.actionbarsherlock.R; - -public class FakeDialogPhoneWindow extends LinearLayout { - final TypedValue mMinWidthMajor = new TypedValue(); - final TypedValue mMinWidthMinor = new TypedValue(); - - public FakeDialogPhoneWindow(Context context, AttributeSet attrs) { - super(context, attrs); - - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockTheme); - - a.getValue(R.styleable.SherlockTheme_windowMinWidthMajor, mMinWidthMajor); - a.getValue(R.styleable.SherlockTheme_windowMinWidthMinor, mMinWidthMinor); - - a.recycle(); - } - - /* Stolen from PhoneWindow */ - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); - final boolean isPortrait = metrics.widthPixels < metrics.heightPixels; - - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - int width = getMeasuredWidth(); - boolean measure = false; - - widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY); - - final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor; - - if (tv.type != TypedValue.TYPE_NULL) { - final int min; - if (tv.type == TypedValue.TYPE_DIMENSION) { - min = (int)tv.getDimension(metrics); - } else if (tv.type == TypedValue.TYPE_FRACTION) { - min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels); - } else { - min = 0; - } - - if (width < min) { - widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY); - measure = true; - } - } - - // TODO: Support height? - - if (measure) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAbsSpinner.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAbsSpinner.java deleted file mode 100644 index ce0cb3bc..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAbsSpinner.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.database.DataSetObserver; -import android.graphics.Rect; -import android.os.Build; -import android.os.Parcel; -import android.os.Parcelable; -import android.util.AttributeSet; -import android.util.SparseArray; -import android.view.View; -import android.view.ViewGroup; -import android.widget.SpinnerAdapter; - -/** - * An abstract base class for spinner widgets. SDK users will probably not - * need to use this class. - * - * @attr ref android.R.styleable#AbsSpinner_entries - */ -public abstract class IcsAbsSpinner extends IcsAdapterView { - private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; - - SpinnerAdapter mAdapter; - - int mHeightMeasureSpec; - int mWidthMeasureSpec; - boolean mBlockLayoutRequests; - - int mSelectionLeftPadding = 0; - int mSelectionTopPadding = 0; - int mSelectionRightPadding = 0; - int mSelectionBottomPadding = 0; - final Rect mSpinnerPadding = new Rect(); - - final RecycleBin mRecycler = new RecycleBin(); - private DataSetObserver mDataSetObserver; - - /** Temporary frame to hold a child View's frame rectangle */ - private Rect mTouchFrame; - - public IcsAbsSpinner(Context context) { - super(context); - initAbsSpinner(); - } - - public IcsAbsSpinner(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public IcsAbsSpinner(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - initAbsSpinner(); - - /* - TypedArray a = context.obtainStyledAttributes(attrs, - com.android.internal.R.styleable.AbsSpinner, defStyle, 0); - - CharSequence[] entries = a.getTextArray(R.styleable.AbsSpinner_entries); - if (entries != null) { - ArrayAdapter adapter = - new ArrayAdapter(context, - R.layout.simple_spinner_item, entries); - adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); - setAdapter(adapter); - } - - a.recycle(); - */ - } - - /** - * Common code for different constructor flavors - */ - private void initAbsSpinner() { - setFocusable(true); - setWillNotDraw(false); - } - - /** - * The Adapter is used to provide the data which backs this Spinner. - * It also provides methods to transform spinner items based on their position - * relative to the selected item. - * @param adapter The SpinnerAdapter to use for this Spinner - */ - @Override - public void setAdapter(SpinnerAdapter adapter) { - if (null != mAdapter) { - mAdapter.unregisterDataSetObserver(mDataSetObserver); - resetList(); - } - - mAdapter = adapter; - - mOldSelectedPosition = INVALID_POSITION; - mOldSelectedRowId = INVALID_ROW_ID; - - if (mAdapter != null) { - mOldItemCount = mItemCount; - mItemCount = mAdapter.getCount(); - checkFocus(); - - mDataSetObserver = new AdapterDataSetObserver(); - mAdapter.registerDataSetObserver(mDataSetObserver); - - int position = mItemCount > 0 ? 0 : INVALID_POSITION; - - setSelectedPositionInt(position); - setNextSelectedPositionInt(position); - - if (mItemCount == 0) { - // Nothing selected - checkSelectionChanged(); - } - - } else { - checkFocus(); - resetList(); - // Nothing selected - checkSelectionChanged(); - } - - requestLayout(); - } - - /** - * Clear out all children from the list - */ - void resetList() { - mDataChanged = false; - mNeedSync = false; - - removeAllViewsInLayout(); - mOldSelectedPosition = INVALID_POSITION; - mOldSelectedRowId = INVALID_ROW_ID; - - setSelectedPositionInt(INVALID_POSITION); - setNextSelectedPositionInt(INVALID_POSITION); - invalidate(); - } - - /** - * @see android.view.View#measure(int, int) - * - * Figure out the dimensions of this Spinner. The width comes from - * the widthMeasureSpec as Spinnners can't have their width set to - * UNSPECIFIED. The height is based on the height of the selected item - * plus padding. - */ - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int widthMode = MeasureSpec.getMode(widthMeasureSpec); - int widthSize; - int heightSize; - - final int mPaddingLeft = getPaddingLeft(); - final int mPaddingTop = getPaddingTop(); - final int mPaddingRight = getPaddingRight(); - final int mPaddingBottom = getPaddingBottom(); - - mSpinnerPadding.left = mPaddingLeft > mSelectionLeftPadding ? mPaddingLeft - : mSelectionLeftPadding; - mSpinnerPadding.top = mPaddingTop > mSelectionTopPadding ? mPaddingTop - : mSelectionTopPadding; - mSpinnerPadding.right = mPaddingRight > mSelectionRightPadding ? mPaddingRight - : mSelectionRightPadding; - mSpinnerPadding.bottom = mPaddingBottom > mSelectionBottomPadding ? mPaddingBottom - : mSelectionBottomPadding; - - if (mDataChanged) { - handleDataChanged(); - } - - int preferredHeight = 0; - int preferredWidth = 0; - boolean needsMeasuring = true; - - int selectedPosition = getSelectedItemPosition(); - if (selectedPosition >= 0 && mAdapter != null && selectedPosition < mAdapter.getCount()) { - // Try looking in the recycler. (Maybe we were measured once already) - View view = mRecycler.get(selectedPosition); - if (view == null) { - // Make a new one - view = mAdapter.getView(selectedPosition, null, this); - } - - if (view != null) { - // Put in recycler for re-measuring and/or layout - mRecycler.put(selectedPosition, view); - } - - if (view != null) { - if (view.getLayoutParams() == null) { - mBlockLayoutRequests = true; - view.setLayoutParams(generateDefaultLayoutParams()); - mBlockLayoutRequests = false; - } - measureChild(view, widthMeasureSpec, heightMeasureSpec); - - preferredHeight = getChildHeight(view) + mSpinnerPadding.top + mSpinnerPadding.bottom; - preferredWidth = getChildWidth(view) + mSpinnerPadding.left + mSpinnerPadding.right; - - needsMeasuring = false; - } - } - - if (needsMeasuring) { - // No views -- just use padding - preferredHeight = mSpinnerPadding.top + mSpinnerPadding.bottom; - if (widthMode == MeasureSpec.UNSPECIFIED) { - preferredWidth = mSpinnerPadding.left + mSpinnerPadding.right; - } - } - - preferredHeight = Math.max(preferredHeight, getSuggestedMinimumHeight()); - preferredWidth = Math.max(preferredWidth, getSuggestedMinimumWidth()); - - if (IS_HONEYCOMB) { - heightSize = resolveSizeAndState(preferredHeight, heightMeasureSpec, 0); - widthSize = resolveSizeAndState(preferredWidth, widthMeasureSpec, 0); - } else { - heightSize = resolveSize(preferredHeight, heightMeasureSpec); - widthSize = resolveSize(preferredWidth, widthMeasureSpec); - } - - setMeasuredDimension(widthSize, heightSize); - mHeightMeasureSpec = heightMeasureSpec; - mWidthMeasureSpec = widthMeasureSpec; - } - - int getChildHeight(View child) { - return child.getMeasuredHeight(); - } - - int getChildWidth(View child) { - return child.getMeasuredWidth(); - } - - @Override - protected ViewGroup.LayoutParams generateDefaultLayoutParams() { - return new ViewGroup.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - } - - void recycleAllViews() { - final int childCount = getChildCount(); - final IcsAbsSpinner.RecycleBin recycleBin = mRecycler; - final int position = mFirstPosition; - - // All views go in recycler - for (int i = 0; i < childCount; i++) { - View v = getChildAt(i); - int index = position + i; - recycleBin.put(index, v); - } - } - - /** - * Jump directly to a specific item in the adapter data. - */ - public void setSelection(int position, boolean animate) { - // Animate only if requested position is already on screen somewhere - boolean shouldAnimate = animate && mFirstPosition <= position && - position <= mFirstPosition + getChildCount() - 1; - setSelectionInt(position, shouldAnimate); - } - - @Override - public void setSelection(int position) { - setNextSelectedPositionInt(position); - requestLayout(); - invalidate(); - } - - - /** - * Makes the item at the supplied position selected. - * - * @param position Position to select - * @param animate Should the transition be animated - * - */ - void setSelectionInt(int position, boolean animate) { - if (position != mOldSelectedPosition) { - mBlockLayoutRequests = true; - int delta = position - mSelectedPosition; - setNextSelectedPositionInt(position); - layout(delta, animate); - mBlockLayoutRequests = false; - } - } - - abstract void layout(int delta, boolean animate); - - @Override - public View getSelectedView() { - if (mItemCount > 0 && mSelectedPosition >= 0) { - return getChildAt(mSelectedPosition - mFirstPosition); - } else { - return null; - } - } - - /** - * Override to prevent spamming ourselves with layout requests - * as we place views - * - * @see android.view.View#requestLayout() - */ - @Override - public void requestLayout() { - if (!mBlockLayoutRequests) { - super.requestLayout(); - } - } - - @Override - public SpinnerAdapter getAdapter() { - return mAdapter; - } - - @Override - public int getCount() { - return mItemCount; - } - - /** - * Maps a point to a position in the list. - * - * @param x X in local coordinate - * @param y Y in local coordinate - * @return The position of the item which contains the specified point, or - * {@link #INVALID_POSITION} if the point does not intersect an item. - */ - public int pointToPosition(int x, int y) { - Rect frame = mTouchFrame; - if (frame == null) { - mTouchFrame = new Rect(); - frame = mTouchFrame; - } - - final int count = getChildCount(); - for (int i = count - 1; i >= 0; i--) { - View child = getChildAt(i); - if (child.getVisibility() == View.VISIBLE) { - child.getHitRect(frame); - if (frame.contains(x, y)) { - return mFirstPosition + i; - } - } - } - return INVALID_POSITION; - } - - static class SavedState extends BaseSavedState { - long selectedId; - int position; - - /** - * Constructor called from {@link AbsSpinner#onSaveInstanceState()} - */ - SavedState(Parcelable superState) { - super(superState); - } - - /** - * Constructor called from {@link #CREATOR} - */ - private SavedState(Parcel in) { - super(in); - selectedId = in.readLong(); - position = in.readInt(); - } - - @Override - public void writeToParcel(Parcel out, int flags) { - super.writeToParcel(out, flags); - out.writeLong(selectedId); - out.writeInt(position); - } - - @Override - public String toString() { - return "AbsSpinner.SavedState{" - + Integer.toHexString(System.identityHashCode(this)) - + " selectedId=" + selectedId - + " position=" + position + "}"; - } - - public static final Parcelable.Creator CREATOR - = new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; - } - - @Override - public Parcelable onSaveInstanceState() { - Parcelable superState = super.onSaveInstanceState(); - SavedState ss = new SavedState(superState); - ss.selectedId = getSelectedItemId(); - if (ss.selectedId >= 0) { - ss.position = getSelectedItemPosition(); - } else { - ss.position = INVALID_POSITION; - } - return ss; - } - - @Override - public void onRestoreInstanceState(Parcelable state) { - SavedState ss = (SavedState) state; - - super.onRestoreInstanceState(ss.getSuperState()); - - if (ss.selectedId >= 0) { - mDataChanged = true; - mNeedSync = true; - mSyncRowId = ss.selectedId; - mSyncPosition = ss.position; - mSyncMode = SYNC_SELECTED_POSITION; - requestLayout(); - } - } - - class RecycleBin { - private final SparseArray mScrapHeap = new SparseArray(); - - public void put(int position, View v) { - mScrapHeap.put(position, v); - } - - View get(int position) { - // System.out.print("Looking for " + position); - View result = mScrapHeap.get(position); - if (result != null) { - // System.out.println(" HIT"); - mScrapHeap.delete(position); - } else { - // System.out.println(" MISS"); - } - return result; - } - - void clear() { - final SparseArray scrapHeap = mScrapHeap; - final int count = scrapHeap.size(); - for (int i = 0; i < count; i++) { - final View view = scrapHeap.valueAt(i); - if (view != null) { - removeDetachedView(view, true); - } - } - scrapHeap.clear(); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAdapterView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAdapterView.java deleted file mode 100644 index c786dc5c..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAdapterView.java +++ /dev/null @@ -1,1160 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.database.DataSetObserver; -import android.os.Parcelable; -import android.os.SystemClock; -import android.util.AttributeSet; -import android.util.SparseArray; -import android.view.ContextMenu; -import android.view.SoundEffectConstants; -import android.view.View; -import android.view.ViewDebug; -import android.view.ViewGroup; -import android.view.accessibility.AccessibilityEvent; -import android.view.accessibility.AccessibilityNodeInfo; -import android.widget.Adapter; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.ListView; - - -/** - * An AdapterView is a view whose children are determined by an {@link Adapter}. - * - *

- * See {@link ListView}, {@link GridView}, {@link Spinner} and - * {@link Gallery} for commonly used subclasses of AdapterView. - * - *

- *

Developer Guides

- *

For more information about using AdapterView, read the - * Binding to Data with AdapterView - * developer guide.

- */ -public abstract class IcsAdapterView extends ViewGroup { - - /** - * The item view type returned by {@link Adapter#getItemViewType(int)} when - * the adapter does not want the item's view recycled. - */ - public static final int ITEM_VIEW_TYPE_IGNORE = -1; - - /** - * The item view type returned by {@link Adapter#getItemViewType(int)} when - * the item is a header or footer. - */ - public static final int ITEM_VIEW_TYPE_HEADER_OR_FOOTER = -2; - - /** - * The position of the first child displayed - */ - @ViewDebug.ExportedProperty(category = "scrolling") - int mFirstPosition = 0; - - /** - * The offset in pixels from the top of the AdapterView to the top - * of the view to select during the next layout. - */ - int mSpecificTop; - - /** - * Position from which to start looking for mSyncRowId - */ - int mSyncPosition; - - /** - * Row id to look for when data has changed - */ - long mSyncRowId = INVALID_ROW_ID; - - /** - * Height of the view when mSyncPosition and mSyncRowId where set - */ - long mSyncHeight; - - /** - * True if we need to sync to mSyncRowId - */ - boolean mNeedSync = false; - - /** - * Indicates whether to sync based on the selection or position. Possible - * values are {@link #SYNC_SELECTED_POSITION} or - * {@link #SYNC_FIRST_POSITION}. - */ - int mSyncMode; - - /** - * Our height after the last layout - */ - private int mLayoutHeight; - - /** - * Sync based on the selected child - */ - static final int SYNC_SELECTED_POSITION = 0; - - /** - * Sync based on the first child displayed - */ - static final int SYNC_FIRST_POSITION = 1; - - /** - * Maximum amount of time to spend in {@link #findSyncPosition()} - */ - static final int SYNC_MAX_DURATION_MILLIS = 100; - - /** - * Indicates that this view is currently being laid out. - */ - boolean mInLayout = false; - - /** - * The listener that receives notifications when an item is selected. - */ - OnItemSelectedListener mOnItemSelectedListener; - - /** - * The listener that receives notifications when an item is clicked. - */ - OnItemClickListener mOnItemClickListener; - - /** - * The listener that receives notifications when an item is long clicked. - */ - OnItemLongClickListener mOnItemLongClickListener; - - /** - * True if the data has changed since the last layout - */ - boolean mDataChanged; - - /** - * The position within the adapter's data set of the item to select - * during the next layout. - */ - @ViewDebug.ExportedProperty(category = "list") - int mNextSelectedPosition = INVALID_POSITION; - - /** - * The item id of the item to select during the next layout. - */ - long mNextSelectedRowId = INVALID_ROW_ID; - - /** - * The position within the adapter's data set of the currently selected item. - */ - @ViewDebug.ExportedProperty(category = "list") - int mSelectedPosition = INVALID_POSITION; - - /** - * The item id of the currently selected item. - */ - long mSelectedRowId = INVALID_ROW_ID; - - /** - * View to show if there are no items to show. - */ - private View mEmptyView; - - /** - * The number of items in the current adapter. - */ - @ViewDebug.ExportedProperty(category = "list") - int mItemCount; - - /** - * The number of items in the adapter before a data changed event occurred. - */ - int mOldItemCount; - - /** - * Represents an invalid position. All valid positions are in the range 0 to 1 less than the - * number of items in the current adapter. - */ - public static final int INVALID_POSITION = -1; - - /** - * Represents an empty or invalid row id - */ - public static final long INVALID_ROW_ID = Long.MIN_VALUE; - - /** - * The last selected position we used when notifying - */ - int mOldSelectedPosition = INVALID_POSITION; - - /** - * The id of the last selected position we used when notifying - */ - long mOldSelectedRowId = INVALID_ROW_ID; - - /** - * Indicates what focusable state is requested when calling setFocusable(). - * In addition to this, this view has other criteria for actually - * determining the focusable state (such as whether its empty or the text - * filter is shown). - * - * @see #setFocusable(boolean) - * @see #checkFocus() - */ - private boolean mDesiredFocusableState; - private boolean mDesiredFocusableInTouchModeState; - - private SelectionNotifier mSelectionNotifier; - /** - * When set to true, calls to requestLayout() will not propagate up the parent hierarchy. - * This is used to layout the children during a layout pass. - */ - boolean mBlockLayoutRequests = false; - - public IcsAdapterView(Context context) { - super(context); - } - - public IcsAdapterView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public IcsAdapterView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } - - /** - * Register a callback to be invoked when an item in this AdapterView has - * been clicked. - * - * @param listener The callback that will be invoked. - */ - public void setOnItemClickListener(OnItemClickListener listener) { - mOnItemClickListener = listener; - } - - /** - * @return The callback to be invoked with an item in this AdapterView has - * been clicked, or null id no callback has been set. - */ - public final OnItemClickListener getOnItemClickListener() { - return mOnItemClickListener; - } - - /** - * Call the OnItemClickListener, if it is defined. - * - * @param view The view within the AdapterView that was clicked. - * @param position The position of the view in the adapter. - * @param id The row id of the item that was clicked. - * @return True if there was an assigned OnItemClickListener that was - * called, false otherwise is returned. - */ - public boolean performItemClick(View view, int position, long id) { - if (mOnItemClickListener != null) { - playSoundEffect(SoundEffectConstants.CLICK); - if (view != null) { - view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); - } - mOnItemClickListener.onItemClick(/*this*/null, view, position, id); - return true; - } - - return false; - } - - /** - * Interface definition for a callback to be invoked when an item in this - * view has been clicked and held. - */ - public interface OnItemLongClickListener { - /** - * Callback method to be invoked when an item in this view has been - * clicked and held. - * - * Implementers can call getItemAtPosition(position) if they need to access - * the data associated with the selected item. - * - * @param parent The AbsListView where the click happened - * @param view The view within the AbsListView that was clicked - * @param position The position of the view in the list - * @param id The row id of the item that was clicked - * - * @return true if the callback consumed the long click, false otherwise - */ - boolean onItemLongClick(IcsAdapterView parent, View view, int position, long id); - } - - - /** - * Register a callback to be invoked when an item in this AdapterView has - * been clicked and held - * - * @param listener The callback that will run - */ - public void setOnItemLongClickListener(OnItemLongClickListener listener) { - if (!isLongClickable()) { - setLongClickable(true); - } - mOnItemLongClickListener = listener; - } - - /** - * @return The callback to be invoked with an item in this AdapterView has - * been clicked and held, or null id no callback as been set. - */ - public final OnItemLongClickListener getOnItemLongClickListener() { - return mOnItemLongClickListener; - } - - /** - * Interface definition for a callback to be invoked when - * an item in this view has been selected. - */ - public interface OnItemSelectedListener { - /** - *

Callback method to be invoked when an item in this view has been - * selected. This callback is invoked only when the newly selected - * position is different from the previously selected position or if - * there was no selected item.

- * - * Impelmenters can call getItemAtPosition(position) if they need to access the - * data associated with the selected item. - * - * @param parent The AdapterView where the selection happened - * @param view The view within the AdapterView that was clicked - * @param position The position of the view in the adapter - * @param id The row id of the item that is selected - */ - void onItemSelected(IcsAdapterView parent, View view, int position, long id); - - /** - * Callback method to be invoked when the selection disappears from this - * view. The selection can disappear for instance when touch is activated - * or when the adapter becomes empty. - * - * @param parent The AdapterView that now contains no selected item. - */ - void onNothingSelected(IcsAdapterView parent); - } - - - /** - * Register a callback to be invoked when an item in this AdapterView has - * been selected. - * - * @param listener The callback that will run - */ - public void setOnItemSelectedListener(OnItemSelectedListener listener) { - mOnItemSelectedListener = listener; - } - - public final OnItemSelectedListener getOnItemSelectedListener() { - return mOnItemSelectedListener; - } - - /** - * Extra menu information provided to the - * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) } - * callback when a context menu is brought up for this AdapterView. - * - */ - public static class AdapterContextMenuInfo implements ContextMenu.ContextMenuInfo { - - public AdapterContextMenuInfo(View targetView, int position, long id) { - this.targetView = targetView; - this.position = position; - this.id = id; - } - - /** - * The child view for which the context menu is being displayed. This - * will be one of the children of this AdapterView. - */ - public View targetView; - - /** - * The position in the adapter for which the context menu is being - * displayed. - */ - public int position; - - /** - * The row id of the item for which the context menu is being displayed. - */ - public long id; - } - - /** - * Returns the adapter currently associated with this widget. - * - * @return The adapter used to provide this view's content. - */ - public abstract T getAdapter(); - - /** - * Sets the adapter that provides the data and the views to represent the data - * in this widget. - * - * @param adapter The adapter to use to create this view's content. - */ - public abstract void setAdapter(T adapter); - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @param child Ignored. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void addView(View child) { - throw new UnsupportedOperationException("addView(View) is not supported in AdapterView"); - } - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @param child Ignored. - * @param index Ignored. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void addView(View child, int index) { - throw new UnsupportedOperationException("addView(View, int) is not supported in AdapterView"); - } - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @param child Ignored. - * @param params Ignored. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void addView(View child, LayoutParams params) { - throw new UnsupportedOperationException("addView(View, LayoutParams) " - + "is not supported in AdapterView"); - } - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @param child Ignored. - * @param index Ignored. - * @param params Ignored. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void addView(View child, int index, LayoutParams params) { - throw new UnsupportedOperationException("addView(View, int, LayoutParams) " - + "is not supported in AdapterView"); - } - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @param child Ignored. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void removeView(View child) { - throw new UnsupportedOperationException("removeView(View) is not supported in AdapterView"); - } - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @param index Ignored. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void removeViewAt(int index) { - throw new UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView"); - } - - /** - * This method is not supported and throws an UnsupportedOperationException when called. - * - * @throws UnsupportedOperationException Every time this method is invoked. - */ - @Override - public void removeAllViews() { - throw new UnsupportedOperationException("removeAllViews() is not supported in AdapterView"); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - mLayoutHeight = getHeight(); - } - - /** - * Return the position of the currently selected item within the adapter's data set - * - * @return int Position (starting at 0), or {@link #INVALID_POSITION} if there is nothing selected. - */ - @ViewDebug.CapturedViewProperty - public int getSelectedItemPosition() { - return mNextSelectedPosition; - } - - /** - * @return The id corresponding to the currently selected item, or {@link #INVALID_ROW_ID} - * if nothing is selected. - */ - @ViewDebug.CapturedViewProperty - public long getSelectedItemId() { - return mNextSelectedRowId; - } - - /** - * @return The view corresponding to the currently selected item, or null - * if nothing is selected - */ - public abstract View getSelectedView(); - - /** - * @return The data corresponding to the currently selected item, or - * null if there is nothing selected. - */ - public Object getSelectedItem() { - T adapter = getAdapter(); - int selection = getSelectedItemPosition(); - if (adapter != null && adapter.getCount() > 0 && selection >= 0) { - return adapter.getItem(selection); - } else { - return null; - } - } - - /** - * @return The number of items owned by the Adapter associated with this - * AdapterView. (This is the number of data items, which may be - * larger than the number of visible views.) - */ - @ViewDebug.CapturedViewProperty - public int getCount() { - return mItemCount; - } - - /** - * Get the position within the adapter's data set for the view, where view is a an adapter item - * or a descendant of an adapter item. - * - * @param view an adapter item, or a descendant of an adapter item. This must be visible in this - * AdapterView at the time of the call. - * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION} - * if the view does not correspond to a list item (or it is not currently visible). - */ - public int getPositionForView(View view) { - View listItem = view; - try { - View v; - while (!(v = (View) listItem.getParent()).equals(this)) { - listItem = v; - } - } catch (ClassCastException e) { - // We made it up to the window without find this list view - return INVALID_POSITION; - } - - // Search the children for the list item - final int childCount = getChildCount(); - for (int i = 0; i < childCount; i++) { - if (getChildAt(i).equals(listItem)) { - return mFirstPosition + i; - } - } - - // Child not found! - return INVALID_POSITION; - } - - /** - * Returns the position within the adapter's data set for the first item - * displayed on screen. - * - * @return The position within the adapter's data set - */ - public int getFirstVisiblePosition() { - return mFirstPosition; - } - - /** - * Returns the position within the adapter's data set for the last item - * displayed on screen. - * - * @return The position within the adapter's data set - */ - public int getLastVisiblePosition() { - return mFirstPosition + getChildCount() - 1; - } - - /** - * Sets the currently selected item. To support accessibility subclasses that - * override this method must invoke the overriden super method first. - * - * @param position Index (starting at 0) of the data item to be selected. - */ - public abstract void setSelection(int position); - - /** - * Sets the view to show if the adapter is empty - */ - public void setEmptyView(View emptyView) { - mEmptyView = emptyView; - - final T adapter = getAdapter(); - final boolean empty = ((adapter == null) || adapter.isEmpty()); - updateEmptyStatus(empty); - } - - /** - * When the current adapter is empty, the AdapterView can display a special view - * call the empty view. The empty view is used to provide feedback to the user - * that no data is available in this AdapterView. - * - * @return The view to show if the adapter is empty. - */ - public View getEmptyView() { - return mEmptyView; - } - - /** - * Indicates whether this view is in filter mode. Filter mode can for instance - * be enabled by a user when typing on the keyboard. - * - * @return True if the view is in filter mode, false otherwise. - */ - boolean isInFilterMode() { - return false; - } - - @Override - public void setFocusable(boolean focusable) { - final T adapter = getAdapter(); - final boolean empty = adapter == null || adapter.getCount() == 0; - - mDesiredFocusableState = focusable; - if (!focusable) { - mDesiredFocusableInTouchModeState = false; - } - - super.setFocusable(focusable && (!empty || isInFilterMode())); - } - - @Override - public void setFocusableInTouchMode(boolean focusable) { - final T adapter = getAdapter(); - final boolean empty = adapter == null || adapter.getCount() == 0; - - mDesiredFocusableInTouchModeState = focusable; - if (focusable) { - mDesiredFocusableState = true; - } - - super.setFocusableInTouchMode(focusable && (!empty || isInFilterMode())); - } - - void checkFocus() { - final T adapter = getAdapter(); - final boolean empty = adapter == null || adapter.getCount() == 0; - final boolean focusable = !empty || isInFilterMode(); - // The order in which we set focusable in touch mode/focusable may matter - // for the client, see View.setFocusableInTouchMode() comments for more - // details - super.setFocusableInTouchMode(focusable && mDesiredFocusableInTouchModeState); - super.setFocusable(focusable && mDesiredFocusableState); - if (mEmptyView != null) { - updateEmptyStatus((adapter == null) || adapter.isEmpty()); - } - } - - /** - * Update the status of the list based on the empty parameter. If empty is true and - * we have an empty view, display it. In all the other cases, make sure that the listview - * is VISIBLE and that the empty view is GONE (if it's not null). - */ - private void updateEmptyStatus(boolean empty) { - if (isInFilterMode()) { - empty = false; - } - - if (empty) { - if (mEmptyView != null) { - mEmptyView.setVisibility(View.VISIBLE); - setVisibility(View.GONE); - } else { - // If the caller just removed our empty view, make sure the list view is visible - setVisibility(View.VISIBLE); - } - - // We are now GONE, so pending layouts will not be dispatched. - // Force one here to make sure that the state of the list matches - // the state of the adapter. - if (mDataChanged) { - this.onLayout(false, getLeft(), getTop(), getRight(), getBottom()); - } - } else { - if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); - setVisibility(View.VISIBLE); - } - } - - /** - * Gets the data associated with the specified position in the list. - * - * @param position Which data to get - * @return The data associated with the specified position in the list - */ - public Object getItemAtPosition(int position) { - T adapter = getAdapter(); - return (adapter == null || position < 0) ? null : adapter.getItem(position); - } - - public long getItemIdAtPosition(int position) { - T adapter = getAdapter(); - return (adapter == null || position < 0) ? INVALID_ROW_ID : adapter.getItemId(position); - } - - @Override - public void setOnClickListener(OnClickListener l) { - throw new RuntimeException("Don't call setOnClickListener for an AdapterView. " - + "You probably want setOnItemClickListener instead"); - } - - /** - * Override to prevent freezing of any views created by the adapter. - */ - @Override - protected void dispatchSaveInstanceState(SparseArray container) { - dispatchFreezeSelfOnly(container); - } - - /** - * Override to prevent thawing of any views created by the adapter. - */ - @Override - protected void dispatchRestoreInstanceState(SparseArray container) { - dispatchThawSelfOnly(container); - } - - class AdapterDataSetObserver extends DataSetObserver { - - private Parcelable mInstanceState = null; - - @Override - public void onChanged() { - mDataChanged = true; - mOldItemCount = mItemCount; - mItemCount = getAdapter().getCount(); - - // Detect the case where a cursor that was previously invalidated has - // been repopulated with new data. - if (IcsAdapterView.this.getAdapter().hasStableIds() && mInstanceState != null - && mOldItemCount == 0 && mItemCount > 0) { - IcsAdapterView.this.onRestoreInstanceState(mInstanceState); - mInstanceState = null; - } else { - rememberSyncState(); - } - checkFocus(); - requestLayout(); - } - - @Override - public void onInvalidated() { - mDataChanged = true; - - if (IcsAdapterView.this.getAdapter().hasStableIds()) { - // Remember the current state for the case where our hosting activity is being - // stopped and later restarted - mInstanceState = IcsAdapterView.this.onSaveInstanceState(); - } - - // Data is invalid so we should reset our state - mOldItemCount = mItemCount; - mItemCount = 0; - mSelectedPosition = INVALID_POSITION; - mSelectedRowId = INVALID_ROW_ID; - mNextSelectedPosition = INVALID_POSITION; - mNextSelectedRowId = INVALID_ROW_ID; - mNeedSync = false; - - checkFocus(); - requestLayout(); - } - - public void clearSavedState() { - mInstanceState = null; - } - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - removeCallbacks(mSelectionNotifier); - } - - private class SelectionNotifier implements Runnable { - public void run() { - if (mDataChanged) { - // Data has changed between when this SelectionNotifier - // was posted and now. We need to wait until the AdapterView - // has been synched to the new data. - if (getAdapter() != null) { - post(this); - } - } else { - fireOnSelected(); - } - } - } - - void selectionChanged() { - if (mOnItemSelectedListener != null) { - if (mInLayout || mBlockLayoutRequests) { - // If we are in a layout traversal, defer notification - // by posting. This ensures that the view tree is - // in a consistent state and is able to accomodate - // new layout or invalidate requests. - if (mSelectionNotifier == null) { - mSelectionNotifier = new SelectionNotifier(); - } - post(mSelectionNotifier); - } else { - fireOnSelected(); - } - } - - // we fire selection events here not in View - if (mSelectedPosition != ListView.INVALID_POSITION && isShown() && !isInTouchMode()) { - sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); - } - } - - private void fireOnSelected() { - if (mOnItemSelectedListener == null) - return; - - int selection = this.getSelectedItemPosition(); - if (selection >= 0) { - View v = getSelectedView(); - mOnItemSelectedListener.onItemSelected(this, v, selection, - getAdapter().getItemId(selection)); - } else { - mOnItemSelectedListener.onNothingSelected(this); - } - } - - @Override - public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { - View selectedView = getSelectedView(); - if (selectedView != null && selectedView.getVisibility() == VISIBLE - && selectedView.dispatchPopulateAccessibilityEvent(event)) { - return true; - } - return false; - } - - @Override - public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { - if (super.onRequestSendAccessibilityEvent(child, event)) { - // Add a record for ourselves as well. - AccessibilityEvent record = AccessibilityEvent.obtain(); - onInitializeAccessibilityEvent(record); - // Populate with the text of the requesting child. - child.dispatchPopulateAccessibilityEvent(record); - event.appendRecord(record); - return true; - } - return false; - } - - @Override - public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { - super.onInitializeAccessibilityNodeInfo(info); - info.setScrollable(isScrollableForAccessibility()); - View selectedView = getSelectedView(); - if (selectedView != null) { - info.setEnabled(selectedView.isEnabled()); - } - } - - @Override - public void onInitializeAccessibilityEvent(AccessibilityEvent event) { - super.onInitializeAccessibilityEvent(event); - event.setScrollable(isScrollableForAccessibility()); - View selectedView = getSelectedView(); - if (selectedView != null) { - event.setEnabled(selectedView.isEnabled()); - } - event.setCurrentItemIndex(getSelectedItemPosition()); - event.setFromIndex(getFirstVisiblePosition()); - event.setToIndex(getLastVisiblePosition()); - event.setItemCount(getCount()); - } - - private boolean isScrollableForAccessibility() { - T adapter = getAdapter(); - if (adapter != null) { - final int itemCount = adapter.getCount(); - return itemCount > 0 - && (getFirstVisiblePosition() > 0 || getLastVisiblePosition() < itemCount - 1); - } - return false; - } - - @Override - protected boolean canAnimate() { - return super.canAnimate() && mItemCount > 0; - } - - void handleDataChanged() { - final int count = mItemCount; - boolean found = false; - - if (count > 0) { - - int newPos; - - // Find the row we are supposed to sync to - if (mNeedSync) { - // Update this first, since setNextSelectedPositionInt inspects - // it - mNeedSync = false; - - // See if we can find a position in the new data with the same - // id as the old selection - newPos = findSyncPosition(); - if (newPos >= 0) { - // Verify that new selection is selectable - int selectablePos = lookForSelectablePosition(newPos, true); - if (selectablePos == newPos) { - // Same row id is selected - setNextSelectedPositionInt(newPos); - found = true; - } - } - } - if (!found) { - // Try to use the same position if we can't find matching data - newPos = getSelectedItemPosition(); - - // Pin position to the available range - if (newPos >= count) { - newPos = count - 1; - } - if (newPos < 0) { - newPos = 0; - } - - // Make sure we select something selectable -- first look down - int selectablePos = lookForSelectablePosition(newPos, true); - if (selectablePos < 0) { - // Looking down didn't work -- try looking up - selectablePos = lookForSelectablePosition(newPos, false); - } - if (selectablePos >= 0) { - setNextSelectedPositionInt(selectablePos); - checkSelectionChanged(); - found = true; - } - } - } - if (!found) { - // Nothing is selected - mSelectedPosition = INVALID_POSITION; - mSelectedRowId = INVALID_ROW_ID; - mNextSelectedPosition = INVALID_POSITION; - mNextSelectedRowId = INVALID_ROW_ID; - mNeedSync = false; - checkSelectionChanged(); - } - } - - void checkSelectionChanged() { - if ((mSelectedPosition != mOldSelectedPosition) || (mSelectedRowId != mOldSelectedRowId)) { - selectionChanged(); - mOldSelectedPosition = mSelectedPosition; - mOldSelectedRowId = mSelectedRowId; - } - } - - /** - * Searches the adapter for a position matching mSyncRowId. The search starts at mSyncPosition - * and then alternates between moving up and moving down until 1) we find the right position, or - * 2) we run out of time, or 3) we have looked at every position - * - * @return Position of the row that matches mSyncRowId, or {@link #INVALID_POSITION} if it can't - * be found - */ - int findSyncPosition() { - int count = mItemCount; - - if (count == 0) { - return INVALID_POSITION; - } - - long idToMatch = mSyncRowId; - int seed = mSyncPosition; - - // If there isn't a selection don't hunt for it - if (idToMatch == INVALID_ROW_ID) { - return INVALID_POSITION; - } - - // Pin seed to reasonable values - seed = Math.max(0, seed); - seed = Math.min(count - 1, seed); - - long endTime = SystemClock.uptimeMillis() + SYNC_MAX_DURATION_MILLIS; - - long rowId; - - // first position scanned so far - int first = seed; - - // last position scanned so far - int last = seed; - - // True if we should move down on the next iteration - boolean next = false; - - // True when we have looked at the first item in the data - boolean hitFirst; - - // True when we have looked at the last item in the data - boolean hitLast; - - // Get the item ID locally (instead of getItemIdAtPosition), so - // we need the adapter - T adapter = getAdapter(); - if (adapter == null) { - return INVALID_POSITION; - } - - while (SystemClock.uptimeMillis() <= endTime) { - rowId = adapter.getItemId(seed); - if (rowId == idToMatch) { - // Found it! - return seed; - } - - hitLast = last == count - 1; - hitFirst = first == 0; - - if (hitLast && hitFirst) { - // Looked at everything - break; - } - - if (hitFirst || (next && !hitLast)) { - // Either we hit the top, or we are trying to move down - last++; - seed = last; - // Try going up next time - next = false; - } else if (hitLast || (!next && !hitFirst)) { - // Either we hit the bottom, or we are trying to move up - first--; - seed = first; - // Try going down next time - next = true; - } - - } - - return INVALID_POSITION; - } - - /** - * Find a position that can be selected (i.e., is not a separator). - * - * @param position The starting position to look at. - * @param lookDown Whether to look down for other positions. - * @return The next selectable position starting at position and then searching either up or - * down. Returns {@link #INVALID_POSITION} if nothing can be found. - */ - int lookForSelectablePosition(int position, boolean lookDown) { - return position; - } - - /** - * Utility to keep mSelectedPosition and mSelectedRowId in sync - * @param position Our current position - */ - void setSelectedPositionInt(int position) { - mSelectedPosition = position; - mSelectedRowId = getItemIdAtPosition(position); - } - - /** - * Utility to keep mNextSelectedPosition and mNextSelectedRowId in sync - * @param position Intended value for mSelectedPosition the next time we go - * through layout - */ - void setNextSelectedPositionInt(int position) { - mNextSelectedPosition = position; - mNextSelectedRowId = getItemIdAtPosition(position); - // If we are trying to sync to the selection, update that too - if (mNeedSync && mSyncMode == SYNC_SELECTED_POSITION && position >= 0) { - mSyncPosition = position; - mSyncRowId = mNextSelectedRowId; - } - } - - /** - * Remember enough information to restore the screen state when the data has - * changed. - * - */ - void rememberSyncState() { - if (getChildCount() > 0) { - mNeedSync = true; - mSyncHeight = mLayoutHeight; - if (mSelectedPosition >= 0) { - // Sync the selection state - View v = getChildAt(mSelectedPosition - mFirstPosition); - mSyncRowId = mNextSelectedRowId; - mSyncPosition = mNextSelectedPosition; - if (v != null) { - mSpecificTop = v.getTop(); - } - mSyncMode = SYNC_SELECTED_POSITION; - } else { - // Sync the based on the offset of the first view - View v = getChildAt(0); - T adapter = getAdapter(); - if (mFirstPosition >= 0 && mFirstPosition < adapter.getCount()) { - mSyncRowId = adapter.getItemId(mFirstPosition); - } else { - mSyncRowId = NO_ID; - } - mSyncPosition = mFirstPosition; - if (v != null) { - mSpecificTop = v.getTop(); - } - mSyncMode = SYNC_FIRST_POSITION; - } - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsLinearLayout.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsLinearLayout.java deleted file mode 100644 index 1b4463a5..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsLinearLayout.java +++ /dev/null @@ -1,272 +0,0 @@ -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.View; -import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; - -/** - * A simple extension of a regular linear layout that supports the divider API - * of Android 4.0+. The dividers are added adjacent to the children by changing - * their layout params. If you need to rely on the margins which fall in the - * same orientation as the layout you should wrap the child in a simple - * {@link android.widget.FrameLayout} so it can receive the margin. - */ -public class IcsLinearLayout extends NineLinearLayout { - private static final int[] LinearLayout = new int[] { - /* 0 */ android.R.attr.divider, - /* 1 */ android.R.attr.showDividers, - /* 2 */ android.R.attr.dividerPadding, - }; - private static final int LinearLayout_divider = 0; - private static final int LinearLayout_showDividers = 1; - private static final int LinearLayout_dividerPadding = 2; - - /** - * Don't show any dividers. - */ - public static final int SHOW_DIVIDER_NONE = 0; - /** - * Show a divider at the beginning of the group. - */ - public static final int SHOW_DIVIDER_BEGINNING = 1; - /** - * Show dividers between each item in the group. - */ - public static final int SHOW_DIVIDER_MIDDLE = 2; - /** - * Show a divider at the end of the group. - */ - public static final int SHOW_DIVIDER_END = 4; - - - private Drawable mDivider; - private int mDividerWidth; - private int mDividerHeight; - private int mShowDividers; - private int mDividerPadding; - - - public IcsLinearLayout(Context context, AttributeSet attrs) { - super(context, attrs); - - TypedArray a = context.obtainStyledAttributes(attrs, /*com.android.internal.R.styleable.*/LinearLayout); - - setDividerDrawable(a.getDrawable(/*com.android.internal.R.styleable.*/LinearLayout_divider)); - mShowDividers = a.getInt(/*com.android.internal.R.styleable.*/LinearLayout_showDividers, SHOW_DIVIDER_NONE); - mDividerPadding = a.getDimensionPixelSize(/*com.android.internal.R.styleable.*/LinearLayout_dividerPadding, 0); - - a.recycle(); - } - - /** - * Set how dividers should be shown between items in this layout - * - * @param showDividers One or more of {@link #SHOW_DIVIDER_BEGINNING}, - * {@link #SHOW_DIVIDER_MIDDLE}, or {@link #SHOW_DIVIDER_END}, - * or {@link #SHOW_DIVIDER_NONE} to show no dividers. - */ - public void setShowDividers(int showDividers) { - if (showDividers != mShowDividers) { - requestLayout(); - invalidate(); //XXX This is required if you are toggling a divider off - } - mShowDividers = showDividers; - } - - /** - * @return A flag set indicating how dividers should be shown around items. - * @see #setShowDividers(int) - */ - public int getShowDividers() { - return mShowDividers; - } - - /** - * Set a drawable to be used as a divider between items. - * @param divider Drawable that will divide each item. - * @see #setShowDividers(int) - */ - public void setDividerDrawable(Drawable divider) { - if (divider == mDivider) { - return; - } - mDivider = divider; - if (divider != null) { - mDividerWidth = divider.getIntrinsicWidth(); - mDividerHeight = divider.getIntrinsicHeight(); - } else { - mDividerWidth = 0; - mDividerHeight = 0; - } - setWillNotDraw(divider == null); - requestLayout(); - } - - /** - * Set padding displayed on both ends of dividers. - * - * @param padding Padding value in pixels that will be applied to each end - * - * @see #setShowDividers(int) - * @see #setDividerDrawable(Drawable) - * @see #getDividerPadding() - */ - public void setDividerPadding(int padding) { - mDividerPadding = padding; - } - - /** - * Get the padding size used to inset dividers in pixels - * - * @see #setShowDividers(int) - * @see #setDividerDrawable(Drawable) - * @see #setDividerPadding(int) - */ - public int getDividerPadding() { - return mDividerPadding; - } - - /** - * Get the width of the current divider drawable. - * - * @hide Used internally by framework. - */ - public int getDividerWidth() { - return mDividerWidth; - } - - @Override - protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { - final int index = indexOfChild(child); - final int orientation = getOrientation(); - final LayoutParams params = (LayoutParams) child.getLayoutParams(); - if (hasDividerBeforeChildAt(index)) { - if (orientation == VERTICAL) { - //Account for the divider by pushing everything up - params.topMargin = mDividerHeight; - } else { - //Account for the divider by pushing everything left - params.leftMargin = mDividerWidth; - } - } - - final int count = getChildCount(); - if (index == count - 1) { - if (hasDividerBeforeChildAt(count)) { - if (orientation == VERTICAL) { - params.bottomMargin = mDividerHeight; - } else { - params.rightMargin = mDividerWidth; - } - } - } - super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed); - } - - @Override - protected void onDraw(Canvas canvas) { - if (mDivider != null) { - if (getOrientation() == VERTICAL) { - drawDividersVertical(canvas); - } else { - drawDividersHorizontal(canvas); - } - } - super.onDraw(canvas); - } - - void drawDividersVertical(Canvas canvas) { - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - - if (child != null && child.getVisibility() != GONE) { - if (hasDividerBeforeChildAt(i)) { - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - final int top = child.getTop() - lp.topMargin/* - mDividerHeight*/; - drawHorizontalDivider(canvas, top); - } - } - } - - if (hasDividerBeforeChildAt(count)) { - final View child = getChildAt(count - 1); - int bottom = 0; - if (child == null) { - bottom = getHeight() - getPaddingBottom() - mDividerHeight; - } else { - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - bottom = child.getBottom()/* + lp.bottomMargin*/; - } - drawHorizontalDivider(canvas, bottom); - } - } - - void drawDividersHorizontal(Canvas canvas) { - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - final View child = getChildAt(i); - - if (child != null && child.getVisibility() != GONE) { - if (hasDividerBeforeChildAt(i)) { - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - final int left = child.getLeft() - lp.leftMargin/* - mDividerWidth*/; - drawVerticalDivider(canvas, left); - } - } - } - - if (hasDividerBeforeChildAt(count)) { - final View child = getChildAt(count - 1); - int right = 0; - if (child == null) { - right = getWidth() - getPaddingRight() - mDividerWidth; - } else { - final LayoutParams lp = (LayoutParams) child.getLayoutParams(); - right = child.getRight()/* + lp.rightMargin*/; - } - drawVerticalDivider(canvas, right); - } - } - - void drawHorizontalDivider(Canvas canvas, int top) { - mDivider.setBounds(getPaddingLeft() + mDividerPadding, top, - getWidth() - getPaddingRight() - mDividerPadding, top + mDividerHeight); - mDivider.draw(canvas); - } - - void drawVerticalDivider(Canvas canvas, int left) { - mDivider.setBounds(left, getPaddingTop() + mDividerPadding, - left + mDividerWidth, getHeight() - getPaddingBottom() - mDividerPadding); - mDivider.draw(canvas); - } - - /** - * Determines where to position dividers between children. - * - * @param childIndex Index of child to check for preceding divider - * @return true if there should be a divider before the child at childIndex - * @hide Pending API consideration. Currently only used internally by the system. - */ - protected boolean hasDividerBeforeChildAt(int childIndex) { - if (childIndex == 0) { - return (mShowDividers & SHOW_DIVIDER_BEGINNING) != 0; - } else if (childIndex == getChildCount()) { - return (mShowDividers & SHOW_DIVIDER_END) != 0; - } else if ((mShowDividers & SHOW_DIVIDER_MIDDLE) != 0) { - boolean hasVisibleViewBefore = false; - for (int i = childIndex - 1; i >= 0; i--) { - if (getChildAt(i).getVisibility() != GONE) { - hasVisibleViewBefore = true; - break; - } - } - return hasVisibleViewBefore; - } - return false; - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsListPopupWindow.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsListPopupWindow.java deleted file mode 100644 index d13c6cea..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsListPopupWindow.java +++ /dev/null @@ -1,644 +0,0 @@ -package com.actionbarsherlock.internal.widget; - -import com.actionbarsherlock.R; - -import android.content.Context; -import android.content.res.Resources; -import android.database.DataSetObserver; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.os.Handler; -import android.util.AttributeSet; -import android.view.ContextThemeWrapper; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.MeasureSpec; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.view.ViewParent; -import android.widget.AbsListView; -import android.widget.AdapterView; -import android.widget.LinearLayout; -import android.widget.ListAdapter; -import android.widget.ListView; -import android.widget.PopupWindow; - -/** - * A proxy between pre- and post-Honeycomb implementations of this class. - */ -public class IcsListPopupWindow { - /** - * This value controls the length of time that the user - * must leave a pointer down without scrolling to expand - * the autocomplete dropdown list to cover the IME. - */ - private static final int EXPAND_LIST_TIMEOUT = 250; - - private Context mContext; - private PopupWindow mPopup; - private ListAdapter mAdapter; - private DropDownListView mDropDownList; - - private int mDropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT; - private int mDropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT; - private int mDropDownHorizontalOffset; - private int mDropDownVerticalOffset; - private boolean mDropDownVerticalOffsetSet; - - private int mListItemExpandMaximum = Integer.MAX_VALUE; - - private View mPromptView; - private int mPromptPosition = POSITION_PROMPT_ABOVE; - - private DataSetObserver mObserver; - - private View mDropDownAnchorView; - - private Drawable mDropDownListHighlight; - - private AdapterView.OnItemClickListener mItemClickListener; - private AdapterView.OnItemSelectedListener mItemSelectedListener; - - private final ResizePopupRunnable mResizePopupRunnable = new ResizePopupRunnable(); - private final PopupTouchInterceptor mTouchInterceptor = new PopupTouchInterceptor(); - private final PopupScrollListener mScrollListener = new PopupScrollListener(); - private final ListSelectorHider mHideSelector = new ListSelectorHider(); - - private Handler mHandler = new Handler(); - - private Rect mTempRect = new Rect(); - - private boolean mModal; - - public static final int POSITION_PROMPT_ABOVE = 0; - public static final int POSITION_PROMPT_BELOW = 1; - - public IcsListPopupWindow(Context context) { - this(context, null, R.attr.listPopupWindowStyle); - } - - public IcsListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr) { - mContext = context; - mPopup = new PopupWindow(context, attrs, defStyleAttr); - mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); - } - - public IcsListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - mContext = context; - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { - Context wrapped = new ContextThemeWrapper(context, defStyleRes); - mPopup = new PopupWindow(wrapped, attrs, defStyleAttr); - } else { - mPopup = new PopupWindow(context, attrs, defStyleAttr, defStyleRes); - } - mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); - } - - public void setAdapter(ListAdapter adapter) { - if (mObserver == null) { - mObserver = new PopupDataSetObserver(); - } else if (mAdapter != null) { - mAdapter.unregisterDataSetObserver(mObserver); - } - mAdapter = adapter; - if (mAdapter != null) { - adapter.registerDataSetObserver(mObserver); - } - - if (mDropDownList != null) { - mDropDownList.setAdapter(mAdapter); - } - } - - public void setPromptPosition(int position) { - mPromptPosition = position; - } - - public void setModal(boolean modal) { - mModal = true; - mPopup.setFocusable(modal); - } - - public void setBackgroundDrawable(Drawable d) { - mPopup.setBackgroundDrawable(d); - } - - public void setAnchorView(View anchor) { - mDropDownAnchorView = anchor; - } - - public void setHorizontalOffset(int offset) { - mDropDownHorizontalOffset = offset; - } - - public void setVerticalOffset(int offset) { - mDropDownVerticalOffset = offset; - mDropDownVerticalOffsetSet = true; - } - - public void setContentWidth(int width) { - Drawable popupBackground = mPopup.getBackground(); - if (popupBackground != null) { - popupBackground.getPadding(mTempRect); - mDropDownWidth = mTempRect.left + mTempRect.right + width; - } else { - mDropDownWidth = width; - } - } - - public void setOnItemClickListener(AdapterView.OnItemClickListener clickListener) { - mItemClickListener = clickListener; - } - - public void show() { - int height = buildDropDown(); - - int widthSpec = 0; - int heightSpec = 0; - - boolean noInputMethod = isInputMethodNotNeeded(); - //XXX mPopup.setAllowScrollingAnchorParent(!noInputMethod); - - if (mPopup.isShowing()) { - if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { - // The call to PopupWindow's update method below can accept -1 for any - // value you do not want to update. - widthSpec = -1; - } else if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { - widthSpec = mDropDownAnchorView.getWidth(); - } else { - widthSpec = mDropDownWidth; - } - - if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { - // The call to PopupWindow's update method below can accept -1 for any - // value you do not want to update. - heightSpec = noInputMethod ? height : ViewGroup.LayoutParams.MATCH_PARENT; - if (noInputMethod) { - mPopup.setWindowLayoutMode( - mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? - ViewGroup.LayoutParams.MATCH_PARENT : 0, 0); - } else { - mPopup.setWindowLayoutMode( - mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? - ViewGroup.LayoutParams.MATCH_PARENT : 0, - ViewGroup.LayoutParams.MATCH_PARENT); - } - } else if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { - heightSpec = height; - } else { - heightSpec = mDropDownHeight; - } - - mPopup.setOutsideTouchable(true); - - mPopup.update(mDropDownAnchorView, mDropDownHorizontalOffset, - mDropDownVerticalOffset, widthSpec, heightSpec); - } else { - if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { - widthSpec = ViewGroup.LayoutParams.MATCH_PARENT; - } else { - if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { - mPopup.setWidth(mDropDownAnchorView.getWidth()); - } else { - mPopup.setWidth(mDropDownWidth); - } - } - - if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { - heightSpec = ViewGroup.LayoutParams.MATCH_PARENT; - } else { - if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { - mPopup.setHeight(height); - } else { - mPopup.setHeight(mDropDownHeight); - } - } - - mPopup.setWindowLayoutMode(widthSpec, heightSpec); - //XXX mPopup.setClipToScreenEnabled(true); - - // use outside touchable to dismiss drop down when touching outside of it, so - // only set this if the dropdown is not always visible - mPopup.setOutsideTouchable(true); - mPopup.setTouchInterceptor(mTouchInterceptor); - mPopup.showAsDropDown(mDropDownAnchorView, - mDropDownHorizontalOffset, mDropDownVerticalOffset); - mDropDownList.setSelection(ListView.INVALID_POSITION); - - if (!mModal || mDropDownList.isInTouchMode()) { - clearListSelection(); - } - if (!mModal) { - mHandler.post(mHideSelector); - } - } - } - - public void dismiss() { - mPopup.dismiss(); - if (mPromptView != null) { - final ViewParent parent = mPromptView.getParent(); - if (parent instanceof ViewGroup) { - final ViewGroup group = (ViewGroup) parent; - group.removeView(mPromptView); - } - } - mPopup.setContentView(null); - mDropDownList = null; - mHandler.removeCallbacks(mResizePopupRunnable); - } - - public void setOnDismissListener(PopupWindow.OnDismissListener listener) { - mPopup.setOnDismissListener(listener); - } - - public void setInputMethodMode(int mode) { - mPopup.setInputMethodMode(mode); - } - - public void clearListSelection() { - final DropDownListView list = mDropDownList; - if (list != null) { - // WARNING: Please read the comment where mListSelectionHidden is declared - list.mListSelectionHidden = true; - //XXX list.hideSelector(); - list.requestLayout(); - } - } - - public boolean isShowing() { - return mPopup.isShowing(); - } - - private boolean isInputMethodNotNeeded() { - return mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; - } - - public ListView getListView() { - return mDropDownList; - } - - private int buildDropDown() { - ViewGroup dropDownView; - int otherHeights = 0; - - if (mDropDownList == null) { - Context context = mContext; - - mDropDownList = new DropDownListView(context, !mModal); - if (mDropDownListHighlight != null) { - mDropDownList.setSelector(mDropDownListHighlight); - } - mDropDownList.setAdapter(mAdapter); - mDropDownList.setOnItemClickListener(mItemClickListener); - mDropDownList.setFocusable(true); - mDropDownList.setFocusableInTouchMode(true); - mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - public void onItemSelected(AdapterView parent, View view, - int position, long id) { - - if (position != -1) { - DropDownListView dropDownList = mDropDownList; - - if (dropDownList != null) { - dropDownList.mListSelectionHidden = false; - } - } - } - - public void onNothingSelected(AdapterView parent) { - } - }); - mDropDownList.setOnScrollListener(mScrollListener); - - if (mItemSelectedListener != null) { - mDropDownList.setOnItemSelectedListener(mItemSelectedListener); - } - - dropDownView = mDropDownList; - - View hintView = mPromptView; - if (hintView != null) { - // if an hint has been specified, we accomodate more space for it and - // add a text view in the drop down menu, at the bottom of the list - LinearLayout hintContainer = new LinearLayout(context); - hintContainer.setOrientation(LinearLayout.VERTICAL); - - LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f - ); - - switch (mPromptPosition) { - case POSITION_PROMPT_BELOW: - hintContainer.addView(dropDownView, hintParams); - hintContainer.addView(hintView); - break; - - case POSITION_PROMPT_ABOVE: - hintContainer.addView(hintView); - hintContainer.addView(dropDownView, hintParams); - break; - - default: - break; - } - - // measure the hint's height to find how much more vertical space - // we need to add to the drop down's height - int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST); - int heightSpec = MeasureSpec.UNSPECIFIED; - hintView.measure(widthSpec, heightSpec); - - hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams(); - otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin - + hintParams.bottomMargin; - - dropDownView = hintContainer; - } - - mPopup.setContentView(dropDownView); - } else { - dropDownView = (ViewGroup) mPopup.getContentView(); - final View view = mPromptView; - if (view != null) { - LinearLayout.LayoutParams hintParams = - (LinearLayout.LayoutParams) view.getLayoutParams(); - otherHeights = view.getMeasuredHeight() + hintParams.topMargin - + hintParams.bottomMargin; - } - } - - // getMaxAvailableHeight() subtracts the padding, so we put it back - // to get the available height for the whole window - int padding = 0; - Drawable background = mPopup.getBackground(); - if (background != null) { - background.getPadding(mTempRect); - padding = mTempRect.top + mTempRect.bottom; - - // If we don't have an explicit vertical offset, determine one from the window - // background so that content will line up. - if (!mDropDownVerticalOffsetSet) { - mDropDownVerticalOffset = -mTempRect.top; - } - } - - // Max height available on the screen for a popup. - boolean ignoreBottomDecorations = - mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; - final int maxHeight = /*mPopup.*/getMaxAvailableHeight( - mDropDownAnchorView, mDropDownVerticalOffset, ignoreBottomDecorations); - - if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { - return maxHeight + padding; - } - - final int listContent = /*mDropDownList.*/measureHeightOfChildren(MeasureSpec.UNSPECIFIED, - 0, -1/*ListView.NO_POSITION*/, maxHeight - otherHeights, -1); - // add padding only if the list has items in it, that way we don't show - // the popup if it is not needed - if (listContent > 0) otherHeights += padding; - - return listContent + otherHeights; - } - - private int getMaxAvailableHeight(View anchor, int yOffset, boolean ignoreBottomDecorations) { - final Rect displayFrame = new Rect(); - anchor.getWindowVisibleDisplayFrame(displayFrame); - - final int[] anchorPos = new int[2]; - anchor.getLocationOnScreen(anchorPos); - - int bottomEdge = displayFrame.bottom; - if (ignoreBottomDecorations) { - Resources res = anchor.getContext().getResources(); - bottomEdge = res.getDisplayMetrics().heightPixels; - } - final int distanceToBottom = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset; - final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset; - - // anchorPos[1] is distance from anchor to top of screen - int returnedHeight = Math.max(distanceToBottom, distanceToTop); - if (mPopup.getBackground() != null) { - mPopup.getBackground().getPadding(mTempRect); - returnedHeight -= mTempRect.top + mTempRect.bottom; - } - - return returnedHeight; - } - - private int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition, - final int maxHeight, int disallowPartialChildPosition) { - - final ListAdapter adapter = mAdapter; - if (adapter == null) { - return mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom(); - } - - // Include the padding of the list - int returnedHeight = mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom(); - final int dividerHeight = ((mDropDownList.getDividerHeight() > 0) && mDropDownList.getDivider() != null) ? mDropDownList.getDividerHeight() : 0; - // The previous height value that was less than maxHeight and contained - // no partial children - int prevHeightWithoutPartialChild = 0; - int i; - View child; - - // mItemCount - 1 since endPosition parameter is inclusive - endPosition = (endPosition == -1/*NO_POSITION*/) ? adapter.getCount() - 1 : endPosition; - - for (i = startPosition; i <= endPosition; ++i) { - child = mAdapter.getView(i, null, mDropDownList); - if (mDropDownList.getCacheColorHint() != 0) { - child.setDrawingCacheBackgroundColor(mDropDownList.getCacheColorHint()); - } - - measureScrapChild(child, i, widthMeasureSpec); - - if (i > 0) { - // Count the divider for all but one child - returnedHeight += dividerHeight; - } - - returnedHeight += child.getMeasuredHeight(); - - if (returnedHeight >= maxHeight) { - // We went over, figure out which height to return. If returnedHeight > maxHeight, - // then the i'th position did not fit completely. - return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1) - && (i > disallowPartialChildPosition) // We've past the min pos - && (prevHeightWithoutPartialChild > 0) // We have a prev height - && (returnedHeight != maxHeight) // i'th child did not fit completely - ? prevHeightWithoutPartialChild - : maxHeight; - } - - if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) { - prevHeightWithoutPartialChild = returnedHeight; - } - } - - // At this point, we went through the range of children, and they each - // completely fit, so return the returnedHeight - return returnedHeight; - } - private void measureScrapChild(View child, int position, int widthMeasureSpec) { - ListView.LayoutParams p = (ListView.LayoutParams) child.getLayoutParams(); - if (p == null) { - p = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT, 0); - child.setLayoutParams(p); - } - //XXX p.viewType = mAdapter.getItemViewType(position); - //XXX p.forceAdd = true; - - int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, - mDropDownList.getPaddingLeft() + mDropDownList.getPaddingRight(), p.width); - int lpHeight = p.height; - int childHeightSpec; - if (lpHeight > 0) { - childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); - } else { - childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - } - child.measure(childWidthSpec, childHeightSpec); - } - - private static class DropDownListView extends ListView { - /* - * WARNING: This is a workaround for a touch mode issue. - * - * Touch mode is propagated lazily to windows. This causes problems in - * the following scenario: - * - Type something in the AutoCompleteTextView and get some results - * - Move down with the d-pad to select an item in the list - * - Move up with the d-pad until the selection disappears - * - Type more text in the AutoCompleteTextView *using the soft keyboard* - * and get new results; you are now in touch mode - * - The selection comes back on the first item in the list, even though - * the list is supposed to be in touch mode - * - * Using the soft keyboard triggers the touch mode change but that change - * is propagated to our window only after the first list layout, therefore - * after the list attempts to resurrect the selection. - * - * The trick to work around this issue is to pretend the list is in touch - * mode when we know that the selection should not appear, that is when - * we know the user moved the selection away from the list. - * - * This boolean is set to true whenever we explicitly hide the list's - * selection and reset to false whenever we know the user moved the - * selection back to the list. - * - * When this boolean is true, isInTouchMode() returns true, otherwise it - * returns super.isInTouchMode(). - */ - private boolean mListSelectionHidden; - - private boolean mHijackFocus; - - public DropDownListView(Context context, boolean hijackFocus) { - super(context, null, /*com.android.internal.*/R.attr.dropDownListViewStyle); - mHijackFocus = hijackFocus; - // TODO: Add an API to control this - setCacheColorHint(0); // Transparent, since the background drawable could be anything. - } - - //XXX @Override - //View obtainView(int position, boolean[] isScrap) { - // View view = super.obtainView(position, isScrap); - - // if (view instanceof TextView) { - // ((TextView) view).setHorizontallyScrolling(true); - // } - - // return view; - //} - - @Override - public boolean isInTouchMode() { - // WARNING: Please read the comment where mListSelectionHidden is declared - return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode(); - } - - @Override - public boolean hasWindowFocus() { - return mHijackFocus || super.hasWindowFocus(); - } - - @Override - public boolean isFocused() { - return mHijackFocus || super.isFocused(); - } - - @Override - public boolean hasFocus() { - return mHijackFocus || super.hasFocus(); - } - } - - private class PopupDataSetObserver extends DataSetObserver { - @Override - public void onChanged() { - if (isShowing()) { - // Resize the popup to fit new content - show(); - } - } - - @Override - public void onInvalidated() { - dismiss(); - } - } - - private class ListSelectorHider implements Runnable { - public void run() { - clearListSelection(); - } - } - - private class ResizePopupRunnable implements Runnable { - public void run() { - if (mDropDownList != null && mDropDownList.getCount() > mDropDownList.getChildCount() && - mDropDownList.getChildCount() <= mListItemExpandMaximum) { - mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); - show(); - } - } - } - - private class PopupTouchInterceptor implements OnTouchListener { - public boolean onTouch(View v, MotionEvent event) { - final int action = event.getAction(); - final int x = (int) event.getX(); - final int y = (int) event.getY(); - - if (action == MotionEvent.ACTION_DOWN && - mPopup != null && mPopup.isShowing() && - (x >= 0 && x < mPopup.getWidth() && y >= 0 && y < mPopup.getHeight())) { - mHandler.postDelayed(mResizePopupRunnable, EXPAND_LIST_TIMEOUT); - } else if (action == MotionEvent.ACTION_UP) { - mHandler.removeCallbacks(mResizePopupRunnable); - } - return false; - } - } - - private class PopupScrollListener implements ListView.OnScrollListener { - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, - int totalItemCount) { - - } - - public void onScrollStateChanged(AbsListView view, int scrollState) { - if (scrollState == SCROLL_STATE_TOUCH_SCROLL && - !isInputMethodNotNeeded() && mPopup.getContentView() != null) { - mHandler.removeCallbacks(mResizePopupRunnable); - mResizePopupRunnable.run(); - } - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsProgressBar.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsProgressBar.java deleted file mode 100644 index 1c02d4ac..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsProgressBar.java +++ /dev/null @@ -1,1193 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.BitmapShader; -import android.graphics.Canvas; -import android.graphics.Rect; -import android.graphics.Shader; -import android.graphics.drawable.Animatable; -import android.graphics.drawable.AnimationDrawable; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.ClipDrawable; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.LayerDrawable; -import android.graphics.drawable.ShapeDrawable; -import android.graphics.drawable.shapes.RoundRectShape; -import android.graphics.drawable.shapes.Shape; -import android.os.Build; -import android.os.Parcel; -import android.os.Parcelable; -import android.os.SystemClock; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.View; -import android.view.ViewDebug; -import android.view.accessibility.AccessibilityEvent; -import android.view.accessibility.AccessibilityManager; -import android.view.animation.AlphaAnimation; -import android.view.animation.Animation; -import android.view.animation.AnimationUtils; -import android.view.animation.Interpolator; -import android.view.animation.LinearInterpolator; -import android.view.animation.Transformation; -import android.widget.RemoteViews.RemoteView; - - -/** - *

- * Visual indicator of progress in some operation. Displays a bar to the user - * representing how far the operation has progressed; the application can - * change the amount of progress (modifying the length of the bar) as it moves - * forward. There is also a secondary progress displayable on a progress bar - * which is useful for displaying intermediate progress, such as the buffer - * level during a streaming playback progress bar. - *

- * - *

- * A progress bar can also be made indeterminate. In indeterminate mode, the - * progress bar shows a cyclic animation without an indication of progress. This mode is used by - * applications when the length of the task is unknown. The indeterminate progress bar can be either - * a spinning wheel or a horizontal bar. - *

- * - *

The following code example shows how a progress bar can be used from - * a worker thread to update the user interface to notify the user of progress: - *

- * - *
- * public class MyActivity extends Activity {
- *     private static final int PROGRESS = 0x1;
- *
- *     private ProgressBar mProgress;
- *     private int mProgressStatus = 0;
- *
- *     private Handler mHandler = new Handler();
- *
- *     protected void onCreate(Bundle icicle) {
- *         super.onCreate(icicle);
- *
- *         setContentView(R.layout.progressbar_activity);
- *
- *         mProgress = (ProgressBar) findViewById(R.id.progress_bar);
- *
- *         // Start lengthy operation in a background thread
- *         new Thread(new Runnable() {
- *             public void run() {
- *                 while (mProgressStatus < 100) {
- *                     mProgressStatus = doWork();
- *
- *                     // Update the progress bar
- *                     mHandler.post(new Runnable() {
- *                         public void run() {
- *                             mProgress.setProgress(mProgressStatus);
- *                         }
- *                     });
- *                 }
- *             }
- *         }).start();
- *     }
- * }
- * - *

To add a progress bar to a layout file, you can use the {@code <ProgressBar>} element. - * By default, the progress bar is a spinning wheel (an indeterminate indicator). To change to a - * horizontal progress bar, apply the {@link android.R.style#Widget_ProgressBar_Horizontal - * Widget.ProgressBar.Horizontal} style, like so:

- * - *
- * <ProgressBar
- *     style="@android:style/Widget.ProgressBar.Horizontal"
- *     ... />
- * - *

If you will use the progress bar to show real progress, you must use the horizontal bar. You - * can then increment the progress with {@link #incrementProgressBy incrementProgressBy()} or - * {@link #setProgress setProgress()}. By default, the progress bar is full when it reaches 100. If - * necessary, you can adjust the maximum value (the value for a full bar) using the {@link - * android.R.styleable#ProgressBar_max android:max} attribute. Other attributes available are listed - * below.

- * - *

Another common style to apply to the progress bar is {@link - * android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}, which shows a smaller - * version of the spinning wheel—useful when waiting for content to load. - * For example, you can insert this kind of progress bar into your default layout for - * a view that will be populated by some content fetched from the Internet—the spinning wheel - * appears immediately and when your application receives the content, it replaces the progress bar - * with the loaded content. For example:

- * - *
- * <LinearLayout
- *     android:orientation="horizontal"
- *     ... >
- *     <ProgressBar
- *         android:layout_width="wrap_content"
- *         android:layout_height="wrap_content"
- *         style="@android:style/Widget.ProgressBar.Small"
- *         android:layout_marginRight="5dp" />
- *     <TextView
- *         android:layout_width="wrap_content"
- *         android:layout_height="wrap_content"
- *         android:text="@string/loading" />
- * </LinearLayout>
- * - *

Other progress bar styles provided by the system include:

- *
    - *
  • {@link android.R.style#Widget_ProgressBar_Horizontal Widget.ProgressBar.Horizontal}
  • - *
  • {@link android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}
  • - *
  • {@link android.R.style#Widget_ProgressBar_Large Widget.ProgressBar.Large}
  • - *
  • {@link android.R.style#Widget_ProgressBar_Inverse Widget.ProgressBar.Inverse}
  • - *
  • {@link android.R.style#Widget_ProgressBar_Small_Inverse - * Widget.ProgressBar.Small.Inverse}
  • - *
  • {@link android.R.style#Widget_ProgressBar_Large_Inverse - * Widget.ProgressBar.Large.Inverse}
  • - *
- *

The "inverse" styles provide an inverse color scheme for the spinner, which may be necessary - * if your application uses a light colored theme (a white background).

- * - *

XML attributes - *

- * See {@link android.R.styleable#ProgressBar ProgressBar Attributes}, - * {@link android.R.styleable#View View Attributes} - *

- * - * @attr ref android.R.styleable#ProgressBar_animationResolution - * @attr ref android.R.styleable#ProgressBar_indeterminate - * @attr ref android.R.styleable#ProgressBar_indeterminateBehavior - * @attr ref android.R.styleable#ProgressBar_indeterminateDrawable - * @attr ref android.R.styleable#ProgressBar_indeterminateDuration - * @attr ref android.R.styleable#ProgressBar_indeterminateOnly - * @attr ref android.R.styleable#ProgressBar_interpolator - * @attr ref android.R.styleable#ProgressBar_max - * @attr ref android.R.styleable#ProgressBar_maxHeight - * @attr ref android.R.styleable#ProgressBar_maxWidth - * @attr ref android.R.styleable#ProgressBar_minHeight - * @attr ref android.R.styleable#ProgressBar_minWidth - * @attr ref android.R.styleable#ProgressBar_progress - * @attr ref android.R.styleable#ProgressBar_progressDrawable - * @attr ref android.R.styleable#ProgressBar_secondaryProgress - */ -@RemoteView -public class IcsProgressBar extends View { - private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; - private static final int MAX_LEVEL = 10000; - private static final int ANIMATION_RESOLUTION = 200; - private static final int TIMEOUT_SEND_ACCESSIBILITY_EVENT = 200; - - private static final int[] ProgressBar = new int[] { - android.R.attr.maxWidth, - android.R.attr.maxHeight, - android.R.attr.max, - android.R.attr.progress, - android.R.attr.secondaryProgress, - android.R.attr.indeterminate, - android.R.attr.indeterminateOnly, - android.R.attr.indeterminateDrawable, - android.R.attr.progressDrawable, - android.R.attr.indeterminateDuration, - android.R.attr.indeterminateBehavior, - android.R.attr.minWidth, - android.R.attr.minHeight, - android.R.attr.interpolator, - android.R.attr.animationResolution, - }; - private static final int ProgressBar_maxWidth = 0; - private static final int ProgressBar_maxHeight = 1; - private static final int ProgressBar_max = 2; - private static final int ProgressBar_progress = 3; - private static final int ProgressBar_secondaryProgress = 4; - private static final int ProgressBar_indeterminate = 5; - private static final int ProgressBar_indeterminateOnly = 6; - private static final int ProgressBar_indeterminateDrawable = 7; - private static final int ProgressBar_progressDrawable = 8; - private static final int ProgressBar_indeterminateDuration = 9; - private static final int ProgressBar_indeterminateBehavior = 10; - private static final int ProgressBar_minWidth = 11; - private static final int ProgressBar_minHeight = 12; - private static final int ProgressBar_interpolator = 13; - private static final int ProgressBar_animationResolution = 14; - - int mMinWidth; - int mMaxWidth; - int mMinHeight; - int mMaxHeight; - - private int mProgress; - private int mSecondaryProgress; - private int mMax; - - private int mBehavior; - private int mDuration; - private boolean mIndeterminate; - private boolean mOnlyIndeterminate; - private Transformation mTransformation; - private AlphaAnimation mAnimation; - private Drawable mIndeterminateDrawable; - private int mIndeterminateRealLeft; - private int mIndeterminateRealTop; - private Drawable mProgressDrawable; - private Drawable mCurrentDrawable; - Bitmap mSampleTile; - private boolean mNoInvalidate; - private Interpolator mInterpolator; - private RefreshProgressRunnable mRefreshProgressRunnable; - private long mUiThreadId; - private boolean mShouldStartAnimationDrawable; - private long mLastDrawTime; - - private boolean mInDrawing; - - private int mAnimationResolution; - - private AccessibilityManager mAccessibilityManager; - private AccessibilityEventSender mAccessibilityEventSender; - - /** - * Create a new progress bar with range 0...100 and initial progress of 0. - * @param context the application environment - */ - public IcsProgressBar(Context context) { - this(context, null); - } - - public IcsProgressBar(Context context, AttributeSet attrs) { - this(context, attrs, android.R.attr.progressBarStyle); - } - - public IcsProgressBar(Context context, AttributeSet attrs, int defStyle) { - this(context, attrs, defStyle, 0); - } - - /** - * @hide - */ - public IcsProgressBar(Context context, AttributeSet attrs, int defStyle, int styleRes) { - super(context, attrs, defStyle); - mUiThreadId = Thread.currentThread().getId(); - initProgressBar(); - - TypedArray a = - context.obtainStyledAttributes(attrs, /*R.styleable.*/ProgressBar, defStyle, styleRes); - - mNoInvalidate = true; - - Drawable drawable = a.getDrawable(/*R.styleable.*/ProgressBar_progressDrawable); - if (drawable != null) { - drawable = tileify(drawable, false); - // Calling this method can set mMaxHeight, make sure the corresponding - // XML attribute for mMaxHeight is read after calling this method - setProgressDrawable(drawable); - } - - - mDuration = a.getInt(/*R.styleable.*/ProgressBar_indeterminateDuration, mDuration); - - mMinWidth = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_minWidth, mMinWidth); - mMaxWidth = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_maxWidth, mMaxWidth); - mMinHeight = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_minHeight, mMinHeight); - mMaxHeight = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_maxHeight, mMaxHeight); - - mBehavior = a.getInt(/*R.styleable.*/ProgressBar_indeterminateBehavior, mBehavior); - - final int resID = a.getResourceId( - /*com.android.internal.R.styleable.*/ProgressBar_interpolator, - android.R.anim.linear_interpolator); // default to linear interpolator - if (resID > 0) { - setInterpolator(context, resID); - } - - setMax(a.getInt(/*R.styleable.*/ProgressBar_max, mMax)); - - setProgress(a.getInt(/*R.styleable.*/ProgressBar_progress, mProgress)); - - setSecondaryProgress( - a.getInt(/*R.styleable.*/ProgressBar_secondaryProgress, mSecondaryProgress)); - - drawable = a.getDrawable(/*R.styleable.*/ProgressBar_indeterminateDrawable); - if (drawable != null) { - drawable = tileifyIndeterminate(drawable); - setIndeterminateDrawable(drawable); - } - - mOnlyIndeterminate = a.getBoolean( - /*R.styleable.*/ProgressBar_indeterminateOnly, mOnlyIndeterminate); - - mNoInvalidate = false; - - setIndeterminate(mOnlyIndeterminate || a.getBoolean( - /*R.styleable.*/ProgressBar_indeterminate, mIndeterminate)); - - mAnimationResolution = a.getInteger(/*R.styleable.*/ProgressBar_animationResolution, - ANIMATION_RESOLUTION); - - a.recycle(); - - mAccessibilityManager = (AccessibilityManager)context.getSystemService(Context.ACCESSIBILITY_SERVICE); - } - - /** - * Converts a drawable to a tiled version of itself. It will recursively - * traverse layer and state list drawables. - */ - private Drawable tileify(Drawable drawable, boolean clip) { - - if (drawable instanceof LayerDrawable) { - LayerDrawable background = (LayerDrawable) drawable; - final int N = background.getNumberOfLayers(); - Drawable[] outDrawables = new Drawable[N]; - - for (int i = 0; i < N; i++) { - int id = background.getId(i); - outDrawables[i] = tileify(background.getDrawable(i), - (id == android.R.id.progress || id == android.R.id.secondaryProgress)); - } - - LayerDrawable newBg = new LayerDrawable(outDrawables); - - for (int i = 0; i < N; i++) { - newBg.setId(i, background.getId(i)); - } - - return newBg; - - }/* else if (drawable instanceof StateListDrawable) { - StateListDrawable in = (StateListDrawable) drawable; - StateListDrawable out = new StateListDrawable(); - int numStates = in.getStateCount(); - for (int i = 0; i < numStates; i++) { - out.addState(in.getStateSet(i), tileify(in.getStateDrawable(i), clip)); - } - return out; - - }*/ else if (drawable instanceof BitmapDrawable) { - final Bitmap tileBitmap = ((BitmapDrawable) drawable).getBitmap(); - if (mSampleTile == null) { - mSampleTile = tileBitmap; - } - - final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape()); - - final BitmapShader bitmapShader = new BitmapShader(tileBitmap, - Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); - shapeDrawable.getPaint().setShader(bitmapShader); - - return (clip) ? new ClipDrawable(shapeDrawable, Gravity.LEFT, - ClipDrawable.HORIZONTAL) : shapeDrawable; - } - - return drawable; - } - - Shape getDrawableShape() { - final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }; - return new RoundRectShape(roundedCorners, null, null); - } - - /** - * Convert a AnimationDrawable for use as a barberpole animation. - * Each frame of the animation is wrapped in a ClipDrawable and - * given a tiling BitmapShader. - */ - private Drawable tileifyIndeterminate(Drawable drawable) { - if (drawable instanceof AnimationDrawable) { - AnimationDrawable background = (AnimationDrawable) drawable; - final int N = background.getNumberOfFrames(); - AnimationDrawable newBg = new AnimationDrawable(); - newBg.setOneShot(background.isOneShot()); - - for (int i = 0; i < N; i++) { - Drawable frame = tileify(background.getFrame(i), true); - frame.setLevel(10000); - newBg.addFrame(frame, background.getDuration(i)); - } - newBg.setLevel(10000); - drawable = newBg; - } - return drawable; - } - - /** - *

- * Initialize the progress bar's default values: - *

- *
    - *
  • progress = 0
  • - *
  • max = 100
  • - *
  • animation duration = 4000 ms
  • - *
  • indeterminate = false
  • - *
  • behavior = repeat
  • - *
- */ - private void initProgressBar() { - mMax = 100; - mProgress = 0; - mSecondaryProgress = 0; - mIndeterminate = false; - mOnlyIndeterminate = false; - mDuration = 4000; - mBehavior = AlphaAnimation.RESTART; - mMinWidth = 24; - mMaxWidth = 48; - mMinHeight = 24; - mMaxHeight = 48; - } - - /** - *

Indicate whether this progress bar is in indeterminate mode.

- * - * @return true if the progress bar is in indeterminate mode - */ - @ViewDebug.ExportedProperty(category = "progress") - public synchronized boolean isIndeterminate() { - return mIndeterminate; - } - - /** - *

Change the indeterminate mode for this progress bar. In indeterminate - * mode, the progress is ignored and the progress bar shows an infinite - * animation instead.

- * - * If this progress bar's style only supports indeterminate mode (such as the circular - * progress bars), then this will be ignored. - * - * @param indeterminate true to enable the indeterminate mode - */ - public synchronized void setIndeterminate(boolean indeterminate) { - if ((!mOnlyIndeterminate || !mIndeterminate) && indeterminate != mIndeterminate) { - mIndeterminate = indeterminate; - - if (indeterminate) { - // swap between indeterminate and regular backgrounds - mCurrentDrawable = mIndeterminateDrawable; - startAnimation(); - } else { - mCurrentDrawable = mProgressDrawable; - stopAnimation(); - } - } - } - - /** - *

Get the drawable used to draw the progress bar in - * indeterminate mode.

- * - * @return a {@link android.graphics.drawable.Drawable} instance - * - * @see #setIndeterminateDrawable(android.graphics.drawable.Drawable) - * @see #setIndeterminate(boolean) - */ - public Drawable getIndeterminateDrawable() { - return mIndeterminateDrawable; - } - - /** - *

Define the drawable used to draw the progress bar in - * indeterminate mode.

- * - * @param d the new drawable - * - * @see #getIndeterminateDrawable() - * @see #setIndeterminate(boolean) - */ - public void setIndeterminateDrawable(Drawable d) { - if (d != null) { - d.setCallback(this); - } - mIndeterminateDrawable = d; - if (mIndeterminate) { - mCurrentDrawable = d; - postInvalidate(); - } - } - - /** - *

Get the drawable used to draw the progress bar in - * progress mode.

- * - * @return a {@link android.graphics.drawable.Drawable} instance - * - * @see #setProgressDrawable(android.graphics.drawable.Drawable) - * @see #setIndeterminate(boolean) - */ - public Drawable getProgressDrawable() { - return mProgressDrawable; - } - - /** - *

Define the drawable used to draw the progress bar in - * progress mode.

- * - * @param d the new drawable - * - * @see #getProgressDrawable() - * @see #setIndeterminate(boolean) - */ - public void setProgressDrawable(Drawable d) { - boolean needUpdate; - if (mProgressDrawable != null && d != mProgressDrawable) { - mProgressDrawable.setCallback(null); - needUpdate = true; - } else { - needUpdate = false; - } - - if (d != null) { - d.setCallback(this); - - // Make sure the ProgressBar is always tall enough - int drawableHeight = d.getMinimumHeight(); - if (mMaxHeight < drawableHeight) { - mMaxHeight = drawableHeight; - requestLayout(); - } - } - mProgressDrawable = d; - if (!mIndeterminate) { - mCurrentDrawable = d; - postInvalidate(); - } - - if (needUpdate) { - updateDrawableBounds(getWidth(), getHeight()); - updateDrawableState(); - doRefreshProgress(android.R.id.progress, mProgress, false, false); - doRefreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false, false); - } - } - - /** - * @return The drawable currently used to draw the progress bar - */ - Drawable getCurrentDrawable() { - return mCurrentDrawable; - } - - @Override - protected boolean verifyDrawable(Drawable who) { - return who == mProgressDrawable || who == mIndeterminateDrawable - || super.verifyDrawable(who); - } - - @Override - public void jumpDrawablesToCurrentState() { - super.jumpDrawablesToCurrentState(); - if (mProgressDrawable != null) mProgressDrawable.jumpToCurrentState(); - if (mIndeterminateDrawable != null) mIndeterminateDrawable.jumpToCurrentState(); - } - - @Override - public void postInvalidate() { - if (!mNoInvalidate) { - super.postInvalidate(); - } - } - - private class RefreshProgressRunnable implements Runnable { - - private int mId; - private int mProgress; - private boolean mFromUser; - - RefreshProgressRunnable(int id, int progress, boolean fromUser) { - mId = id; - mProgress = progress; - mFromUser = fromUser; - } - - public void run() { - doRefreshProgress(mId, mProgress, mFromUser, true); - // Put ourselves back in the cache when we are done - mRefreshProgressRunnable = this; - } - - public void setup(int id, int progress, boolean fromUser) { - mId = id; - mProgress = progress; - mFromUser = fromUser; - } - - } - - private synchronized void doRefreshProgress(int id, int progress, boolean fromUser, - boolean callBackToApp) { - float scale = mMax > 0 ? (float) progress / (float) mMax : 0; - final Drawable d = mCurrentDrawable; - if (d != null) { - Drawable progressDrawable = null; - - if (d instanceof LayerDrawable) { - progressDrawable = ((LayerDrawable) d).findDrawableByLayerId(id); - } - - final int level = (int) (scale * MAX_LEVEL); - (progressDrawable != null ? progressDrawable : d).setLevel(level); - } else { - invalidate(); - } - - if (callBackToApp && id == android.R.id.progress) { - onProgressRefresh(scale, fromUser); - } - } - - void onProgressRefresh(float scale, boolean fromUser) { - if (mAccessibilityManager.isEnabled()) { - scheduleAccessibilityEventSender(); - } - } - - private synchronized void refreshProgress(int id, int progress, boolean fromUser) { - if (mUiThreadId == Thread.currentThread().getId()) { - doRefreshProgress(id, progress, fromUser, true); - } else { - RefreshProgressRunnable r; - if (mRefreshProgressRunnable != null) { - // Use cached RefreshProgressRunnable if available - r = mRefreshProgressRunnable; - // Uncache it - mRefreshProgressRunnable = null; - r.setup(id, progress, fromUser); - } else { - // Make a new one - r = new RefreshProgressRunnable(id, progress, fromUser); - } - post(r); - } - } - - /** - *

Set the current progress to the specified value. Does not do anything - * if the progress bar is in indeterminate mode.

- * - * @param progress the new progress, between 0 and {@link #getMax()} - * - * @see #setIndeterminate(boolean) - * @see #isIndeterminate() - * @see #getProgress() - * @see #incrementProgressBy(int) - */ - public synchronized void setProgress(int progress) { - setProgress(progress, false); - } - - synchronized void setProgress(int progress, boolean fromUser) { - if (mIndeterminate) { - return; - } - - if (progress < 0) { - progress = 0; - } - - if (progress > mMax) { - progress = mMax; - } - - if (progress != mProgress) { - mProgress = progress; - refreshProgress(android.R.id.progress, mProgress, fromUser); - } - } - - /** - *

- * Set the current secondary progress to the specified value. Does not do - * anything if the progress bar is in indeterminate mode. - *

- * - * @param secondaryProgress the new secondary progress, between 0 and {@link #getMax()} - * @see #setIndeterminate(boolean) - * @see #isIndeterminate() - * @see #getSecondaryProgress() - * @see #incrementSecondaryProgressBy(int) - */ - public synchronized void setSecondaryProgress(int secondaryProgress) { - if (mIndeterminate) { - return; - } - - if (secondaryProgress < 0) { - secondaryProgress = 0; - } - - if (secondaryProgress > mMax) { - secondaryProgress = mMax; - } - - if (secondaryProgress != mSecondaryProgress) { - mSecondaryProgress = secondaryProgress; - refreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false); - } - } - - /** - *

Get the progress bar's current level of progress. Return 0 when the - * progress bar is in indeterminate mode.

- * - * @return the current progress, between 0 and {@link #getMax()} - * - * @see #setIndeterminate(boolean) - * @see #isIndeterminate() - * @see #setProgress(int) - * @see #setMax(int) - * @see #getMax() - */ - @ViewDebug.ExportedProperty(category = "progress") - public synchronized int getProgress() { - return mIndeterminate ? 0 : mProgress; - } - - /** - *

Get the progress bar's current level of secondary progress. Return 0 when the - * progress bar is in indeterminate mode.

- * - * @return the current secondary progress, between 0 and {@link #getMax()} - * - * @see #setIndeterminate(boolean) - * @see #isIndeterminate() - * @see #setSecondaryProgress(int) - * @see #setMax(int) - * @see #getMax() - */ - @ViewDebug.ExportedProperty(category = "progress") - public synchronized int getSecondaryProgress() { - return mIndeterminate ? 0 : mSecondaryProgress; - } - - /** - *

Return the upper limit of this progress bar's range.

- * - * @return a positive integer - * - * @see #setMax(int) - * @see #getProgress() - * @see #getSecondaryProgress() - */ - @ViewDebug.ExportedProperty(category = "progress") - public synchronized int getMax() { - return mMax; - } - - /** - *

Set the range of the progress bar to 0...max.

- * - * @param max the upper range of this progress bar - * - * @see #getMax() - * @see #setProgress(int) - * @see #setSecondaryProgress(int) - */ - public synchronized void setMax(int max) { - if (max < 0) { - max = 0; - } - if (max != mMax) { - mMax = max; - postInvalidate(); - - if (mProgress > max) { - mProgress = max; - } - refreshProgress(android.R.id.progress, mProgress, false); - } - } - - /** - *

Increase the progress bar's progress by the specified amount.

- * - * @param diff the amount by which the progress must be increased - * - * @see #setProgress(int) - */ - public synchronized final void incrementProgressBy(int diff) { - setProgress(mProgress + diff); - } - - /** - *

Increase the progress bar's secondary progress by the specified amount.

- * - * @param diff the amount by which the secondary progress must be increased - * - * @see #setSecondaryProgress(int) - */ - public synchronized final void incrementSecondaryProgressBy(int diff) { - setSecondaryProgress(mSecondaryProgress + diff); - } - - /** - *

Start the indeterminate progress animation.

- */ - void startAnimation() { - if (getVisibility() != VISIBLE) { - return; - } - - if (mIndeterminateDrawable instanceof Animatable) { - mShouldStartAnimationDrawable = true; - mAnimation = null; - } else { - if (mInterpolator == null) { - mInterpolator = new LinearInterpolator(); - } - - mTransformation = new Transformation(); - mAnimation = new AlphaAnimation(0.0f, 1.0f); - mAnimation.setRepeatMode(mBehavior); - mAnimation.setRepeatCount(Animation.INFINITE); - mAnimation.setDuration(mDuration); - mAnimation.setInterpolator(mInterpolator); - mAnimation.setStartTime(Animation.START_ON_FIRST_FRAME); - } - postInvalidate(); - } - - /** - *

Stop the indeterminate progress animation.

- */ - void stopAnimation() { - mAnimation = null; - mTransformation = null; - if (mIndeterminateDrawable instanceof Animatable) { - ((Animatable) mIndeterminateDrawable).stop(); - mShouldStartAnimationDrawable = false; - } - postInvalidate(); - } - - /** - * Sets the acceleration curve for the indeterminate animation. - * The interpolator is loaded as a resource from the specified context. - * - * @param context The application environment - * @param resID The resource identifier of the interpolator to load - */ - public void setInterpolator(Context context, int resID) { - setInterpolator(AnimationUtils.loadInterpolator(context, resID)); - } - - /** - * Sets the acceleration curve for the indeterminate animation. - * Defaults to a linear interpolation. - * - * @param interpolator The interpolator which defines the acceleration curve - */ - public void setInterpolator(Interpolator interpolator) { - mInterpolator = interpolator; - } - - /** - * Gets the acceleration curve type for the indeterminate animation. - * - * @return the {@link Interpolator} associated to this animation - */ - public Interpolator getInterpolator() { - return mInterpolator; - } - - @Override - public void setVisibility(int v) { - if (getVisibility() != v) { - super.setVisibility(v); - - if (mIndeterminate) { - // let's be nice with the UI thread - if (v == GONE || v == INVISIBLE) { - stopAnimation(); - } else { - startAnimation(); - } - } - } - } - - @Override - protected void onVisibilityChanged(View changedView, int visibility) { - super.onVisibilityChanged(changedView, visibility); - - if (mIndeterminate) { - // let's be nice with the UI thread - if (visibility == GONE || visibility == INVISIBLE) { - stopAnimation(); - } else { - startAnimation(); - } - } - } - - @Override - public void invalidateDrawable(Drawable dr) { - if (!mInDrawing) { - if (verifyDrawable(dr)) { - final Rect dirty = dr.getBounds(); - final int scrollX = getScrollX() + getPaddingLeft(); - final int scrollY = getScrollY() + getPaddingTop(); - - invalidate(dirty.left + scrollX, dirty.top + scrollY, - dirty.right + scrollX, dirty.bottom + scrollY); - } else { - super.invalidateDrawable(dr); - } - } - } - - /** - * @hide - * - @Override - public int getResolvedLayoutDirection(Drawable who) { - return (who == mProgressDrawable || who == mIndeterminateDrawable) ? - getResolvedLayoutDirection() : super.getResolvedLayoutDirection(who); - } - */ - - @Override - protected void onSizeChanged(int w, int h, int oldw, int oldh) { - updateDrawableBounds(w, h); - } - - private void updateDrawableBounds(int w, int h) { - // onDraw will translate the canvas so we draw starting at 0,0 - int right = w - getPaddingRight() - getPaddingLeft(); - int bottom = h - getPaddingBottom() - getPaddingTop(); - int top = 0; - int left = 0; - - if (mIndeterminateDrawable != null) { - // Aspect ratio logic does not apply to AnimationDrawables - if (mOnlyIndeterminate && !(mIndeterminateDrawable instanceof AnimationDrawable)) { - // Maintain aspect ratio. Certain kinds of animated drawables - // get very confused otherwise. - final int intrinsicWidth = mIndeterminateDrawable.getIntrinsicWidth(); - final int intrinsicHeight = mIndeterminateDrawable.getIntrinsicHeight(); - final float intrinsicAspect = (float) intrinsicWidth / intrinsicHeight; - final float boundAspect = (float) w / h; - if (intrinsicAspect != boundAspect) { - if (boundAspect > intrinsicAspect) { - // New width is larger. Make it smaller to match height. - final int width = (int) (h * intrinsicAspect); - left = (w - width) / 2; - right = left + width; - } else { - // New height is larger. Make it smaller to match width. - final int height = (int) (w * (1 / intrinsicAspect)); - top = (h - height) / 2; - bottom = top + height; - } - } - } - mIndeterminateDrawable.setBounds(0, 0, right - left, bottom - top); - mIndeterminateRealLeft = left; - mIndeterminateRealTop = top; - } - - if (mProgressDrawable != null) { - mProgressDrawable.setBounds(0, 0, right, bottom); - } - } - - @Override - protected synchronized void onDraw(Canvas canvas) { - super.onDraw(canvas); - - Drawable d = mCurrentDrawable; - if (d != null) { - // Translate canvas so a indeterminate circular progress bar with padding - // rotates properly in its animation - canvas.save(); - canvas.translate(getPaddingLeft() + mIndeterminateRealLeft, getPaddingTop() + mIndeterminateRealTop); - long time = getDrawingTime(); - if (mAnimation != null) { - mAnimation.getTransformation(time, mTransformation); - float scale = mTransformation.getAlpha(); - try { - mInDrawing = true; - d.setLevel((int) (scale * MAX_LEVEL)); - } finally { - mInDrawing = false; - } - if (SystemClock.uptimeMillis() - mLastDrawTime >= mAnimationResolution) { - mLastDrawTime = SystemClock.uptimeMillis(); - postInvalidateDelayed(mAnimationResolution); - } - } - d.draw(canvas); - canvas.restore(); - if (mShouldStartAnimationDrawable && d instanceof Animatable) { - ((Animatable) d).start(); - mShouldStartAnimationDrawable = false; - } - } - } - - @Override - protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - Drawable d = mCurrentDrawable; - - int dw = 0; - int dh = 0; - if (d != null) { - dw = Math.max(mMinWidth, Math.min(mMaxWidth, d.getIntrinsicWidth())); - dh = Math.max(mMinHeight, Math.min(mMaxHeight, d.getIntrinsicHeight())); - } - updateDrawableState(); - dw += getPaddingLeft() + getPaddingRight(); - dh += getPaddingTop() + getPaddingBottom(); - - if (IS_HONEYCOMB) { - setMeasuredDimension(View.resolveSizeAndState(dw, widthMeasureSpec, 0), - View.resolveSizeAndState(dh, heightMeasureSpec, 0)); - } else { - setMeasuredDimension(View.resolveSize(dw, widthMeasureSpec), - View.resolveSize(dh, heightMeasureSpec)); - } - } - - @Override - protected void drawableStateChanged() { - super.drawableStateChanged(); - updateDrawableState(); - } - - private void updateDrawableState() { - int[] state = getDrawableState(); - - if (mProgressDrawable != null && mProgressDrawable.isStateful()) { - mProgressDrawable.setState(state); - } - - if (mIndeterminateDrawable != null && mIndeterminateDrawable.isStateful()) { - mIndeterminateDrawable.setState(state); - } - } - - static class SavedState extends BaseSavedState { - int progress; - int secondaryProgress; - - /** - * Constructor called from {@link IcsProgressBar#onSaveInstanceState()} - */ - SavedState(Parcelable superState) { - super(superState); - } - - /** - * Constructor called from {@link #CREATOR} - */ - private SavedState(Parcel in) { - super(in); - progress = in.readInt(); - secondaryProgress = in.readInt(); - } - - @Override - public void writeToParcel(Parcel out, int flags) { - super.writeToParcel(out, flags); - out.writeInt(progress); - out.writeInt(secondaryProgress); - } - - public static final Parcelable.Creator CREATOR - = new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; - } - - @Override - public Parcelable onSaveInstanceState() { - // Force our ancestor class to save its state - Parcelable superState = super.onSaveInstanceState(); - SavedState ss = new SavedState(superState); - - ss.progress = mProgress; - ss.secondaryProgress = mSecondaryProgress; - - return ss; - } - - @Override - public void onRestoreInstanceState(Parcelable state) { - SavedState ss = (SavedState) state; - super.onRestoreInstanceState(ss.getSuperState()); - - setProgress(ss.progress); - setSecondaryProgress(ss.secondaryProgress); - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - if (mIndeterminate) { - startAnimation(); - } - } - - @Override - protected void onDetachedFromWindow() { - if (mIndeterminate) { - stopAnimation(); - } - if(mRefreshProgressRunnable != null) { - removeCallbacks(mRefreshProgressRunnable); - } - if (mAccessibilityEventSender != null) { - removeCallbacks(mAccessibilityEventSender); - } - // This should come after stopAnimation(), otherwise an invalidate message remains in the - // queue, which can prevent the entire view hierarchy from being GC'ed during a rotation - super.onDetachedFromWindow(); - } - - @Override - public void onInitializeAccessibilityEvent(AccessibilityEvent event) { - super.onInitializeAccessibilityEvent(event); - event.setItemCount(mMax); - event.setCurrentItemIndex(mProgress); - } - - /** - * Schedule a command for sending an accessibility event. - *
- * Note: A command is used to ensure that accessibility events - * are sent at most one in a given time frame to save - * system resources while the progress changes quickly. - */ - private void scheduleAccessibilityEventSender() { - if (mAccessibilityEventSender == null) { - mAccessibilityEventSender = new AccessibilityEventSender(); - } else { - removeCallbacks(mAccessibilityEventSender); - } - postDelayed(mAccessibilityEventSender, TIMEOUT_SEND_ACCESSIBILITY_EVENT); - } - - /** - * Command for sending an accessibility event. - */ - private class AccessibilityEventSender implements Runnable { - public void run() { - sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsSpinner.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsSpinner.java deleted file mode 100644 index 038d1e03..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsSpinner.java +++ /dev/null @@ -1,703 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.internal.widget; - -import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; -import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; -import com.actionbarsherlock.R; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.content.res.TypedArray; -import android.database.DataSetObserver; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.ListAdapter; -import android.widget.ListView; -import android.widget.PopupWindow; -import android.widget.SpinnerAdapter; - - -/** - * A view that displays one child at a time and lets the user pick among them. - * The items in the Spinner come from the {@link Adapter} associated with - * this view. - * - *

See the Spinner - * tutorial.

- * - * @attr ref android.R.styleable#Spinner_prompt - */ -public class IcsSpinner extends IcsAbsSpinner implements OnClickListener { - //private static final String TAG = "Spinner"; - - // Only measure this many items to get a decent max width. - private static final int MAX_ITEMS_MEASURED = 15; - - /** - * Use a dialog window for selecting spinner options. - */ - //public static final int MODE_DIALOG = 0; - - /** - * Use a dropdown anchored to the Spinner for selecting spinner options. - */ - public static final int MODE_DROPDOWN = 1; - - /** - * Use the theme-supplied value to select the dropdown mode. - */ - //private static final int MODE_THEME = -1; - - private SpinnerPopup mPopup; - private DropDownAdapter mTempAdapter; - int mDropDownWidth; - - private int mGravity; - private boolean mDisableChildrenWhenDisabled; - - private Rect mTempRect = new Rect(); - - public IcsSpinner(Context context, AttributeSet attrs) { - this(context, attrs, R.attr.actionDropDownStyle); - } - - /** - * Construct a new spinner with the given context's theme, the supplied attribute set, - * and default style. - * - * @param context The Context the view is running in, through which it can - * access the current theme, resources, etc. - * @param attrs The attributes of the XML tag that is inflating the view. - * @param defStyle The default style to apply to this view. If 0, no style - * will be applied (beyond what is included in the theme). This may - * either be an attribute resource, whose value will be retrieved - * from the current theme, or an explicit style resource. - */ - public IcsSpinner(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - - TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SherlockSpinner, defStyle, 0); - - - DropdownPopup popup = new DropdownPopup(context, attrs, defStyle); - - mDropDownWidth = a.getLayoutDimension( - R.styleable.SherlockSpinner_android_dropDownWidth, - ViewGroup.LayoutParams.WRAP_CONTENT); - popup.setBackgroundDrawable(a.getDrawable( - R.styleable.SherlockSpinner_android_popupBackground)); - final int verticalOffset = a.getDimensionPixelOffset( - R.styleable.SherlockSpinner_android_dropDownVerticalOffset, 0); - if (verticalOffset != 0) { - popup.setVerticalOffset(verticalOffset); - } - - final int horizontalOffset = a.getDimensionPixelOffset( - R.styleable.SherlockSpinner_android_dropDownHorizontalOffset, 0); - if (horizontalOffset != 0) { - popup.setHorizontalOffset(horizontalOffset); - } - - mPopup = popup; - - mGravity = a.getInt(R.styleable.SherlockSpinner_android_gravity, Gravity.CENTER); - - mPopup.setPromptText(a.getString(R.styleable.SherlockSpinner_android_prompt)); - - mDisableChildrenWhenDisabled = true; - - a.recycle(); - - // Base constructor can call setAdapter before we initialize mPopup. - // Finish setting things up if this happened. - if (mTempAdapter != null) { - mPopup.setAdapter(mTempAdapter); - mTempAdapter = null; - } - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - if (mDisableChildrenWhenDisabled) { - final int count = getChildCount(); - for (int i = 0; i < count; i++) { - getChildAt(i).setEnabled(enabled); - } - } - } - - /** - * Describes how the selected item view is positioned. Currently only the horizontal component - * is used. The default is determined by the current theme. - * - * @param gravity See {@link android.view.Gravity} - * - * @attr ref android.R.styleable#Spinner_gravity - */ - public void setGravity(int gravity) { - if (mGravity != gravity) { - if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { - gravity |= Gravity.LEFT; - } - mGravity = gravity; - requestLayout(); - } - } - - @Override - public void setAdapter(SpinnerAdapter adapter) { - super.setAdapter(adapter); - - if (mPopup != null) { - mPopup.setAdapter(new DropDownAdapter(adapter)); - } else { - mTempAdapter = new DropDownAdapter(adapter); - } - } - - @Override - public int getBaseline() { - View child = null; - - if (getChildCount() > 0) { - child = getChildAt(0); - } else if (mAdapter != null && mAdapter.getCount() > 0) { - child = makeAndAddView(0); - mRecycler.put(0, child); - removeAllViewsInLayout(); - } - - if (child != null) { - final int childBaseline = child.getBaseline(); - return childBaseline >= 0 ? child.getTop() + childBaseline : -1; - } else { - return -1; - } - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - - if (mPopup != null && mPopup.isShowing()) { - mPopup.dismiss(); - } - } - - /** - *

A spinner does not support item click events. Calling this method - * will raise an exception.

- * - * @param l this listener will be ignored - */ - @Override - public void setOnItemClickListener(OnItemClickListener l) { - throw new RuntimeException("setOnItemClickListener cannot be used with a spinner."); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - if (mPopup != null && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) { - final int measuredWidth = getMeasuredWidth(); - setMeasuredDimension(Math.min(Math.max(measuredWidth, - measureContentWidth(getAdapter(), getBackground())), - MeasureSpec.getSize(widthMeasureSpec)), - getMeasuredHeight()); - } - } - - /** - * @see android.view.View#onLayout(boolean,int,int,int,int) - * - * Creates and positions all views - * - */ - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - super.onLayout(changed, l, t, r, b); - mInLayout = true; - layout(0, false); - mInLayout = false; - } - - /** - * Creates and positions all views for this Spinner. - * - * @param delta Change in the selected position. +1 moves selection is moving to the right, - * so views are scrolling to the left. -1 means selection is moving to the left. - */ - @Override - void layout(int delta, boolean animate) { - int childrenLeft = mSpinnerPadding.left; - int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left - mSpinnerPadding.right; - - if (mDataChanged) { - handleDataChanged(); - } - - // Handle the empty set by removing all views - if (mItemCount == 0) { - resetList(); - return; - } - - if (mNextSelectedPosition >= 0) { - setSelectedPositionInt(mNextSelectedPosition); - } - - recycleAllViews(); - - // Clear out old views - removeAllViewsInLayout(); - - // Make selected view and position it - mFirstPosition = mSelectedPosition; - View sel = makeAndAddView(mSelectedPosition); - int width = sel.getMeasuredWidth(); - int selectedOffset = childrenLeft; - switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { - case Gravity.CENTER_HORIZONTAL: - selectedOffset = childrenLeft + (childrenWidth / 2) - (width / 2); - break; - case Gravity.RIGHT: - selectedOffset = childrenLeft + childrenWidth - width; - break; - } - sel.offsetLeftAndRight(selectedOffset); - - // Flush any cached views that did not get reused above - mRecycler.clear(); - - invalidate(); - - checkSelectionChanged(); - - mDataChanged = false; - mNeedSync = false; - setNextSelectedPositionInt(mSelectedPosition); - } - - /** - * Obtain a view, either by pulling an existing view from the recycler or - * by getting a new one from the adapter. If we are animating, make sure - * there is enough information in the view's layout parameters to animate - * from the old to new positions. - * - * @param position Position in the spinner for the view to obtain - * @return A view that has been added to the spinner - */ - private View makeAndAddView(int position) { - - View child; - - if (!mDataChanged) { - child = mRecycler.get(position); - if (child != null) { - // Position the view - setUpChild(child); - - return child; - } - } - - // Nothing found in the recycler -- ask the adapter for a view - child = mAdapter.getView(position, null, this); - - // Position the view - setUpChild(child); - - return child; - } - - /** - * Helper for makeAndAddView to set the position of a view - * and fill out its layout paramters. - * - * @param child The view to position - */ - private void setUpChild(View child) { - - // Respect layout params that are already in the view. Otherwise - // make some up... - ViewGroup.LayoutParams lp = child.getLayoutParams(); - if (lp == null) { - lp = generateDefaultLayoutParams(); - } - - addViewInLayout(child, 0, lp); - - child.setSelected(hasFocus()); - if (mDisableChildrenWhenDisabled) { - child.setEnabled(isEnabled()); - } - - // Get measure specs - int childHeightSpec = ViewGroup.getChildMeasureSpec(mHeightMeasureSpec, - mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height); - int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, - mSpinnerPadding.left + mSpinnerPadding.right, lp.width); - - // Measure child - child.measure(childWidthSpec, childHeightSpec); - - int childLeft; - int childRight; - - // Position vertically based on gravity setting - int childTop = mSpinnerPadding.top - + ((getMeasuredHeight() - mSpinnerPadding.bottom - - mSpinnerPadding.top - child.getMeasuredHeight()) / 2); - int childBottom = childTop + child.getMeasuredHeight(); - - int width = child.getMeasuredWidth(); - childLeft = 0; - childRight = childLeft + width; - - child.layout(childLeft, childTop, childRight, childBottom); - } - - @Override - public boolean performClick() { - boolean handled = super.performClick(); - - if (!handled) { - handled = true; - - if (!mPopup.isShowing()) { - mPopup.show(); - } - } - - return handled; - } - - public void onClick(DialogInterface dialog, int which) { - setSelection(which); - dialog.dismiss(); - } - - /** - * Sets the prompt to display when the dialog is shown. - * @param prompt the prompt to set - */ - public void setPrompt(CharSequence prompt) { - mPopup.setPromptText(prompt); - } - - /** - * Sets the prompt to display when the dialog is shown. - * @param promptId the resource ID of the prompt to display when the dialog is shown - */ - public void setPromptId(int promptId) { - setPrompt(getContext().getText(promptId)); - } - - /** - * @return The prompt to display when the dialog is shown - */ - public CharSequence getPrompt() { - return mPopup.getHintText(); - } - - int measureContentWidth(SpinnerAdapter adapter, Drawable background) { - if (adapter == null) { - return 0; - } - - int width = 0; - View itemView = null; - int itemType = 0; - final int widthMeasureSpec = - MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - final int heightMeasureSpec = - MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - - // Make sure the number of items we'll measure is capped. If it's a huge data set - // with wildly varying sizes, oh well. - int start = Math.max(0, getSelectedItemPosition()); - final int end = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED); - final int count = end - start; - start = Math.max(0, start - (MAX_ITEMS_MEASURED - count)); - for (int i = start; i < end; i++) { - final int positionType = adapter.getItemViewType(i); - if (positionType != itemType) { - itemType = positionType; - itemView = null; - } - itemView = adapter.getView(i, itemView, this); - if (itemView.getLayoutParams() == null) { - itemView.setLayoutParams(new ViewGroup.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT)); - } - itemView.measure(widthMeasureSpec, heightMeasureSpec); - width = Math.max(width, itemView.getMeasuredWidth()); - } - - // Add background padding to measured width - if (background != null) { - background.getPadding(mTempRect); - width += mTempRect.left + mTempRect.right; - } - - return width; - } - - /** - *

Wrapper class for an Adapter. Transforms the embedded Adapter instance - * into a ListAdapter.

- */ - private static class DropDownAdapter implements ListAdapter, SpinnerAdapter { - private SpinnerAdapter mAdapter; - private ListAdapter mListAdapter; - - /** - *

Creates a new ListAdapter wrapper for the specified adapter.

- * - * @param adapter the Adapter to transform into a ListAdapter - */ - public DropDownAdapter(SpinnerAdapter adapter) { - this.mAdapter = adapter; - if (adapter instanceof ListAdapter) { - this.mListAdapter = (ListAdapter) adapter; - } - } - - public int getCount() { - return mAdapter == null ? 0 : mAdapter.getCount(); - } - - public Object getItem(int position) { - return mAdapter == null ? null : mAdapter.getItem(position); - } - - public long getItemId(int position) { - return mAdapter == null ? -1 : mAdapter.getItemId(position); - } - - public View getView(int position, View convertView, ViewGroup parent) { - return getDropDownView(position, convertView, parent); - } - - public View getDropDownView(int position, View convertView, ViewGroup parent) { - return mAdapter == null ? null : - mAdapter.getDropDownView(position, convertView, parent); - } - - public boolean hasStableIds() { - return mAdapter != null && mAdapter.hasStableIds(); - } - - public void registerDataSetObserver(DataSetObserver observer) { - if (mAdapter != null) { - mAdapter.registerDataSetObserver(observer); - } - } - - public void unregisterDataSetObserver(DataSetObserver observer) { - if (mAdapter != null) { - mAdapter.unregisterDataSetObserver(observer); - } - } - - /** - * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call. - * Otherwise, return true. - */ - public boolean areAllItemsEnabled() { - final ListAdapter adapter = mListAdapter; - if (adapter != null) { - return adapter.areAllItemsEnabled(); - } else { - return true; - } - } - - /** - * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call. - * Otherwise, return true. - */ - public boolean isEnabled(int position) { - final ListAdapter adapter = mListAdapter; - if (adapter != null) { - return adapter.isEnabled(position); - } else { - return true; - } - } - - public int getItemViewType(int position) { - return 0; - } - - public int getViewTypeCount() { - return 1; - } - - public boolean isEmpty() { - return getCount() == 0; - } - } - - /** - * Implements some sort of popup selection interface for selecting a spinner option. - * Allows for different spinner modes. - */ - private interface SpinnerPopup { - public void setAdapter(ListAdapter adapter); - - /** - * Show the popup - */ - public void show(); - - /** - * Dismiss the popup - */ - public void dismiss(); - - /** - * @return true if the popup is showing, false otherwise. - */ - public boolean isShowing(); - - /** - * Set hint text to be displayed to the user. This should provide - * a description of the choice being made. - * @param hintText Hint text to set. - */ - public void setPromptText(CharSequence hintText); - public CharSequence getHintText(); - } - - /* - private class DialogPopup implements SpinnerPopup, DialogInterface.OnClickListener { - private AlertDialog mPopup; - private ListAdapter mListAdapter; - private CharSequence mPrompt; - - public void dismiss() { - mPopup.dismiss(); - mPopup = null; - } - - public boolean isShowing() { - return mPopup != null ? mPopup.isShowing() : false; - } - - public void setAdapter(ListAdapter adapter) { - mListAdapter = adapter; - } - - public void setPromptText(CharSequence hintText) { - mPrompt = hintText; - } - - public CharSequence getHintText() { - return mPrompt; - } - - public void show() { - AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); - if (mPrompt != null) { - builder.setTitle(mPrompt); - } - mPopup = builder.setSingleChoiceItems(mListAdapter, - getSelectedItemPosition(), this).show(); - } - - public void onClick(DialogInterface dialog, int which) { - setSelection(which); - dismiss(); - } - } - */ - - private class DropdownPopup extends IcsListPopupWindow implements SpinnerPopup { - private CharSequence mHintText; - private ListAdapter mAdapter; - - public DropdownPopup(Context context, AttributeSet attrs, int defStyleRes) { - super(context, attrs, 0, defStyleRes); - - setAnchorView(IcsSpinner.this); - setModal(true); - setPromptPosition(POSITION_PROMPT_ABOVE); - setOnItemClickListener(new OnItemClickListener() { - @SuppressWarnings("rawtypes") - public void onItemClick(AdapterView parent, View v, int position, long id) { - IcsSpinner.this.setSelection(position); - dismiss(); - } - }); - } - - @Override - public void setAdapter(ListAdapter adapter) { - super.setAdapter(adapter); - mAdapter = adapter; - } - - public CharSequence getHintText() { - return mHintText; - } - - public void setPromptText(CharSequence hintText) { - // Hint text is ignored for dropdowns, but maintain it here. - mHintText = hintText; - } - - @Override - public void show() { - final int spinnerPaddingLeft = IcsSpinner.this.getPaddingLeft(); - if (mDropDownWidth == WRAP_CONTENT) { - final int spinnerWidth = IcsSpinner.this.getWidth(); - final int spinnerPaddingRight = IcsSpinner.this.getPaddingRight(); - setContentWidth(Math.max( - measureContentWidth((SpinnerAdapter) mAdapter, getBackground()), - spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight)); - } else if (mDropDownWidth == MATCH_PARENT) { - final int spinnerWidth = IcsSpinner.this.getWidth(); - final int spinnerPaddingRight = IcsSpinner.this.getPaddingRight(); - setContentWidth(spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight); - } else { - setContentWidth(mDropDownWidth); - } - final Drawable background = getBackground(); - int bgOffset = 0; - if (background != null) { - background.getPadding(mTempRect); - bgOffset = -mTempRect.left; - } - setHorizontalOffset(bgOffset + spinnerPaddingLeft); - setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); - super.show(); - getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); - setSelection(IcsSpinner.this.getSelectedItemPosition()); - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java deleted file mode 100644 index a7185d08..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.actionbarsherlock.internal.widget; - -import android.view.View; - -final class IcsView { - //No instances - private IcsView() {} - - /** - * Return only the state bits of {@link #getMeasuredWidthAndState()} - * and {@link #getMeasuredHeightAndState()}, combined into one integer. - * The width component is in the regular bits {@link #MEASURED_STATE_MASK} - * and the height component is at the shifted bits - * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. - */ - public static int getMeasuredStateInt(View child) { - return (child.getMeasuredWidth()&View.MEASURED_STATE_MASK) - | ((child.getMeasuredHeight()>>View.MEASURED_HEIGHT_STATE_SHIFT) - & (View.MEASURED_STATE_MASK>>View.MEASURED_HEIGHT_STATE_SHIFT)); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java deleted file mode 100644 index 1a532e06..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.actionbarsherlock.internal.widget; - -import android.content.Context; -import android.content.res.Configuration; -import android.content.res.TypedArray; -import android.graphics.drawable.Drawable; -import android.text.TextUtils.TruncateAt; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewParent; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.Interpolator; -import android.widget.BaseAdapter; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import com.actionbarsherlock.R; -import com.actionbarsherlock.app.ActionBar; -import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; -import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; -import com.actionbarsherlock.internal.nineoldandroids.widget.NineHorizontalScrollView; - -/** - * This widget implements the dynamic action bar tab behavior that can change - * across different configurations or circumstances. - */ -public class ScrollingTabContainerView extends NineHorizontalScrollView - implements IcsAdapterView.OnItemSelectedListener { - //UNUSED private static final String TAG = "ScrollingTabContainerView"; - Runnable mTabSelector; - private TabClickListener mTabClickListener; - - private IcsLinearLayout mTabLayout; - private IcsSpinner mTabSpinner; - private boolean mAllowCollapse; - - private LayoutInflater mInflater; - - int mMaxTabWidth; - private int mContentHeight; - private int mSelectedTabIndex; - - protected Animator mVisibilityAnim; - protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); - - private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); - - private static final int FADE_DURATION = 200; - - public ScrollingTabContainerView(Context context) { - super(context); - setHorizontalScrollBarEnabled(false); - - TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, - R.attr.actionBarStyle, 0); - setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); - a.recycle(); - - mInflater = LayoutInflater.from(context); - - mTabLayout = createTabLayout(); - addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.MATCH_PARENT)); - } - - @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - final int widthMode = MeasureSpec.getMode(widthMeasureSpec); - final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY; - setFillViewport(lockedExpanded); - - final int childCount = mTabLayout.getChildCount(); - if (childCount > 1 && - (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) { - if (childCount > 2) { - mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f); - } else { - mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2; - } - } else { - mMaxTabWidth = -1; - } - - heightMeasureSpec = MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY); - - final boolean canCollapse = !lockedExpanded && mAllowCollapse; - - if (canCollapse) { - // See if we should expand - mTabLayout.measure(MeasureSpec.UNSPECIFIED, heightMeasureSpec); - if (mTabLayout.getMeasuredWidth() > MeasureSpec.getSize(widthMeasureSpec)) { - performCollapse(); - } else { - performExpand(); - } - } else { - performExpand(); - } - - final int oldWidth = getMeasuredWidth(); - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - final int newWidth = getMeasuredWidth(); - - if (lockedExpanded && oldWidth != newWidth) { - // Recenter the tab display if we're at a new (scrollable) size. - setTabSelected(mSelectedTabIndex); - } - } - - /** - * Indicates whether this view is collapsed into a dropdown menu instead - * of traditional tabs. - * @return true if showing as a spinner - */ - private boolean isCollapsed() { - return mTabSpinner != null && mTabSpinner.getParent() == this; - } - - public void setAllowCollapse(boolean allowCollapse) { - mAllowCollapse = allowCollapse; - } - - private void performCollapse() { - if (isCollapsed()) return; - - if (mTabSpinner == null) { - mTabSpinner = createSpinner(); - } - removeView(mTabLayout); - addView(mTabSpinner, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.MATCH_PARENT)); - if (mTabSpinner.getAdapter() == null) { - mTabSpinner.setAdapter(new TabAdapter()); - } - if (mTabSelector != null) { - removeCallbacks(mTabSelector); - mTabSelector = null; - } - mTabSpinner.setSelection(mSelectedTabIndex); - } - - private boolean performExpand() { - if (!isCollapsed()) return false; - - removeView(mTabSpinner); - addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.MATCH_PARENT)); - setTabSelected(mTabSpinner.getSelectedItemPosition()); - return false; - } - - public void setTabSelected(int position) { - mSelectedTabIndex = position; - final int tabCount = mTabLayout.getChildCount(); - for (int i = 0; i < tabCount; i++) { - final View child = mTabLayout.getChildAt(i); - final boolean isSelected = i == position; - child.setSelected(isSelected); - if (isSelected) { - animateToTab(position); - } - } - } - - public void setContentHeight(int contentHeight) { - mContentHeight = contentHeight; - requestLayout(); - } - - private IcsLinearLayout createTabLayout() { - final IcsLinearLayout tabLayout = (IcsLinearLayout) LayoutInflater.from(getContext()) - .inflate(R.layout.abs__action_bar_tab_bar_view, null); - tabLayout.setLayoutParams(new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); - return tabLayout; - } - - private IcsSpinner createSpinner() { - final IcsSpinner spinner = new IcsSpinner(getContext(), null, - R.attr.actionDropDownStyle); - spinner.setLayoutParams(new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); - spinner.setOnItemSelectedListener(this); - return spinner; - } - - @Override - protected void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - - // Action bar can change size on configuration changes. - // Reread the desired height from the theme-specified style. - TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, - R.attr.actionBarStyle, 0); - setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); - a.recycle(); - } - - public void animateToVisibility(int visibility) { - if (mVisibilityAnim != null) { - mVisibilityAnim.cancel(); - } - if (visibility == VISIBLE) { - if (getVisibility() != VISIBLE) { - setAlpha(0); - } - ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); - anim.setDuration(FADE_DURATION); - anim.setInterpolator(sAlphaInterpolator); - - anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); - anim.start(); - } else { - ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); - anim.setDuration(FADE_DURATION); - anim.setInterpolator(sAlphaInterpolator); - - anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); - anim.start(); - } - } - - public void animateToTab(final int position) { - final View tabView = mTabLayout.getChildAt(position); - if (mTabSelector != null) { - removeCallbacks(mTabSelector); - } - mTabSelector = new Runnable() { - public void run() { - final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2; - smoothScrollTo(scrollPos, 0); - mTabSelector = null; - } - }; - post(mTabSelector); - } - - @Override - public void onAttachedToWindow() { - super.onAttachedToWindow(); - if (mTabSelector != null) { - // Re-post the selector we saved - post(mTabSelector); - } - } - - @Override - public void onDetachedFromWindow() { - super.onDetachedFromWindow(); - if (mTabSelector != null) { - removeCallbacks(mTabSelector); - } - } - - private TabView createTabView(ActionBar.Tab tab, boolean forAdapter) { - //Workaround for not being able to pass a defStyle on pre-3.0 - final TabView tabView = (TabView)mInflater.inflate(R.layout.abs__action_bar_tab, null); - tabView.init(this, tab, forAdapter); - - if (forAdapter) { - tabView.setBackgroundDrawable(null); - tabView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, - mContentHeight)); - } else { - tabView.setFocusable(true); - - if (mTabClickListener == null) { - mTabClickListener = new TabClickListener(); - } - tabView.setOnClickListener(mTabClickListener); - } - return tabView; - } - - public void addTab(ActionBar.Tab tab, boolean setSelected) { - TabView tabView = createTabView(tab, false); - mTabLayout.addView(tabView, new IcsLinearLayout.LayoutParams(0, - LayoutParams.MATCH_PARENT, 1)); - if (mTabSpinner != null) { - ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); - } - if (setSelected) { - tabView.setSelected(true); - } - if (mAllowCollapse) { - requestLayout(); - } - } - - public void addTab(ActionBar.Tab tab, int position, boolean setSelected) { - final TabView tabView = createTabView(tab, false); - mTabLayout.addView(tabView, position, new IcsLinearLayout.LayoutParams( - 0, LayoutParams.MATCH_PARENT, 1)); - if (mTabSpinner != null) { - ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); - } - if (setSelected) { - tabView.setSelected(true); - } - if (mAllowCollapse) { - requestLayout(); - } - } - - public void updateTab(int position) { - ((TabView) mTabLayout.getChildAt(position)).update(); - if (mTabSpinner != null) { - ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); - } - if (mAllowCollapse) { - requestLayout(); - } - } - - public void removeTabAt(int position) { - mTabLayout.removeViewAt(position); - if (mTabSpinner != null) { - ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); - } - if (mAllowCollapse) { - requestLayout(); - } - } - - public void removeAllTabs() { - mTabLayout.removeAllViews(); - if (mTabSpinner != null) { - ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); - } - if (mAllowCollapse) { - requestLayout(); - } - } - - @Override - public void onItemSelected(IcsAdapterView parent, View view, int position, long id) { - TabView tabView = (TabView) view; - tabView.getTab().select(); - } - - @Override - public void onNothingSelected(IcsAdapterView parent) { - } - - public static class TabView extends LinearLayout { - private ScrollingTabContainerView mParent; - private ActionBar.Tab mTab; - private CapitalizingTextView mTextView; - private ImageView mIconView; - private View mCustomView; - - public TabView(Context context, AttributeSet attrs) { - //TODO super(context, null, R.attr.actionBarTabStyle); - super(context, attrs); - } - - public void init(ScrollingTabContainerView parent, ActionBar.Tab tab, boolean forList) { - mParent = parent; - mTab = tab; - - if (forList) { - setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); - } - - update(); - } - - public void bindTab(ActionBar.Tab tab) { - mTab = tab; - update(); - } - - @Override - public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - - // Re-measure if we went beyond our maximum size. - if (mParent.mMaxTabWidth > 0 && getMeasuredWidth() > mParent.mMaxTabWidth) { - super.onMeasure(MeasureSpec.makeMeasureSpec(mParent.mMaxTabWidth, MeasureSpec.EXACTLY), - heightMeasureSpec); - } - } - - public void update() { - final ActionBar.Tab tab = mTab; - final View custom = tab.getCustomView(); - if (custom != null) { - final ViewParent customParent = custom.getParent(); - if (customParent != this) { - if (customParent != null) ((ViewGroup) customParent).removeView(custom); - addView(custom); - } - mCustomView = custom; - if (mTextView != null) mTextView.setVisibility(GONE); - if (mIconView != null) { - mIconView.setVisibility(GONE); - mIconView.setImageDrawable(null); - } - } else { - if (mCustomView != null) { - removeView(mCustomView); - mCustomView = null; - } - - final Drawable icon = tab.getIcon(); - final CharSequence text = tab.getText(); - - if (icon != null) { - if (mIconView == null) { - ImageView iconView = new ImageView(getContext()); - LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.WRAP_CONTENT); - lp.gravity = Gravity.CENTER_VERTICAL; - iconView.setLayoutParams(lp); - addView(iconView, 0); - mIconView = iconView; - } - mIconView.setImageDrawable(icon); - mIconView.setVisibility(VISIBLE); - } else if (mIconView != null) { - mIconView.setVisibility(GONE); - mIconView.setImageDrawable(null); - } - - if (text != null) { - if (mTextView == null) { - CapitalizingTextView textView = new CapitalizingTextView(getContext(), null, - R.attr.actionBarTabTextStyle); - textView.setEllipsize(TruncateAt.END); - LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, - LayoutParams.WRAP_CONTENT); - lp.gravity = Gravity.CENTER_VERTICAL; - textView.setLayoutParams(lp); - addView(textView); - mTextView = textView; - } - mTextView.setTextCompat(text); - mTextView.setVisibility(VISIBLE); - } else if (mTextView != null) { - mTextView.setVisibility(GONE); - mTextView.setText(null); - } - - if (mIconView != null) { - mIconView.setContentDescription(tab.getContentDescription()); - } - } - } - - public ActionBar.Tab getTab() { - return mTab; - } - } - - private class TabAdapter extends BaseAdapter { - @Override - public int getCount() { - return mTabLayout.getChildCount(); - } - - @Override - public Object getItem(int position) { - return ((TabView) mTabLayout.getChildAt(position)).getTab(); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - if (convertView == null) { - convertView = createTabView((ActionBar.Tab) getItem(position), true); - } else { - ((TabView) convertView).bindTab((ActionBar.Tab) getItem(position)); - } - return convertView; - } - } - - private class TabClickListener implements OnClickListener { - public void onClick(View view) { - TabView tabView = (TabView) view; - tabView.getTab().select(); - final int tabCount = mTabLayout.getChildCount(); - for (int i = 0; i < tabCount; i++) { - final View child = mTabLayout.getChildAt(i); - child.setSelected(child == view); - } - } - } - - protected class VisibilityAnimListener implements Animator.AnimatorListener { - private boolean mCanceled = false; - private int mFinalVisibility; - - public VisibilityAnimListener withFinalVisibility(int visibility) { - mFinalVisibility = visibility; - return this; - } - - @Override - public void onAnimationStart(Animator animation) { - setVisibility(VISIBLE); - mVisibilityAnim = animation; - mCanceled = false; - } - - @Override - public void onAnimationEnd(Animator animation) { - if (mCanceled) return; - - mVisibilityAnim = null; - setVisibility(mFinalVisibility); - } - - @Override - public void onAnimationCancel(Animator animation) { - mCanceled = true; - } - - @Override - public void onAnimationRepeat(Animator animation) { - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionMode.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionMode.java deleted file mode 100644 index 81b4cd4d..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionMode.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.view; - -import android.view.View; - - -/** - * Represents a contextual mode of the user interface. Action modes can be used for - * modal interactions with content and replace parts of the normal UI until finished. - * Examples of good action modes include selection modes, search, content editing, etc. - */ -public abstract class ActionMode { - private Object mTag; - - /** - * Set a tag object associated with this ActionMode. - * - *

Like the tag available to views, this allows applications to associate arbitrary - * data with an ActionMode for later reference. - * - * @param tag Tag to associate with this ActionMode - * - * @see #getTag() - */ - public void setTag(Object tag) { - mTag = tag; - } - - /** - * Retrieve the tag object associated with this ActionMode. - * - *

Like the tag available to views, this allows applications to associate arbitrary - * data with an ActionMode for later reference. - * - * @return Tag associated with this ActionMode - * - * @see #setTag(Object) - */ - public Object getTag() { - return mTag; - } - - /** - * Set the title of the action mode. This method will have no visible effect if - * a custom view has been set. - * - * @param title Title string to set - * - * @see #setTitle(int) - * @see #setCustomView(View) - */ - public abstract void setTitle(CharSequence title); - - /** - * Set the title of the action mode. This method will have no visible effect if - * a custom view has been set. - * - * @param resId Resource ID of a string to set as the title - * - * @see #setTitle(CharSequence) - * @see #setCustomView(View) - */ - public abstract void setTitle(int resId); - - /** - * Set the subtitle of the action mode. This method will have no visible effect if - * a custom view has been set. - * - * @param subtitle Subtitle string to set - * - * @see #setSubtitle(int) - * @see #setCustomView(View) - */ - public abstract void setSubtitle(CharSequence subtitle); - - /** - * Set the subtitle of the action mode. This method will have no visible effect if - * a custom view has been set. - * - * @param resId Resource ID of a string to set as the subtitle - * - * @see #setSubtitle(CharSequence) - * @see #setCustomView(View) - */ - public abstract void setSubtitle(int resId); - - /** - * Set a custom view for this action mode. The custom view will take the place of - * the title and subtitle. Useful for things like search boxes. - * - * @param view Custom view to use in place of the title/subtitle. - * - * @see #setTitle(CharSequence) - * @see #setSubtitle(CharSequence) - */ - public abstract void setCustomView(View view); - - /** - * Invalidate the action mode and refresh menu content. The mode's - * {@link ActionMode.Callback} will have its - * {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called. - * If it returns true the menu will be scanned for updated content and any relevant changes - * will be reflected to the user. - */ - public abstract void invalidate(); - - /** - * Finish and close this action mode. The action mode's {@link ActionMode.Callback} will - * have its {@link Callback#onDestroyActionMode(ActionMode)} method called. - */ - public abstract void finish(); - - /** - * Returns the menu of actions that this action mode presents. - * @return The action mode's menu. - */ - public abstract Menu getMenu(); - - /** - * Returns the current title of this action mode. - * @return Title text - */ - public abstract CharSequence getTitle(); - - /** - * Returns the current subtitle of this action mode. - * @return Subtitle text - */ - public abstract CharSequence getSubtitle(); - - /** - * Returns the current custom view for this action mode. - * @return The current custom view - */ - public abstract View getCustomView(); - - /** - * Returns a {@link MenuInflater} with the ActionMode's context. - */ - public abstract MenuInflater getMenuInflater(); - - /** - * Returns whether the UI presenting this action mode can take focus or not. - * This is used by internal components within the framework that would otherwise - * present an action mode UI that requires focus, such as an EditText as a custom view. - * - * @return true if the UI used to show this action mode can take focus - * @hide Internal use only - */ - public boolean isUiFocusable() { - return true; - } - - /** - * Callback interface for action modes. Supplied to - * {@link View#startActionMode(Callback)}, a Callback - * configures and handles events raised by a user's interaction with an action mode. - * - *

An action mode's lifecycle is as follows: - *

    - *
  • {@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial - * creation
  • - *
  • {@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation - * and any time the {@link ActionMode} is invalidated
  • - *
  • {@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a - * contextual action button is clicked
  • - *
  • {@link Callback#onDestroyActionMode(ActionMode)} when the action mode - * is closed
  • - *
- */ - public interface Callback { - /** - * Called when action mode is first created. The menu supplied will be used to - * generate action buttons for the action mode. - * - * @param mode ActionMode being created - * @param menu Menu used to populate action buttons - * @return true if the action mode should be created, false if entering this - * mode should be aborted. - */ - public boolean onCreateActionMode(ActionMode mode, Menu menu); - - /** - * Called to refresh an action mode's action menu whenever it is invalidated. - * - * @param mode ActionMode being prepared - * @param menu Menu used to populate action buttons - * @return true if the menu or action mode was updated, false otherwise. - */ - public boolean onPrepareActionMode(ActionMode mode, Menu menu); - - /** - * Called to report a user click on an action button. - * - * @param mode The current ActionMode - * @param item The item that was clicked - * @return true if this callback handled the event, false if the standard MenuItem - * invocation should continue. - */ - public boolean onActionItemClicked(ActionMode mode, MenuItem item); - - /** - * Called when an action mode is about to be exited and destroyed. - * - * @param mode The current ActionMode being destroyed - */ - public void onDestroyActionMode(ActionMode mode); - } -} \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionProvider.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionProvider.java deleted file mode 100644 index ae7cb1fe..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionProvider.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.view; - -import android.content.Context; -import android.view.View; - -/** - * This class is a mediator for accomplishing a given task, for example sharing a file. - * It is responsible for creating a view that performs an action that accomplishes the task. - * This class also implements other functions such a performing a default action. - *

- * An ActionProvider can be optionally specified for a {@link MenuItem} and in such a - * case it will be responsible for creating the action view that appears in the - * {@link android.app.ActionBar} as a substitute for the menu item when the item is - * displayed as an action item. Also the provider is responsible for performing a - * default action if a menu item placed on the overflow menu of the ActionBar is - * selected and none of the menu item callbacks has handled the selection. For this - * case the provider can also optionally provide a sub-menu for accomplishing the - * task at hand. - *

- *

- * There are two ways for using an action provider for creating and handling of action views: - *

    - *
  • - * Setting the action provider on a {@link MenuItem} directly by calling - * {@link MenuItem#setActionProvider(ActionProvider)}. - *
  • - *
  • - * Declaring the action provider in the menu XML resource. For example: - *
    - * 
    - *   <item android:id="@+id/my_menu_item"
    - *     android:title="Title"
    - *     android:icon="@drawable/my_menu_item_icon"
    - *     android:showAsAction="ifRoom"
    - *     android:actionProviderClass="foo.bar.SomeActionProvider" />
    - * 
    - * 
    - *
  • - *
- *

- * - * @see MenuItem#setActionProvider(ActionProvider) - * @see MenuItem#getActionProvider() - */ -public abstract class ActionProvider { - private SubUiVisibilityListener mSubUiVisibilityListener; - - /** - * Creates a new instance. - * - * @param context Context for accessing resources. - */ - public ActionProvider(Context context) { - } - - /** - * Factory method for creating new action views. - * - * @return A new action view. - */ - public abstract View onCreateActionView(); - - /** - * Performs an optional default action. - *

- * For the case of an action provider placed in a menu item not shown as an action this - * method is invoked if previous callbacks for processing menu selection has handled - * the event. - *

- *

- * A menu item selection is processed in the following order: - *

    - *
  • - * Receiving a call to {@link MenuItem.OnMenuItemClickListener#onMenuItemClick - * MenuItem.OnMenuItemClickListener.onMenuItemClick}. - *
  • - *
  • - * Receiving a call to {@link android.app.Activity#onOptionsItemSelected(MenuItem) - * Activity.onOptionsItemSelected(MenuItem)} - *
  • - *
  • - * Receiving a call to {@link android.app.Fragment#onOptionsItemSelected(MenuItem) - * Fragment.onOptionsItemSelected(MenuItem)} - *
  • - *
  • - * Launching the {@link android.content.Intent} set via - * {@link MenuItem#setIntent(android.content.Intent) MenuItem.setIntent(android.content.Intent)} - *
  • - *
  • - * Invoking this method. - *
  • - *
- *

- *

- * The default implementation does not perform any action and returns false. - *

- */ - public boolean onPerformDefaultAction() { - return false; - } - - /** - * Determines if this ActionProvider has a submenu associated with it. - * - *

Associated submenus will be shown when an action view is not. This - * provider instance will receive a call to {@link #onPrepareSubMenu(SubMenu)} - * after the call to {@link #onPerformDefaultAction()} and before a submenu is - * displayed to the user. - * - * @return true if the item backed by this provider should have an associated submenu - */ - public boolean hasSubMenu() { - return false; - } - - /** - * Called to prepare an associated submenu for the menu item backed by this ActionProvider. - * - *

if {@link #hasSubMenu()} returns true, this method will be called when the - * menu item is selected to prepare the submenu for presentation to the user. Apps - * may use this to create or alter submenu content right before display. - * - * @param subMenu Submenu that will be displayed - */ - public void onPrepareSubMenu(SubMenu subMenu) { - } - - /** - * Notify the system that the visibility of an action view's sub-UI such as - * an anchored popup has changed. This will affect how other system - * visibility notifications occur. - * - * @hide Pending future API approval - */ - public void subUiVisibilityChanged(boolean isVisible) { - if (mSubUiVisibilityListener != null) { - mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible); - } - } - - /** - * @hide Internal use only - */ - public void setSubUiVisibilityListener(SubUiVisibilityListener listener) { - mSubUiVisibilityListener = listener; - } - - /** - * @hide Internal use only - */ - public interface SubUiVisibilityListener { - public void onSubUiVisibilityChanged(boolean isVisible); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/CollapsibleActionView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/CollapsibleActionView.java deleted file mode 100644 index 43281b01..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/CollapsibleActionView.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.view; - -/** - * When a {@link View} implements this interface it will receive callbacks - * when expanded or collapsed as an action view alongside the optional, - * app-specified callbacks to {@link OnActionExpandListener}. - * - *

See {@link MenuItem} for more information about action views. - * See {@link android.app.ActionBar} for more information about the action bar. - */ -public interface CollapsibleActionView { - /** - * Called when this view is expanded as an action view. - * See {@link MenuItem#expandActionView()}. - */ - public void onActionViewExpanded(); - - /** - * Called when this view is collapsed as an action view. - * See {@link MenuItem#collapseActionView()}. - */ - public void onActionViewCollapsed(); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Menu.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Menu.java deleted file mode 100644 index 951f4cce..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Menu.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.view; - -import android.content.ComponentName; -import android.content.Intent; -import android.view.KeyEvent; - -/** - * Interface for managing the items in a menu. - *

- * By default, every Activity supports an options menu of actions or options. - * You can add items to this menu and handle clicks on your additions. The - * easiest way of adding menu items is inflating an XML file into the - * {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to - * clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and - * {@link Activity#onContextItemSelected(MenuItem)}. - *

- * Different menu types support different features: - *

    - *
  1. Context menus: Do not support item shortcuts and item icons. - *
  2. Options menus: The icon menus do not support item check - * marks and only show the item's - * {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The - * expanded menus (only available if six or more menu items are visible, - * reached via the 'More' item in the icon menu) do not show item icons, and - * item check marks are discouraged. - *
  3. Sub menus: Do not support item icons, or nested sub menus. - *
- * - *
- *

Developer Guides

- *

For more information about creating menus, read the - * Menus developer guide.

- *
- */ -public interface Menu { - - /** - * This is the part of an order integer that the user can provide. - * @hide - */ - static final int USER_MASK = 0x0000ffff; - /** - * Bit shift of the user portion of the order integer. - * @hide - */ - static final int USER_SHIFT = 0; - - /** - * This is the part of an order integer that supplies the category of the - * item. - * @hide - */ - static final int CATEGORY_MASK = 0xffff0000; - /** - * Bit shift of the category portion of the order integer. - * @hide - */ - static final int CATEGORY_SHIFT = 16; - - /** - * Value to use for group and item identifier integers when you don't care - * about them. - */ - static final int NONE = 0; - - /** - * First value for group and item identifier integers. - */ - static final int FIRST = 1; - - // Implementation note: Keep these CATEGORY_* in sync with the category enum - // in attrs.xml - - /** - * Category code for the order integer for items/groups that are part of a - * container -- or/add this with your base value. - */ - static final int CATEGORY_CONTAINER = 0x00010000; - - /** - * Category code for the order integer for items/groups that are provided by - * the system -- or/add this with your base value. - */ - static final int CATEGORY_SYSTEM = 0x00020000; - - /** - * Category code for the order integer for items/groups that are - * user-supplied secondary (infrequently used) options -- or/add this with - * your base value. - */ - static final int CATEGORY_SECONDARY = 0x00030000; - - /** - * Category code for the order integer for items/groups that are - * alternative actions on the data that is currently displayed -- or/add - * this with your base value. - */ - static final int CATEGORY_ALTERNATIVE = 0x00040000; - - /** - * Flag for {@link #addIntentOptions}: if set, do not automatically remove - * any existing menu items in the same group. - */ - static final int FLAG_APPEND_TO_GROUP = 0x0001; - - /** - * Flag for {@link #performShortcut}: if set, do not close the menu after - * executing the shortcut. - */ - static final int FLAG_PERFORM_NO_CLOSE = 0x0001; - - /** - * Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always - * close the menu after executing the shortcut. Closing the menu also resets - * the prepared state. - */ - static final int FLAG_ALWAYS_PERFORM_CLOSE = 0x0002; - - /** - * Add a new item to the menu. This item displays the given title for its - * label. - * - * @param title The text to display for the item. - * @return The newly added menu item. - */ - public MenuItem add(CharSequence title); - - /** - * Add a new item to the menu. This item displays the given title for its - * label. - * - * @param titleRes Resource identifier of title string. - * @return The newly added menu item. - */ - public MenuItem add(int titleRes); - - /** - * Add a new item to the menu. This item displays the given title for its - * label. - * - * @param groupId The group identifier that this item should be part of. - * This can be used to define groups of items for batch state - * changes. Normally use {@link #NONE} if an item should not be in a - * group. - * @param itemId Unique item ID. Use {@link #NONE} if you do not need a - * unique ID. - * @param order The order for the item. Use {@link #NONE} if you do not care - * about the order. See {@link MenuItem#getOrder()}. - * @param title The text to display for the item. - * @return The newly added menu item. - */ - public MenuItem add(int groupId, int itemId, int order, CharSequence title); - - /** - * Variation on {@link #add(int, int, int, CharSequence)} that takes a - * string resource identifier instead of the string itself. - * - * @param groupId The group identifier that this item should be part of. - * This can also be used to define groups of items for batch state - * changes. Normally use {@link #NONE} if an item should not be in a - * group. - * @param itemId Unique item ID. Use {@link #NONE} if you do not need a - * unique ID. - * @param order The order for the item. Use {@link #NONE} if you do not care - * about the order. See {@link MenuItem#getOrder()}. - * @param titleRes Resource identifier of title string. - * @return The newly added menu item. - */ - public MenuItem add(int groupId, int itemId, int order, int titleRes); - - /** - * Add a new sub-menu to the menu. This item displays the given title for - * its label. To modify other attributes on the submenu's menu item, use - * {@link SubMenu#getItem()}. - * - * @param title The text to display for the item. - * @return The newly added sub-menu - */ - SubMenu addSubMenu(final CharSequence title); - - /** - * Add a new sub-menu to the menu. This item displays the given title for - * its label. To modify other attributes on the submenu's menu item, use - * {@link SubMenu#getItem()}. - * - * @param titleRes Resource identifier of title string. - * @return The newly added sub-menu - */ - SubMenu addSubMenu(final int titleRes); - - /** - * Add a new sub-menu to the menu. This item displays the given - * title for its label. To modify other attributes on the - * submenu's menu item, use {@link SubMenu#getItem()}. - *

- * Note that you can only have one level of sub-menus, i.e. you cannnot add - * a subMenu to a subMenu: An {@link UnsupportedOperationException} will be - * thrown if you try. - * - * @param groupId The group identifier that this item should be part of. - * This can also be used to define groups of items for batch state - * changes. Normally use {@link #NONE} if an item should not be in a - * group. - * @param itemId Unique item ID. Use {@link #NONE} if you do not need a - * unique ID. - * @param order The order for the item. Use {@link #NONE} if you do not care - * about the order. See {@link MenuItem#getOrder()}. - * @param title The text to display for the item. - * @return The newly added sub-menu - */ - SubMenu addSubMenu(final int groupId, final int itemId, int order, final CharSequence title); - - /** - * Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes - * a string resource identifier for the title instead of the string itself. - * - * @param groupId The group identifier that this item should be part of. - * This can also be used to define groups of items for batch state - * changes. Normally use {@link #NONE} if an item should not be in a group. - * @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID. - * @param order The order for the item. Use {@link #NONE} if you do not care about the - * order. See {@link MenuItem#getOrder()}. - * @param titleRes Resource identifier of title string. - * @return The newly added sub-menu - */ - SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes); - - /** - * Add a group of menu items corresponding to actions that can be performed - * for a particular Intent. The Intent is most often configured with a null - * action, the data that the current activity is working with, and includes - * either the {@link Intent#CATEGORY_ALTERNATIVE} or - * {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have - * said they would like to be included as optional action. You can, however, - * use any Intent you want. - * - *

- * See {@link android.content.pm.PackageManager#queryIntentActivityOptions} - * for more * details on the caller, specifics, and - * intent arguments. The list returned by that function is used - * to populate the resulting menu items. - * - *

- * All of the menu items of possible options for the intent will be added - * with the given group and id. You can use the group to control ordering of - * the items in relation to other items in the menu. Normally this function - * will automatically remove any existing items in the menu in the same - * group and place a divider above and below the added items; this behavior - * can be modified with the flags parameter. For each of the - * generated items {@link MenuItem#setIntent} is called to associate the - * appropriate Intent with the item; this means the activity will - * automatically be started for you without having to do anything else. - * - * @param groupId The group identifier that the items should be part of. - * This can also be used to define groups of items for batch state - * changes. Normally use {@link #NONE} if the items should not be in - * a group. - * @param itemId Unique item ID. Use {@link #NONE} if you do not need a - * unique ID. - * @param order The order for the items. Use {@link #NONE} if you do not - * care about the order. See {@link MenuItem#getOrder()}. - * @param caller The current activity component name as defined by - * queryIntentActivityOptions(). - * @param specifics Specific items to place first as defined by - * queryIntentActivityOptions(). - * @param intent Intent describing the kinds of items to populate in the - * list as defined by queryIntentActivityOptions(). - * @param flags Additional options controlling how the items are added. - * @param outSpecificItems Optional array in which to place the menu items - * that were generated for each of the specifics that were - * requested. Entries may be null if no activity was found for that - * specific action. - * @return The number of menu items that were added. - * - * @see #FLAG_APPEND_TO_GROUP - * @see MenuItem#setIntent - * @see android.content.pm.PackageManager#queryIntentActivityOptions - */ - public int addIntentOptions(int groupId, int itemId, int order, - ComponentName caller, Intent[] specifics, - Intent intent, int flags, MenuItem[] outSpecificItems); - - /** - * Remove the item with the given identifier. - * - * @param id The item to be removed. If there is no item with this - * identifier, nothing happens. - */ - public void removeItem(int id); - - /** - * Remove all items in the given group. - * - * @param groupId The group to be removed. If there are no items in this - * group, nothing happens. - */ - public void removeGroup(int groupId); - - /** - * Remove all existing items from the menu, leaving it empty as if it had - * just been created. - */ - public void clear(); - - /** - * Control whether a particular group of items can show a check mark. This - * is similar to calling {@link MenuItem#setCheckable} on all of the menu items - * with the given group identifier, but in addition you can control whether - * this group contains a mutually-exclusive set items. This should be called - * after the items of the group have been added to the menu. - * - * @param group The group of items to operate on. - * @param checkable Set to true to allow a check mark, false to - * disallow. The default is false. - * @param exclusive If set to true, only one item in this group can be - * checked at a time; checking an item will automatically - * uncheck all others in the group. If set to false, each - * item can be checked independently of the others. - * - * @see MenuItem#setCheckable - * @see MenuItem#setChecked - */ - public void setGroupCheckable(int group, boolean checkable, boolean exclusive); - - /** - * Show or hide all menu items that are in the given group. - * - * @param group The group of items to operate on. - * @param visible If true the items are visible, else they are hidden. - * - * @see MenuItem#setVisible - */ - public void setGroupVisible(int group, boolean visible); - - /** - * Enable or disable all menu items that are in the given group. - * - * @param group The group of items to operate on. - * @param enabled If true the items will be enabled, else they will be disabled. - * - * @see MenuItem#setEnabled - */ - public void setGroupEnabled(int group, boolean enabled); - - /** - * Return whether the menu currently has item items that are visible. - * - * @return True if there is one or more item visible, - * else false. - */ - public boolean hasVisibleItems(); - - /** - * Return the menu item with a particular identifier. - * - * @param id The identifier to find. - * - * @return The menu item object, or null if there is no item with - * this identifier. - */ - public MenuItem findItem(int id); - - /** - * Get the number of items in the menu. Note that this will change any - * times items are added or removed from the menu. - * - * @return The item count. - */ - public int size(); - - /** - * Gets the menu item at the given index. - * - * @param index The index of the menu item to return. - * @return The menu item. - * @exception IndexOutOfBoundsException - * when {@code index < 0 || >= size()} - */ - public MenuItem getItem(int index); - - /** - * Closes the menu, if open. - */ - public void close(); - - /** - * Execute the menu item action associated with the given shortcut - * character. - * - * @param keyCode The keycode of the shortcut key. - * @param event Key event message. - * @param flags Additional option flags or 0. - * - * @return If the given shortcut exists and is shown, returns - * true; else returns false. - * - * @see #FLAG_PERFORM_NO_CLOSE - */ - public boolean performShortcut(int keyCode, KeyEvent event, int flags); - - /** - * Is a keypress one of the defined shortcut keys for this window. - * @param keyCode the key code from {@link KeyEvent} to check. - * @param event the {@link KeyEvent} to use to help check. - */ - boolean isShortcutKey(int keyCode, KeyEvent event); - - /** - * Execute the menu item action associated with the given menu identifier. - * - * @param id Identifier associated with the menu item. - * @param flags Additional option flags or 0. - * - * @return If the given identifier exists and is shown, returns - * true; else returns false. - * - * @see #FLAG_PERFORM_NO_CLOSE - */ - public boolean performIdentifierAction(int id, int flags); - - - /** - * Control whether the menu should be running in qwerty mode (alphabetic - * shortcuts) or 12-key mode (numeric shortcuts). - * - * @param isQwerty If true the menu will use alphabetic shortcuts; else it - * will use numeric shortcuts. - */ - public void setQwertyMode(boolean isQwerty); -} - diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java deleted file mode 100644 index 96945974..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java +++ /dev/null @@ -1,472 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * 2011 Jake Wharton - * - * 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 com.actionbarsherlock.view; - -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import android.content.Context; -import android.content.res.TypedArray; -import android.content.res.XmlResourceParser; -import android.util.AttributeSet; -import android.util.Log; -import android.util.TypedValue; -import android.util.Xml; -import android.view.InflateException; -import android.view.View; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.view.menu.MenuItemImpl; - -/** - * This class is used to instantiate menu XML files into Menu objects. - *

- * For performance reasons, menu inflation relies heavily on pre-processing of - * XML files that is done at build time. Therefore, it is not currently possible - * to use MenuInflater with an XmlPullParser over a plain XML file at runtime; - * it only works with an XmlPullParser returned from a compiled resource (R. - * something file.) - */ -public class MenuInflater { - private static final String LOG_TAG = "MenuInflater"; - - /** Menu tag name in XML. */ - private static final String XML_MENU = "menu"; - - /** Group tag name in XML. */ - private static final String XML_GROUP = "group"; - - /** Item tag name in XML. */ - private static final String XML_ITEM = "item"; - - private static final int NO_ID = 0; - - private static final Class[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class}; - - private static final Class[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE; - - private final Object[] mActionViewConstructorArguments; - - private final Object[] mActionProviderConstructorArguments; - - private Context mContext; - - /** - * Constructs a menu inflater. - * - * @see Activity#getMenuInflater() - */ - public MenuInflater(Context context) { - mContext = context; - mActionViewConstructorArguments = new Object[] {context}; - mActionProviderConstructorArguments = mActionViewConstructorArguments; - } - - /** - * Inflate a menu hierarchy from the specified XML resource. Throws - * {@link InflateException} if there is an error. - * - * @param menuRes Resource ID for an XML layout resource to load (e.g., - * R.menu.main_activity) - * @param menu The Menu to inflate into. The items and submenus will be - * added to this Menu. - */ - public void inflate(int menuRes, Menu menu) { - XmlResourceParser parser = null; - try { - parser = mContext.getResources().getLayout(menuRes); - AttributeSet attrs = Xml.asAttributeSet(parser); - - parseMenu(parser, attrs, menu); - } catch (XmlPullParserException e) { - throw new InflateException("Error inflating menu XML", e); - } catch (IOException e) { - throw new InflateException("Error inflating menu XML", e); - } finally { - if (parser != null) parser.close(); - } - } - - /** - * Called internally to fill the given menu. If a sub menu is seen, it will - * call this recursively. - */ - private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu) - throws XmlPullParserException, IOException { - MenuState menuState = new MenuState(menu); - - int eventType = parser.getEventType(); - String tagName; - boolean lookingForEndOfUnknownTag = false; - String unknownTagName = null; - - // This loop will skip to the menu start tag - do { - if (eventType == XmlPullParser.START_TAG) { - tagName = parser.getName(); - if (tagName.equals(XML_MENU)) { - // Go to next tag - eventType = parser.next(); - break; - } - - throw new RuntimeException("Expecting menu, got " + tagName); - } - eventType = parser.next(); - } while (eventType != XmlPullParser.END_DOCUMENT); - - boolean reachedEndOfMenu = false; - while (!reachedEndOfMenu) { - switch (eventType) { - case XmlPullParser.START_TAG: - if (lookingForEndOfUnknownTag) { - break; - } - - tagName = parser.getName(); - if (tagName.equals(XML_GROUP)) { - menuState.readGroup(attrs); - } else if (tagName.equals(XML_ITEM)) { - menuState.readItem(attrs); - } else if (tagName.equals(XML_MENU)) { - // A menu start tag denotes a submenu for an item - SubMenu subMenu = menuState.addSubMenuItem(); - - // Parse the submenu into returned SubMenu - parseMenu(parser, attrs, subMenu); - } else { - lookingForEndOfUnknownTag = true; - unknownTagName = tagName; - } - break; - - case XmlPullParser.END_TAG: - tagName = parser.getName(); - if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) { - lookingForEndOfUnknownTag = false; - unknownTagName = null; - } else if (tagName.equals(XML_GROUP)) { - menuState.resetGroup(); - } else if (tagName.equals(XML_ITEM)) { - // Add the item if it hasn't been added (if the item was - // a submenu, it would have been added already) - if (!menuState.hasAddedItem()) { - if (menuState.itemActionProvider != null && - menuState.itemActionProvider.hasSubMenu()) { - menuState.addSubMenuItem(); - } else { - menuState.addItem(); - } - } - } else if (tagName.equals(XML_MENU)) { - reachedEndOfMenu = true; - } - break; - - case XmlPullParser.END_DOCUMENT: - throw new RuntimeException("Unexpected end of document"); - } - - eventType = parser.next(); - } - } - - private static class InflatedOnMenuItemClickListener - implements MenuItem.OnMenuItemClickListener { - private static final Class[] PARAM_TYPES = new Class[] { MenuItem.class }; - - private Context mContext; - private Method mMethod; - - public InflatedOnMenuItemClickListener(Context context, String methodName) { - mContext = context; - Class c = context.getClass(); - try { - mMethod = c.getMethod(methodName, PARAM_TYPES); - } catch (Exception e) { - InflateException ex = new InflateException( - "Couldn't resolve menu item onClick handler " + methodName + - " in class " + c.getName()); - ex.initCause(e); - throw ex; - } - } - - public boolean onMenuItemClick(MenuItem item) { - try { - if (mMethod.getReturnType() == Boolean.TYPE) { - return (Boolean) mMethod.invoke(mContext, item); - } else { - mMethod.invoke(mContext, item); - return true; - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - /** - * State for the current menu. - *

- * Groups can not be nested unless there is another menu (which will have - * its state class). - */ - private class MenuState { - private Menu menu; - - /* - * Group state is set on items as they are added, allowing an item to - * override its group state. (As opposed to set on items at the group end tag.) - */ - private int groupId; - private int groupCategory; - private int groupOrder; - private int groupCheckable; - private boolean groupVisible; - private boolean groupEnabled; - - private boolean itemAdded; - private int itemId; - private int itemCategoryOrder; - private CharSequence itemTitle; - private CharSequence itemTitleCondensed; - private int itemIconResId; - private char itemAlphabeticShortcut; - private char itemNumericShortcut; - /** - * Sync to attrs.xml enum: - * - 0: none - * - 1: all - * - 2: exclusive - */ - private int itemCheckable; - private boolean itemChecked; - private boolean itemVisible; - private boolean itemEnabled; - - /** - * Sync to attrs.xml enum, values in MenuItem: - * - 0: never - * - 1: ifRoom - * - 2: always - * - -1: Safe sentinel for "no value". - */ - private int itemShowAsAction; - - private int itemActionViewLayout; - private String itemActionViewClassName; - private String itemActionProviderClassName; - - private String itemListenerMethodName; - - private ActionProvider itemActionProvider; - - private static final int defaultGroupId = NO_ID; - private static final int defaultItemId = NO_ID; - private static final int defaultItemCategory = 0; - private static final int defaultItemOrder = 0; - private static final int defaultItemCheckable = 0; - private static final boolean defaultItemChecked = false; - private static final boolean defaultItemVisible = true; - private static final boolean defaultItemEnabled = true; - - public MenuState(final Menu menu) { - this.menu = menu; - - resetGroup(); - } - - public void resetGroup() { - groupId = defaultGroupId; - groupCategory = defaultItemCategory; - groupOrder = defaultItemOrder; - groupCheckable = defaultItemCheckable; - groupVisible = defaultItemVisible; - groupEnabled = defaultItemEnabled; - } - - /** - * Called when the parser is pointing to a group tag. - */ - public void readGroup(AttributeSet attrs) { - TypedArray a = mContext.obtainStyledAttributes(attrs, - R.styleable.SherlockMenuGroup); - - groupId = a.getResourceId(R.styleable.SherlockMenuGroup_android_id, defaultGroupId); - groupCategory = a.getInt(R.styleable.SherlockMenuGroup_android_menuCategory, defaultItemCategory); - groupOrder = a.getInt(R.styleable.SherlockMenuGroup_android_orderInCategory, defaultItemOrder); - groupCheckable = a.getInt(R.styleable.SherlockMenuGroup_android_checkableBehavior, defaultItemCheckable); - groupVisible = a.getBoolean(R.styleable.SherlockMenuGroup_android_visible, defaultItemVisible); - groupEnabled = a.getBoolean(R.styleable.SherlockMenuGroup_android_enabled, defaultItemEnabled); - - a.recycle(); - } - - /** - * Called when the parser is pointing to an item tag. - */ - public void readItem(AttributeSet attrs) { - TypedArray a = mContext.obtainStyledAttributes(attrs, - R.styleable.SherlockMenuItem); - - // Inherit attributes from the group as default value - itemId = a.getResourceId(R.styleable.SherlockMenuItem_android_id, defaultItemId); - final int category = a.getInt(R.styleable.SherlockMenuItem_android_menuCategory, groupCategory); - final int order = a.getInt(R.styleable.SherlockMenuItem_android_orderInCategory, groupOrder); - itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK); - itemTitle = a.getText(R.styleable.SherlockMenuItem_android_title); - itemTitleCondensed = a.getText(R.styleable.SherlockMenuItem_android_titleCondensed); - itemIconResId = a.getResourceId(R.styleable.SherlockMenuItem_android_icon, 0); - itemAlphabeticShortcut = - getShortcut(a.getString(R.styleable.SherlockMenuItem_android_alphabeticShortcut)); - itemNumericShortcut = - getShortcut(a.getString(R.styleable.SherlockMenuItem_android_numericShortcut)); - if (a.hasValue(R.styleable.SherlockMenuItem_android_checkable)) { - // Item has attribute checkable, use it - itemCheckable = a.getBoolean(R.styleable.SherlockMenuItem_android_checkable, false) ? 1 : 0; - } else { - // Item does not have attribute, use the group's (group can have one more state - // for checkable that represents the exclusive checkable) - itemCheckable = groupCheckable; - } - - itemChecked = a.getBoolean(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked); - itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible); - itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled); - - TypedValue value = new TypedValue(); - a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value); - itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1; - - itemListenerMethodName = a.getString(R.styleable.SherlockMenuItem_android_onClick); - itemActionViewLayout = a.getResourceId(R.styleable.SherlockMenuItem_android_actionLayout, 0); - itemActionViewClassName = a.getString(R.styleable.SherlockMenuItem_android_actionViewClass); - itemActionProviderClassName = a.getString(R.styleable.SherlockMenuItem_android_actionProviderClass); - - final boolean hasActionProvider = itemActionProviderClassName != null; - if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) { - itemActionProvider = newInstance(itemActionProviderClassName, - ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE, - mActionProviderConstructorArguments); - } else { - if (hasActionProvider) { - Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'." - + " Action view already specified."); - } - itemActionProvider = null; - } - - a.recycle(); - - itemAdded = false; - } - - private char getShortcut(String shortcutString) { - if (shortcutString == null) { - return 0; - } else { - return shortcutString.charAt(0); - } - } - - private void setItem(MenuItem item) { - item.setChecked(itemChecked) - .setVisible(itemVisible) - .setEnabled(itemEnabled) - .setCheckable(itemCheckable >= 1) - .setTitleCondensed(itemTitleCondensed) - .setIcon(itemIconResId) - .setAlphabeticShortcut(itemAlphabeticShortcut) - .setNumericShortcut(itemNumericShortcut); - - if (itemShowAsAction >= 0) { - item.setShowAsAction(itemShowAsAction); - } - - if (itemListenerMethodName != null) { - if (mContext.isRestricted()) { - throw new IllegalStateException("The android:onClick attribute cannot " - + "be used within a restricted context"); - } - item.setOnMenuItemClickListener( - new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName)); - } - - if (itemCheckable >= 2) { - if (item instanceof MenuItemImpl) { - MenuItemImpl impl = (MenuItemImpl) item; - impl.setExclusiveCheckable(true); - } else { - menu.setGroupCheckable(groupId, true, true); - } - } - - boolean actionViewSpecified = false; - if (itemActionViewClassName != null) { - View actionView = (View) newInstance(itemActionViewClassName, - ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments); - item.setActionView(actionView); - actionViewSpecified = true; - } - if (itemActionViewLayout > 0) { - if (!actionViewSpecified) { - item.setActionView(itemActionViewLayout); - actionViewSpecified = true; - } else { - Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'." - + " Action view already specified."); - } - } - if (itemActionProvider != null) { - item.setActionProvider(itemActionProvider); - } - } - - public void addItem() { - itemAdded = true; - setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle)); - } - - public SubMenu addSubMenuItem() { - itemAdded = true; - SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle); - setItem(subMenu.getItem()); - return subMenu; - } - - public boolean hasAddedItem() { - return itemAdded; - } - - @SuppressWarnings("unchecked") - private T newInstance(String className, Class[] constructorSignature, - Object[] arguments) { - try { - Class clazz = mContext.getClassLoader().loadClass(className); - Constructor constructor = clazz.getConstructor(constructorSignature); - return (T) constructor.newInstance(arguments); - } catch (Exception e) { - Log.w(LOG_TAG, "Cannot instantiate class: " + className, e); - } - return null; - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java deleted file mode 100644 index 7fc3aa43..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java +++ /dev/null @@ -1,598 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.view; - -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.View; - -/** - * Interface for direct access to a previously created menu item. - *

- * An Item is returned by calling one of the {@link android.view.Menu#add} - * methods. - *

- * For a feature set of specific menu types, see {@link Menu}. - * - *

- *

Developer Guides

- *

For information about creating menus, read the - * Menus developer guide.

- *
- */ -public interface MenuItem { - /* - * These should be kept in sync with attrs.xml enum constants for showAsAction - */ - /** Never show this item as a button in an Action Bar. */ - public static final int SHOW_AS_ACTION_NEVER = android.view.MenuItem.SHOW_AS_ACTION_NEVER; - /** Show this item as a button in an Action Bar if the system decides there is room for it. */ - public static final int SHOW_AS_ACTION_IF_ROOM = android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM; - /** - * Always show this item as a button in an Action Bar. - * Use sparingly! If too many items are set to always show in the Action Bar it can - * crowd the Action Bar and degrade the user experience on devices with smaller screens. - * A good rule of thumb is to have no more than 2 items set to always show at a time. - */ - public static final int SHOW_AS_ACTION_ALWAYS = android.view.MenuItem.SHOW_AS_ACTION_ALWAYS; - - /** - * When this item is in the action bar, always show it with a text label even if - * it also has an icon specified. - */ - public static final int SHOW_AS_ACTION_WITH_TEXT = android.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT; - - /** - * This item's action view collapses to a normal menu item. - * When expanded, the action view temporarily takes over - * a larger segment of its container. - */ - public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW; - - /** - * Interface definition for a callback to be invoked when a menu item is - * clicked. - * - * @see Activity#onContextItemSelected(MenuItem) - * @see Activity#onOptionsItemSelected(MenuItem) - */ - public interface OnMenuItemClickListener { - /** - * Called when a menu item has been invoked. This is the first code - * that is executed; if it returns true, no other callbacks will be - * executed. - * - * @param item The menu item that was invoked. - * - * @return Return true to consume this click and prevent others from - * executing. - */ - public boolean onMenuItemClick(MenuItem item); - } - - /** - * Interface definition for a callback to be invoked when a menu item - * marked with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} is - * expanded or collapsed. - * - * @see MenuItem#expandActionView() - * @see MenuItem#collapseActionView() - * @see MenuItem#setShowAsActionFlags(int) - */ - public interface OnActionExpandListener { - /** - * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} - * is expanded. - * @param item Item that was expanded - * @return true if the item should expand, false if expansion should be suppressed. - */ - public boolean onMenuItemActionExpand(MenuItem item); - - /** - * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} - * is collapsed. - * @param item Item that was collapsed - * @return true if the item should collapse, false if collapsing should be suppressed. - */ - public boolean onMenuItemActionCollapse(MenuItem item); - } - - /** - * Return the identifier for this menu item. The identifier can not - * be changed after the menu is created. - * - * @return The menu item's identifier. - */ - public int getItemId(); - - /** - * Return the group identifier that this menu item is part of. The group - * identifier can not be changed after the menu is created. - * - * @return The menu item's group identifier. - */ - public int getGroupId(); - - /** - * Return the category and order within the category of this item. This - * item will be shown before all items (within its category) that have - * order greater than this value. - *

- * An order integer contains the item's category (the upper bits of the - * integer; set by or/add the category with the order within the - * category) and the ordering of the item within that category (the - * lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM}, - * {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE}, - * {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list. - * - * @return The order of this item. - */ - public int getOrder(); - - /** - * Change the title associated with this item. - * - * @param title The new text to be displayed. - * @return This Item so additional setters can be called. - */ - public MenuItem setTitle(CharSequence title); - - /** - * Change the title associated with this item. - *

- * Some menu types do not sufficient space to show the full title, and - * instead a condensed title is preferred. See {@link Menu} for more - * information. - * - * @param title The resource id of the new text to be displayed. - * @return This Item so additional setters can be called. - * @see #setTitleCondensed(CharSequence) - */ - - public MenuItem setTitle(int title); - - /** - * Retrieve the current title of the item. - * - * @return The title. - */ - public CharSequence getTitle(); - - /** - * Change the condensed title associated with this item. The condensed - * title is used in situations where the normal title may be too long to - * be displayed. - * - * @param title The new text to be displayed as the condensed title. - * @return This Item so additional setters can be called. - */ - public MenuItem setTitleCondensed(CharSequence title); - - /** - * Retrieve the current condensed title of the item. If a condensed - * title was never set, it will return the normal title. - * - * @return The condensed title, if it exists. - * Otherwise the normal title. - */ - public CharSequence getTitleCondensed(); - - /** - * Change the icon associated with this item. This icon will not always be - * shown, so the title should be sufficient in describing this item. See - * {@link Menu} for the menu types that support icons. - * - * @param icon The new icon (as a Drawable) to be displayed. - * @return This Item so additional setters can be called. - */ - public MenuItem setIcon(Drawable icon); - - /** - * Change the icon associated with this item. This icon will not always be - * shown, so the title should be sufficient in describing this item. See - * {@link Menu} for the menu types that support icons. - *

- * This method will set the resource ID of the icon which will be used to - * lazily get the Drawable when this item is being shown. - * - * @param iconRes The new icon (as a resource ID) to be displayed. - * @return This Item so additional setters can be called. - */ - public MenuItem setIcon(int iconRes); - - /** - * Returns the icon for this item as a Drawable (getting it from resources if it hasn't been - * loaded before). - * - * @return The icon as a Drawable. - */ - public Drawable getIcon(); - - /** - * Change the Intent associated with this item. By default there is no - * Intent associated with a menu item. If you set one, and nothing - * else handles the item, then the default behavior will be to call - * {@link android.content.Context#startActivity} with the given Intent. - * - *

Note that setIntent() can not be used with the versions of - * {@link Menu#add} that take a Runnable, because {@link Runnable#run} - * does not return a value so there is no way to tell if it handled the - * item. In this case it is assumed that the Runnable always handles - * the item, and the intent will never be started. - * - * @see #getIntent - * @param intent The Intent to associated with the item. This Intent - * object is not copied, so be careful not to - * modify it later. - * @return This Item so additional setters can be called. - */ - public MenuItem setIntent(Intent intent); - - /** - * Return the Intent associated with this item. This returns a - * reference to the Intent which you can change as desired to modify - * what the Item is holding. - * - * @see #setIntent - * @return Returns the last value supplied to {@link #setIntent}, or - * null. - */ - public Intent getIntent(); - - /** - * Change both the numeric and alphabetic shortcut associated with this - * item. Note that the shortcut will be triggered when the key that - * generates the given character is pressed alone or along with with the alt - * key. Also note that case is not significant and that alphabetic shortcut - * characters will be displayed in lower case. - *

- * See {@link Menu} for the menu types that support shortcuts. - * - * @param numericChar The numeric shortcut key. This is the shortcut when - * using a numeric (e.g., 12-key) keyboard. - * @param alphaChar The alphabetic shortcut key. This is the shortcut when - * using a keyboard with alphabetic keys. - * @return This Item so additional setters can be called. - */ - public MenuItem setShortcut(char numericChar, char alphaChar); - - /** - * Change the numeric shortcut associated with this item. - *

- * See {@link Menu} for the menu types that support shortcuts. - * - * @param numericChar The numeric shortcut key. This is the shortcut when - * using a 12-key (numeric) keyboard. - * @return This Item so additional setters can be called. - */ - public MenuItem setNumericShortcut(char numericChar); - - /** - * Return the char for this menu item's numeric (12-key) shortcut. - * - * @return Numeric character to use as a shortcut. - */ - public char getNumericShortcut(); - - /** - * Change the alphabetic shortcut associated with this item. The shortcut - * will be triggered when the key that generates the given character is - * pressed alone or along with with the alt key. Case is not significant and - * shortcut characters will be displayed in lower case. Note that menu items - * with the characters '\b' or '\n' as shortcuts will get triggered by the - * Delete key or Carriage Return key, respectively. - *

- * See {@link Menu} for the menu types that support shortcuts. - * - * @param alphaChar The alphabetic shortcut key. This is the shortcut when - * using a keyboard with alphabetic keys. - * @return This Item so additional setters can be called. - */ - public MenuItem setAlphabeticShortcut(char alphaChar); - - /** - * Return the char for this menu item's alphabetic shortcut. - * - * @return Alphabetic character to use as a shortcut. - */ - public char getAlphabeticShortcut(); - - /** - * Control whether this item can display a check mark. Setting this does - * not actually display a check mark (see {@link #setChecked} for that); - * rather, it ensures there is room in the item in which to display a - * check mark. - *

- * See {@link Menu} for the menu types that support check marks. - * - * @param checkable Set to true to allow a check mark, false to - * disallow. The default is false. - * @see #setChecked - * @see #isCheckable - * @see Menu#setGroupCheckable - * @return This Item so additional setters can be called. - */ - public MenuItem setCheckable(boolean checkable); - - /** - * Return whether the item can currently display a check mark. - * - * @return If a check mark can be displayed, returns true. - * - * @see #setCheckable - */ - public boolean isCheckable(); - - /** - * Control whether this item is shown with a check mark. Note that you - * must first have enabled checking with {@link #setCheckable} or else - * the check mark will not appear. If this item is a member of a group that contains - * mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)}, - * the other items in the group will be unchecked. - *

- * See {@link Menu} for the menu types that support check marks. - * - * @see #setCheckable - * @see #isChecked - * @see Menu#setGroupCheckable - * @param checked Set to true to display a check mark, false to hide - * it. The default value is false. - * @return This Item so additional setters can be called. - */ - public MenuItem setChecked(boolean checked); - - /** - * Return whether the item is currently displaying a check mark. - * - * @return If a check mark is displayed, returns true. - * - * @see #setChecked - */ - public boolean isChecked(); - - /** - * Sets the visibility of the menu item. Even if a menu item is not visible, - * it may still be invoked via its shortcut (to completely disable an item, - * set it to invisible and {@link #setEnabled(boolean) disabled}). - * - * @param visible If true then the item will be visible; if false it is - * hidden. - * @return This Item so additional setters can be called. - */ - public MenuItem setVisible(boolean visible); - - /** - * Return the visibility of the menu item. - * - * @return If true the item is visible; else it is hidden. - */ - public boolean isVisible(); - - /** - * Sets whether the menu item is enabled. Disabling a menu item will not - * allow it to be invoked via its shortcut. The menu item will still be - * visible. - * - * @param enabled If true then the item will be invokable; if false it is - * won't be invokable. - * @return This Item so additional setters can be called. - */ - public MenuItem setEnabled(boolean enabled); - - /** - * Return the enabled state of the menu item. - * - * @return If true the item is enabled and hence invokable; else it is not. - */ - public boolean isEnabled(); - - /** - * Check whether this item has an associated sub-menu. I.e. it is a - * sub-menu of another menu. - * - * @return If true this item has a menu; else it is a - * normal item. - */ - public boolean hasSubMenu(); - - /** - * Get the sub-menu to be invoked when this item is selected, if it has - * one. See {@link #hasSubMenu()}. - * - * @return The associated menu if there is one, else null - */ - public SubMenu getSubMenu(); - - /** - * Set a custom listener for invocation of this menu item. In most - * situations, it is more efficient and easier to use - * {@link Activity#onOptionsItemSelected(MenuItem)} or - * {@link Activity#onContextItemSelected(MenuItem)}. - * - * @param menuItemClickListener The object to receive invokations. - * @return This Item so additional setters can be called. - * @see Activity#onOptionsItemSelected(MenuItem) - * @see Activity#onContextItemSelected(MenuItem) - */ - public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener); - - /** - * Gets the extra information linked to this menu item. This extra - * information is set by the View that added this menu item to the - * menu. - * - * @see OnCreateContextMenuListener - * @return The extra information linked to the View that added this - * menu item to the menu. This can be null. - */ - public ContextMenuInfo getMenuInfo(); - - /** - * Sets how this item should display in the presence of an Action Bar. - * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS}, - * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should - * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}. - * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action, - * it should be shown with a text label. - * - * @param actionEnum How the item should display. One of - * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or - * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default. - * - * @see android.app.ActionBar - * @see #setActionView(View) - */ - public void setShowAsAction(int actionEnum); - - /** - * Sets how this item should display in the presence of an Action Bar. - * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS}, - * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should - * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}. - * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action, - * it should be shown with a text label. - * - *

Note: This method differs from {@link #setShowAsAction(int)} only in that it - * returns the current MenuItem instance for call chaining. - * - * @param actionEnum How the item should display. One of - * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or - * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default. - * - * @see android.app.ActionBar - * @see #setActionView(View) - * @return This MenuItem instance for call chaining. - */ - public MenuItem setShowAsActionFlags(int actionEnum); - - /** - * Set an action view for this menu item. An action view will be displayed in place - * of an automatically generated menu item element in the UI when this item is shown - * as an action within a parent. - *

- * Note: Setting an action view overrides the action provider - * set via {@link #setActionProvider(ActionProvider)}. - *

- * - * @param view View to use for presenting this item to the user. - * @return This Item so additional setters can be called. - * - * @see #setShowAsAction(int) - */ - public MenuItem setActionView(View view); - - /** - * Set an action view for this menu item. An action view will be displayed in place - * of an automatically generated menu item element in the UI when this item is shown - * as an action within a parent. - *

- * Note: Setting an action view overrides the action provider - * set via {@link #setActionProvider(ActionProvider)}. - *

- * - * @param resId Layout resource to use for presenting this item to the user. - * @return This Item so additional setters can be called. - * - * @see #setShowAsAction(int) - */ - public MenuItem setActionView(int resId); - - /** - * Returns the currently set action view for this menu item. - * - * @return This item's action view - * - * @see #setActionView(View) - * @see #setShowAsAction(int) - */ - public View getActionView(); - - /** - * Sets the {@link ActionProvider} responsible for creating an action view if - * the item is placed on the action bar. The provider also provides a default - * action invoked if the item is placed in the overflow menu. - *

- * Note: Setting an action provider overrides the action view - * set via {@link #setActionView(int)} or {@link #setActionView(View)}. - *

- * - * @param actionProvider The action provider. - * @return This Item so additional setters can be called. - * - * @see ActionProvider - */ - public MenuItem setActionProvider(ActionProvider actionProvider); - - /** - * Gets the {@link ActionProvider}. - * - * @return The action provider. - * - * @see ActionProvider - * @see #setActionProvider(ActionProvider) - */ - public ActionProvider getActionProvider(); - - /** - * Expand the action view associated with this menu item. - * The menu item must have an action view set, as well as - * the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. - * If a listener has been set using {@link #setOnActionExpandListener(OnActionExpandListener)} - * it will have its {@link OnActionExpandListener#onMenuItemActionExpand(MenuItem)} - * method invoked. The listener may return false from this method to prevent expanding - * the action view. - * - * @return true if the action view was expanded, false otherwise. - */ - public boolean expandActionView(); - - /** - * Collapse the action view associated with this menu item. - * The menu item must have an action view set, as well as the showAsAction flag - * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a listener has been set using - * {@link #setOnActionExpandListener(OnActionExpandListener)} it will have its - * {@link OnActionExpandListener#onMenuItemActionCollapse(MenuItem)} method invoked. - * The listener may return false from this method to prevent collapsing the action view. - * - * @return true if the action view was collapsed, false otherwise. - */ - public boolean collapseActionView(); - - /** - * Returns true if this menu item's action view has been expanded. - * - * @return true if the item's action view is expanded, false otherwise. - * - * @see #expandActionView() - * @see #collapseActionView() - * @see #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW - * @see OnActionExpandListener - */ - public boolean isActionViewExpanded(); - - /** - * Set an {@link OnActionExpandListener} on this menu item to be notified when - * the associated action view is expanded or collapsed. The menu item must - * be configured to expand or collapse its action view using the flag - * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. - * - * @param listener Listener that will respond to expand/collapse events - * @return This menu item instance for call chaining - */ - public MenuItem setOnActionExpandListener(OnActionExpandListener listener); -} \ No newline at end of file diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/SubMenu.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/SubMenu.java deleted file mode 100644 index 397fd1c2..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/SubMenu.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.view; - -import android.graphics.drawable.Drawable; -import android.view.View; - -/** - * Subclass of {@link Menu} for sub menus. - *

- * Sub menus do not support item icons, or nested sub menus. - * - *

- *

Developer Guides

- *

For information about creating menus, read the - * Menus developer guide.

- *
- */ - -public interface SubMenu extends Menu { - /** - * Sets the submenu header's title to the title given in titleRes - * resource identifier. - * - * @param titleRes The string resource identifier used for the title. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setHeaderTitle(int titleRes); - - /** - * Sets the submenu header's title to the title given in title. - * - * @param title The character sequence used for the title. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setHeaderTitle(CharSequence title); - - /** - * Sets the submenu header's icon to the icon given in iconRes - * resource id. - * - * @param iconRes The resource identifier used for the icon. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setHeaderIcon(int iconRes); - - /** - * Sets the submenu header's icon to the icon given in icon - * {@link Drawable}. - * - * @param icon The {@link Drawable} used for the icon. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setHeaderIcon(Drawable icon); - - /** - * Sets the header of the submenu to the {@link View} given in - * view. This replaces the header title and icon (and those - * replace this). - * - * @param view The {@link View} used for the header. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setHeaderView(View view); - - /** - * Clears the header of the submenu. - */ - public void clearHeader(); - - /** - * Change the icon associated with this submenu's item in its parent menu. - * - * @see MenuItem#setIcon(int) - * @param iconRes The new icon (as a resource ID) to be displayed. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setIcon(int iconRes); - - /** - * Change the icon associated with this submenu's item in its parent menu. - * - * @see MenuItem#setIcon(Drawable) - * @param icon The new icon (as a Drawable) to be displayed. - * @return This SubMenu so additional setters can be called. - */ - public SubMenu setIcon(Drawable icon); - - /** - * Gets the {@link MenuItem} that represents this submenu in the parent - * menu. Use this for setting additional item attributes. - * - * @return The {@link MenuItem} that launches the submenu when invoked. - */ - public MenuItem getItem(); -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Window.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Window.java deleted file mode 100644 index a340a429..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Window.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * Copyright (C) 2011 Jake Wharton - * - * 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 com.actionbarsherlock.view; - -import android.content.Context; - -/** - *

Abstract base class for a top-level window look and behavior policy. An - * instance of this class should be used as the top-level view added to the - * window manager. It provides standard UI policies such as a background, title - * area, default key processing, etc.

- * - *

The only existing implementation of this abstract class is - * android.policy.PhoneWindow, which you should instantiate when needing a - * Window. Eventually that class will be refactored and a factory method added - * for creating Window instances without knowing about a particular - * implementation.

- */ -public abstract class Window extends android.view.Window { - public static final long FEATURE_ACTION_BAR = android.view.Window.FEATURE_ACTION_BAR; - public static final long FEATURE_ACTION_BAR_OVERLAY = android.view.Window.FEATURE_ACTION_BAR_OVERLAY; - public static final long FEATURE_ACTION_MODE_OVERLAY = android.view.Window.FEATURE_ACTION_MODE_OVERLAY; - public static final long FEATURE_NO_TITLE = android.view.Window.FEATURE_NO_TITLE; - public static final long FEATURE_PROGRESS = android.view.Window.FEATURE_PROGRESS; - public static final long FEATURE_INDETERMINATE_PROGRESS = android.view.Window.FEATURE_INDETERMINATE_PROGRESS; - - /** - * Create a new instance for a context. - * - * @param context Context. - */ - private Window(Context context) { - super(context); - } - - - public interface Callback { - /** - * Called when a panel's menu item has been selected by the user. - * - * @param featureId The panel that the menu is in. - * @param item The menu item that was selected. - * - * @return boolean Return true to finish processing of selection, or - * false to perform the normal menu handling (calling its - * Runnable or sending a Message to its target Handler). - */ - public boolean onMenuItemSelected(int featureId, MenuItem item); - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java deleted file mode 100644 index 37920747..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java +++ /dev/null @@ -1,1131 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.widget; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ResolveInfo; -import android.database.DataSetObservable; -import android.os.Handler; -import android.text.TextUtils; -import android.util.Log; -import android.util.Xml; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; -import org.xmlpull.v1.XmlSerializer; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Executor; - -/** - *

- * This class represents a data model for choosing a component for handing a - * given {@link Intent}. The model is responsible for querying the system for - * activities that can handle the given intent and order found activities - * based on historical data of previous choices. The historical data is stored - * in an application private file. If a client does not want to have persistent - * choice history the file can be omitted, thus the activities will be ordered - * based on historical usage for the current session. - *

- *

- * For each backing history file there is a singleton instance of this class. Thus, - * several clients that specify the same history file will share the same model. Note - * that if multiple clients are sharing the same model they should implement semantically - * equivalent functionality since setting the model intent will change the found - * activities and they may be inconsistent with the functionality of some of the clients. - * For example, choosing a share activity can be implemented by a single backing - * model and two different views for performing the selection. If however, one of the - * views is used for sharing but the other for importing, for example, then each - * view should be backed by a separate model. - *

- *

- * The way clients interact with this class is as follows: - *

- *

- *

- * 
- *  // Get a model and set it to a couple of clients with semantically similar function.
- *  ActivityChooserModel dataModel =
- *      ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
- *
- *  ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
- *  modelClient1.setActivityChooserModel(dataModel);
- *
- *  ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
- *  modelClient2.setActivityChooserModel(dataModel);
- *
- *  // Set an intent to choose a an activity for.
- *  dataModel.setIntent(intent);
- * 
- * 
- * 

- *

- * Note: This class is thread safe. - *

- * - * @hide - */ -class ActivityChooserModel extends DataSetObservable { - - /** - * Client that utilizes an {@link ActivityChooserModel}. - */ - public interface ActivityChooserModelClient { - - /** - * Sets the {@link ActivityChooserModel}. - * - * @param dataModel The model. - */ - public void setActivityChooserModel(ActivityChooserModel dataModel); - } - - /** - * Defines a sorter that is responsible for sorting the activities - * based on the provided historical choices and an intent. - */ - public interface ActivitySorter { - - /** - * Sorts the activities in descending order of relevance - * based on previous history and an intent. - * - * @param intent The {@link Intent}. - * @param activities Activities to be sorted. - * @param historicalRecords Historical records. - */ - // This cannot be done by a simple comparator since an Activity weight - // is computed from history. Note that Activity implements Comparable. - public void sort(Intent intent, List activities, - List historicalRecords); - } - - /** - * Listener for choosing an activity. - */ - public interface OnChooseActivityListener { - - /** - * Called when an activity has been chosen. The client can decide whether - * an activity can be chosen and if so the caller of - * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent} - * for launching it. - *

- * Note: Modifying the intent is not permitted and - * any changes to the latter will be ignored. - *

- * - * @param host The listener's host model. - * @param intent The intent for launching the chosen activity. - * @return Whether the intent is handled and should not be delivered to clients. - * - * @see ActivityChooserModel#chooseActivity(int) - */ - public boolean onChooseActivity(ActivityChooserModel host, Intent intent); - } - - /** - * Flag for selecting debug mode. - */ - private static final boolean DEBUG = false; - - /** - * Tag used for logging. - */ - private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName(); - - /** - * The root tag in the history file. - */ - private static final String TAG_HISTORICAL_RECORDS = "historical-records"; - - /** - * The tag for a record in the history file. - */ - private static final String TAG_HISTORICAL_RECORD = "historical-record"; - - /** - * Attribute for the activity. - */ - private static final String ATTRIBUTE_ACTIVITY = "activity"; - - /** - * Attribute for the choice time. - */ - private static final String ATTRIBUTE_TIME = "time"; - - /** - * Attribute for the choice weight. - */ - private static final String ATTRIBUTE_WEIGHT = "weight"; - - /** - * The default name of the choice history file. - */ - public static final String DEFAULT_HISTORY_FILE_NAME = - "activity_choser_model_history.xml"; - - /** - * The default maximal length of the choice history. - */ - public static final int DEFAULT_HISTORY_MAX_LENGTH = 50; - - /** - * The amount with which to inflate a chosen activity when set as default. - */ - private static final int DEFAULT_ACTIVITY_INFLATION = 5; - - /** - * Default weight for a choice record. - */ - private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f; - - /** - * The extension of the history file. - */ - private static final String HISTORY_FILE_EXTENSION = ".xml"; - - /** - * An invalid item index. - */ - private static final int INVALID_INDEX = -1; - - /** - * Lock to guard the model registry. - */ - private static final Object sRegistryLock = new Object(); - - /** - * This the registry for data models. - */ - private static final Map sDataModelRegistry = - new HashMap(); - - /** - * Lock for synchronizing on this instance. - */ - private final Object mInstanceLock = new Object(); - - /** - * List of activities that can handle the current intent. - */ - private final List mActivites = new ArrayList(); - - /** - * List with historical choice records. - */ - private final List mHistoricalRecords = new ArrayList(); - - /** - * Context for accessing resources. - */ - private final Context mContext; - - /** - * The name of the history file that backs this model. - */ - private final String mHistoryFileName; - - /** - * The intent for which a activity is being chosen. - */ - private Intent mIntent; - - /** - * The sorter for ordering activities based on intent and past choices. - */ - private ActivitySorter mActivitySorter = new DefaultSorter(); - - /** - * The maximal length of the choice history. - */ - private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH; - - /** - * Flag whether choice history can be read. In general many clients can - * share the same data model and {@link #readHistoricalData()} may be called - * by arbitrary of them any number of times. Therefore, this class guarantees - * that the very first read succeeds and subsequent reads can be performed - * only after a call to {@link #persistHistoricalData()} followed by change - * of the share records. - */ - private boolean mCanReadHistoricalData = true; - - /** - * Flag whether the choice history was read. This is used to enforce that - * before calling {@link #persistHistoricalData()} a call to - * {@link #persistHistoricalData()} has been made. This aims to avoid a - * scenario in which a choice history file exits, it is not read yet and - * it is overwritten. Note that always all historical records are read in - * full and the file is rewritten. This is necessary since we need to - * purge old records that are outside of the sliding window of past choices. - */ - private boolean mReadShareHistoryCalled = false; - - /** - * Flag whether the choice records have changed. In general many clients can - * share the same data model and {@link #persistHistoricalData()} may be called - * by arbitrary of them any number of times. Therefore, this class guarantees - * that choice history will be persisted only if it has changed. - */ - private boolean mHistoricalRecordsChanged = true; - - /** - * Hander for scheduling work on client tread. - */ - private final Handler mHandler = new Handler(); - - /** - * Policy for controlling how the model handles chosen activities. - */ - private OnChooseActivityListener mActivityChoserModelPolicy; - - /** - * Gets the data model backed by the contents of the provided file with historical data. - * Note that only one data model is backed by a given file, thus multiple calls with - * the same file name will return the same model instance. If no such instance is present - * it is created. - *

- * Note: To use the default historical data file clients should explicitly - * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice - * history is desired clients should pass null for the file name. In such - * case a new model is returned for each invocation. - *

- * - *

- * Always use difference historical data files for semantically different actions. - * For example, sharing is different from importing. - *

- * - * @param context Context for loading resources. - * @param historyFileName File name with choice history, null - * if the model should not be backed by a file. In this case the activities - * will be ordered only by data from the current session. - * - * @return The model. - */ - public static ActivityChooserModel get(Context context, String historyFileName) { - synchronized (sRegistryLock) { - ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName); - if (dataModel == null) { - dataModel = new ActivityChooserModel(context, historyFileName); - sDataModelRegistry.put(historyFileName, dataModel); - } - dataModel.readHistoricalData(); - return dataModel; - } - } - - /** - * Creates a new instance. - * - * @param context Context for loading resources. - * @param historyFileName The history XML file. - */ - private ActivityChooserModel(Context context, String historyFileName) { - mContext = context.getApplicationContext(); - if (!TextUtils.isEmpty(historyFileName) - && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) { - mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION; - } else { - mHistoryFileName = historyFileName; - } - } - - /** - * Sets an intent for which to choose a activity. - *

- * Note: Clients must set only semantically similar - * intents for each data model. - *

- * - * @param intent The intent. - */ - public void setIntent(Intent intent) { - synchronized (mInstanceLock) { - if (mIntent == intent) { - return; - } - mIntent = intent; - loadActivitiesLocked(); - } - } - - /** - * Gets the intent for which a activity is being chosen. - * - * @return The intent. - */ - public Intent getIntent() { - synchronized (mInstanceLock) { - return mIntent; - } - } - - /** - * Gets the number of activities that can handle the intent. - * - * @return The activity count. - * - * @see #setIntent(Intent) - */ - public int getActivityCount() { - synchronized (mInstanceLock) { - return mActivites.size(); - } - } - - /** - * Gets an activity at a given index. - * - * @return The activity. - * - * @see ActivityResolveInfo - * @see #setIntent(Intent) - */ - public ResolveInfo getActivity(int index) { - synchronized (mInstanceLock) { - return mActivites.get(index).resolveInfo; - } - } - - /** - * Gets the index of a the given activity. - * - * @param activity The activity index. - * - * @return The index if found, -1 otherwise. - */ - public int getActivityIndex(ResolveInfo activity) { - List activities = mActivites; - final int activityCount = activities.size(); - for (int i = 0; i < activityCount; i++) { - ActivityResolveInfo currentActivity = activities.get(i); - if (currentActivity.resolveInfo == activity) { - return i; - } - } - return INVALID_INDEX; - } - - /** - * Chooses a activity to handle the current intent. This will result in - * adding a historical record for that action and construct intent with - * its component name set such that it can be immediately started by the - * client. - *

- * Note: By calling this method the client guarantees - * that the returned intent will be started. This intent is returned to - * the client solely to let additional customization before the start. - *

- * - * @return An {@link Intent} for launching the activity or null if the - * policy has consumed the intent. - * - * @see HistoricalRecord - * @see OnChooseActivityListener - */ - public Intent chooseActivity(int index) { - ActivityResolveInfo chosenActivity = mActivites.get(index); - - ComponentName chosenName = new ComponentName( - chosenActivity.resolveInfo.activityInfo.packageName, - chosenActivity.resolveInfo.activityInfo.name); - - Intent choiceIntent = new Intent(mIntent); - choiceIntent.setComponent(chosenName); - - if (mActivityChoserModelPolicy != null) { - // Do not allow the policy to change the intent. - Intent choiceIntentCopy = new Intent(choiceIntent); - final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this, - choiceIntentCopy); - if (handled) { - return null; - } - } - - HistoricalRecord historicalRecord = new HistoricalRecord(chosenName, - System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT); - addHisoricalRecord(historicalRecord); - - return choiceIntent; - } - - /** - * Sets the listener for choosing an activity. - * - * @param listener The listener. - */ - public void setOnChooseActivityListener(OnChooseActivityListener listener) { - mActivityChoserModelPolicy = listener; - } - - /** - * Gets the default activity, The default activity is defined as the one - * with highest rank i.e. the first one in the list of activities that can - * handle the intent. - * - * @return The default activity, null id not activities. - * - * @see #getActivity(int) - */ - public ResolveInfo getDefaultActivity() { - synchronized (mInstanceLock) { - if (!mActivites.isEmpty()) { - return mActivites.get(0).resolveInfo; - } - } - return null; - } - - /** - * Sets the default activity. The default activity is set by adding a - * historical record with weight high enough that this activity will - * become the highest ranked. Such a strategy guarantees that the default - * will eventually change if not used. Also the weight of the record for - * setting a default is inflated with a constant amount to guarantee that - * it will stay as default for awhile. - * - * @param index The index of the activity to set as default. - */ - public void setDefaultActivity(int index) { - ActivityResolveInfo newDefaultActivity = mActivites.get(index); - ActivityResolveInfo oldDefaultActivity = mActivites.get(0); - - final float weight; - if (oldDefaultActivity != null) { - // Add a record with weight enough to boost the chosen at the top. - weight = oldDefaultActivity.weight - newDefaultActivity.weight - + DEFAULT_ACTIVITY_INFLATION; - } else { - weight = DEFAULT_HISTORICAL_RECORD_WEIGHT; - } - - ComponentName defaultName = new ComponentName( - newDefaultActivity.resolveInfo.activityInfo.packageName, - newDefaultActivity.resolveInfo.activityInfo.name); - HistoricalRecord historicalRecord = new HistoricalRecord(defaultName, - System.currentTimeMillis(), weight); - addHisoricalRecord(historicalRecord); - } - - /** - * Reads the history data from the backing file if the latter - * was provided. Calling this method more than once before a call - * to {@link #persistHistoricalData()} has been made has no effect. - *

- * Note: Historical data is read asynchronously and - * as soon as the reading is completed any registered - * {@link DataSetObserver}s will be notified. Also no historical - * data is read until this method is invoked. - *

- */ - private void readHistoricalData() { - synchronized (mInstanceLock) { - if (!mCanReadHistoricalData || !mHistoricalRecordsChanged) { - return; - } - mCanReadHistoricalData = false; - mReadShareHistoryCalled = true; - if (!TextUtils.isEmpty(mHistoryFileName)) { - /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryLoader()); - } - } - } - - private static final SerialExecutor SERIAL_EXECUTOR = new SerialExecutor(); - - private static class SerialExecutor implements Executor { - final LinkedList mTasks = new LinkedList(); - Runnable mActive; - - public synchronized void execute(final Runnable r) { - mTasks.offer(new Runnable() { - public void run() { - try { - r.run(); - } finally { - scheduleNext(); - } - } - }); - if (mActive == null) { - scheduleNext(); - } - } - - protected synchronized void scheduleNext() { - if ((mActive = mTasks.poll()) != null) { - mActive.run(); - } - } - } - - /** - * Persists the history data to the backing file if the latter - * was provided. Calling this method before a call to {@link #readHistoricalData()} - * throws an exception. Calling this method more than one without choosing an - * activity has not effect. - * - * @throws IllegalStateException If this method is called before a call to - * {@link #readHistoricalData()}. - */ - private void persistHistoricalData() { - synchronized (mInstanceLock) { - if (!mReadShareHistoryCalled) { - throw new IllegalStateException("No preceding call to #readHistoricalData"); - } - if (!mHistoricalRecordsChanged) { - return; - } - mHistoricalRecordsChanged = false; - mCanReadHistoricalData = true; - if (!TextUtils.isEmpty(mHistoryFileName)) { - /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryPersister()); - } - } - } - - /** - * Sets the sorter for ordering activities based on historical data and an intent. - * - * @param activitySorter The sorter. - * - * @see ActivitySorter - */ - public void setActivitySorter(ActivitySorter activitySorter) { - synchronized (mInstanceLock) { - if (mActivitySorter == activitySorter) { - return; - } - mActivitySorter = activitySorter; - sortActivities(); - } - } - - /** - * Sorts the activities based on history and an intent. If - * a sorter is not specified this a default implementation is used. - * - * @see #setActivitySorter(ActivitySorter) - */ - private void sortActivities() { - synchronized (mInstanceLock) { - if (mActivitySorter != null && !mActivites.isEmpty()) { - mActivitySorter.sort(mIntent, mActivites, - Collections.unmodifiableList(mHistoricalRecords)); - notifyChanged(); - } - } - } - - /** - * Sets the maximal size of the historical data. Defaults to - * {@link #DEFAULT_HISTORY_MAX_LENGTH} - *

- * Note: Setting this property will immediately - * enforce the specified max history size by dropping enough old - * historical records to enforce the desired size. Thus, any - * records that exceed the history size will be discarded and - * irreversibly lost. - *

- * - * @param historyMaxSize The max history size. - */ - public void setHistoryMaxSize(int historyMaxSize) { - synchronized (mInstanceLock) { - if (mHistoryMaxSize == historyMaxSize) { - return; - } - mHistoryMaxSize = historyMaxSize; - pruneExcessiveHistoricalRecordsLocked(); - sortActivities(); - } - } - - /** - * Gets the history max size. - * - * @return The history max size. - */ - public int getHistoryMaxSize() { - synchronized (mInstanceLock) { - return mHistoryMaxSize; - } - } - - /** - * Gets the history size. - * - * @return The history size. - */ - public int getHistorySize() { - synchronized (mInstanceLock) { - return mHistoricalRecords.size(); - } - } - - /** - * Adds a historical record. - * - * @param historicalRecord The record to add. - * @return True if the record was added. - */ - private boolean addHisoricalRecord(HistoricalRecord historicalRecord) { - synchronized (mInstanceLock) { - final boolean added = mHistoricalRecords.add(historicalRecord); - if (added) { - mHistoricalRecordsChanged = true; - pruneExcessiveHistoricalRecordsLocked(); - persistHistoricalData(); - sortActivities(); - } - return added; - } - } - - /** - * Prunes older excessive records to guarantee {@link #mHistoryMaxSize}. - */ - private void pruneExcessiveHistoricalRecordsLocked() { - List choiceRecords = mHistoricalRecords; - final int pruneCount = choiceRecords.size() - mHistoryMaxSize; - if (pruneCount <= 0) { - return; - } - mHistoricalRecordsChanged = true; - for (int i = 0; i < pruneCount; i++) { - HistoricalRecord prunedRecord = choiceRecords.remove(0); - if (DEBUG) { - Log.i(LOG_TAG, "Pruned: " + prunedRecord); - } - } - } - - /** - * Loads the activities. - */ - private void loadActivitiesLocked() { - mActivites.clear(); - if (mIntent != null) { - List resolveInfos = - mContext.getPackageManager().queryIntentActivities(mIntent, 0); - final int resolveInfoCount = resolveInfos.size(); - for (int i = 0; i < resolveInfoCount; i++) { - ResolveInfo resolveInfo = resolveInfos.get(i); - mActivites.add(new ActivityResolveInfo(resolveInfo)); - } - sortActivities(); - } else { - notifyChanged(); - } - } - - /** - * Represents a record in the history. - */ - public final static class HistoricalRecord { - - /** - * The activity name. - */ - public final ComponentName activity; - - /** - * The choice time. - */ - public final long time; - - /** - * The record weight. - */ - public final float weight; - - /** - * Creates a new instance. - * - * @param activityName The activity component name flattened to string. - * @param time The time the activity was chosen. - * @param weight The weight of the record. - */ - public HistoricalRecord(String activityName, long time, float weight) { - this(ComponentName.unflattenFromString(activityName), time, weight); - } - - /** - * Creates a new instance. - * - * @param activityName The activity name. - * @param time The time the activity was chosen. - * @param weight The weight of the record. - */ - public HistoricalRecord(ComponentName activityName, long time, float weight) { - this.activity = activityName; - this.time = time; - this.weight = weight; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((activity == null) ? 0 : activity.hashCode()); - result = prime * result + (int) (time ^ (time >>> 32)); - result = prime * result + Float.floatToIntBits(weight); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - HistoricalRecord other = (HistoricalRecord) obj; - if (activity == null) { - if (other.activity != null) { - return false; - } - } else if (!activity.equals(other.activity)) { - return false; - } - if (time != other.time) { - return false; - } - if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("["); - builder.append("; activity:").append(activity); - builder.append("; time:").append(time); - builder.append("; weight:").append(new BigDecimal(weight)); - builder.append("]"); - return builder.toString(); - } - } - - /** - * Represents an activity. - */ - public final class ActivityResolveInfo implements Comparable { - - /** - * The {@link ResolveInfo} of the activity. - */ - public final ResolveInfo resolveInfo; - - /** - * Weight of the activity. Useful for sorting. - */ - public float weight; - - /** - * Creates a new instance. - * - * @param resolveInfo activity {@link ResolveInfo}. - */ - public ActivityResolveInfo(ResolveInfo resolveInfo) { - this.resolveInfo = resolveInfo; - } - - @Override - public int hashCode() { - return 31 + Float.floatToIntBits(weight); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ActivityResolveInfo other = (ActivityResolveInfo) obj; - if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) { - return false; - } - return true; - } - - public int compareTo(ActivityResolveInfo another) { - return Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("["); - builder.append("resolveInfo:").append(resolveInfo.toString()); - builder.append("; weight:").append(new BigDecimal(weight)); - builder.append("]"); - return builder.toString(); - } - } - - /** - * Default activity sorter implementation. - */ - private final class DefaultSorter implements ActivitySorter { - private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f; - - private final Map mPackageNameToActivityMap = - new HashMap(); - - public void sort(Intent intent, List activities, - List historicalRecords) { - Map packageNameToActivityMap = - mPackageNameToActivityMap; - packageNameToActivityMap.clear(); - - final int activityCount = activities.size(); - for (int i = 0; i < activityCount; i++) { - ActivityResolveInfo activity = activities.get(i); - activity.weight = 0.0f; - String packageName = activity.resolveInfo.activityInfo.packageName; - packageNameToActivityMap.put(packageName, activity); - } - - final int lastShareIndex = historicalRecords.size() - 1; - float nextRecordWeight = 1; - for (int i = lastShareIndex; i >= 0; i--) { - HistoricalRecord historicalRecord = historicalRecords.get(i); - String packageName = historicalRecord.activity.getPackageName(); - ActivityResolveInfo activity = packageNameToActivityMap.get(packageName); - if (activity != null) { - activity.weight += historicalRecord.weight * nextRecordWeight; - nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT; - } - } - - Collections.sort(activities); - - if (DEBUG) { - for (int i = 0; i < activityCount; i++) { - Log.i(LOG_TAG, "Sorted: " + activities.get(i)); - } - } - } - } - - /** - * Command for reading the historical records from a file off the UI thread. - */ - private final class HistoryLoader implements Runnable { - - public void run() { - FileInputStream fis = null; - try { - fis = mContext.openFileInput(mHistoryFileName); - } catch (FileNotFoundException fnfe) { - if (DEBUG) { - Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName); - } - return; - } - try { - XmlPullParser parser = Xml.newPullParser(); - parser.setInput(fis, null); - - int type = XmlPullParser.START_DOCUMENT; - while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) { - type = parser.next(); - } - - if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) { - throw new XmlPullParserException("Share records file does not start with " - + TAG_HISTORICAL_RECORDS + " tag."); - } - - List readRecords = new ArrayList(); - - while (true) { - type = parser.next(); - if (type == XmlPullParser.END_DOCUMENT) { - break; - } - if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { - continue; - } - String nodeName = parser.getName(); - if (!TAG_HISTORICAL_RECORD.equals(nodeName)) { - throw new XmlPullParserException("Share records file not well-formed."); - } - - String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY); - final long time = - Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME)); - final float weight = - Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT)); - - HistoricalRecord readRecord = new HistoricalRecord(activity, time, - weight); - readRecords.add(readRecord); - - if (DEBUG) { - Log.i(LOG_TAG, "Read " + readRecord.toString()); - } - } - - if (DEBUG) { - Log.i(LOG_TAG, "Read " + readRecords.size() + " historical records."); - } - - synchronized (mInstanceLock) { - Set uniqueShareRecords = - new LinkedHashSet(readRecords); - - // Make sure no duplicates. Example: Read a file with - // one record, add one record, persist the two records, - // add a record, read the persisted records - the - // read two records should not be added again. - List historicalRecords = mHistoricalRecords; - final int historicalRecordsCount = historicalRecords.size(); - for (int i = historicalRecordsCount - 1; i >= 0; i--) { - HistoricalRecord historicalRecord = historicalRecords.get(i); - uniqueShareRecords.add(historicalRecord); - } - - if (historicalRecords.size() == uniqueShareRecords.size()) { - return; - } - - // Make sure the oldest records go to the end. - historicalRecords.clear(); - historicalRecords.addAll(uniqueShareRecords); - - mHistoricalRecordsChanged = true; - - // Do this on the client thread since the client may be on the UI - // thread, wait for data changes which happen during sorting, and - // perform UI modification based on the data change. - mHandler.post(new Runnable() { - public void run() { - pruneExcessiveHistoricalRecordsLocked(); - sortActivities(); - } - }); - } - } catch (XmlPullParserException xppe) { - Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe); - } catch (IOException ioe) { - Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe); - } finally { - if (fis != null) { - try { - fis.close(); - } catch (IOException ioe) { - /* ignore */ - } - } - } - } - } - - /** - * Command for persisting the historical records to a file off the UI thread. - */ - private final class HistoryPersister implements Runnable { - - public void run() { - FileOutputStream fos = null; - List records = null; - - synchronized (mInstanceLock) { - records = new ArrayList(mHistoricalRecords); - } - - try { - fos = mContext.openFileOutput(mHistoryFileName, Context.MODE_PRIVATE); - } catch (FileNotFoundException fnfe) { - Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, fnfe); - return; - } - - XmlSerializer serializer = Xml.newSerializer(); - - try { - serializer.setOutput(fos, null); - serializer.startDocument("UTF-8", true); - serializer.startTag(null, TAG_HISTORICAL_RECORDS); - - final int recordCount = records.size(); - for (int i = 0; i < recordCount; i++) { - HistoricalRecord record = records.remove(0); - serializer.startTag(null, TAG_HISTORICAL_RECORD); - serializer.attribute(null, ATTRIBUTE_ACTIVITY, record.activity.flattenToString()); - serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time)); - serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight)); - serializer.endTag(null, TAG_HISTORICAL_RECORD); - if (DEBUG) { - Log.i(LOG_TAG, "Wrote " + record.toString()); - } - } - - serializer.endTag(null, TAG_HISTORICAL_RECORDS); - serializer.endDocument(); - - if (DEBUG) { - Log.i(LOG_TAG, "Wrote " + recordCount + " historical records."); - } - } catch (IllegalArgumentException iae) { - Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae); - } catch (IllegalStateException ise) { - Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise); - } catch (IOException ioe) { - Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe); - } finally { - if (fos != null) { - try { - fos.close(); - } catch (IOException e) { - /* ignore */ - } - } - } - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java deleted file mode 100644 index da13bc99..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java +++ /dev/null @@ -1,818 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.widget; - -import android.os.Build; -import com.actionbarsherlock.R; -import com.actionbarsherlock.internal.widget.IcsLinearLayout; -import com.actionbarsherlock.internal.widget.IcsListPopupWindow; -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.widget.ActivityChooserModel.ActivityChooserModelClient; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.database.DataSetObserver; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.view.ViewTreeObserver.OnGlobalLayoutListener; -import android.widget.AdapterView; -import android.widget.BaseAdapter; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.PopupWindow; -import android.widget.TextView; - -/** - * This class is a view for choosing an activity for handling a given {@link Intent}. - *

- * The view is composed of two adjacent buttons: - *

    - *
  • - * The left button is an immediate action and allows one click activity choosing. - * Tapping this button immediately executes the intent without requiring any further - * user input. Long press on this button shows a popup for changing the default - * activity. - *
  • - *
  • - * The right button is an overflow action and provides an optimized menu - * of additional activities. Tapping this button shows a popup anchored to this - * view, listing the most frequently used activities. This list is initially - * limited to a small number of items in frequency used order. The last item, - * "Show all..." serves as an affordance to display all available activities. - *
  • - *
- *

- * - * @hide - */ -class ActivityChooserView extends ViewGroup implements ActivityChooserModelClient { - - /** - * An adapter for displaying the activities in an {@link AdapterView}. - */ - private final ActivityChooserViewAdapter mAdapter; - - /** - * Implementation of various interfaces to avoid publishing them in the APIs. - */ - private final Callbacks mCallbacks; - - /** - * The content of this view. - */ - private final IcsLinearLayout mActivityChooserContent; - - /** - * Stores the background drawable to allow hiding and latter showing. - */ - private final Drawable mActivityChooserContentBackground; - - /** - * The expand activities action button; - */ - private final FrameLayout mExpandActivityOverflowButton; - - /** - * The image for the expand activities action button; - */ - private final ImageView mExpandActivityOverflowButtonImage; - - /** - * The default activities action button; - */ - private final FrameLayout mDefaultActivityButton; - - /** - * The image for the default activities action button; - */ - private final ImageView mDefaultActivityButtonImage; - - /** - * The maximal width of the list popup. - */ - private final int mListPopupMaxWidth; - - /** - * The ActionProvider hosting this view, if applicable. - */ - ActionProvider mProvider; - - /** - * Observer for the model data. - */ - private final DataSetObserver mModelDataSetOberver = new DataSetObserver() { - - @Override - public void onChanged() { - super.onChanged(); - mAdapter.notifyDataSetChanged(); - } - @Override - public void onInvalidated() { - super.onInvalidated(); - mAdapter.notifyDataSetInvalidated(); - } - }; - - private final OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - if (isShowingPopup()) { - if (!isShown()) { - getListPopupWindow().dismiss(); - } else { - getListPopupWindow().show(); - if (mProvider != null) { - mProvider.subUiVisibilityChanged(true); - } - } - } - } - }; - - /** - * Popup window for showing the activity overflow list. - */ - private IcsListPopupWindow mListPopupWindow; - - /** - * Listener for the dismissal of the popup/alert. - */ - private PopupWindow.OnDismissListener mOnDismissListener; - - /** - * Flag whether a default activity currently being selected. - */ - private boolean mIsSelectingDefaultActivity; - - /** - * The count of activities in the popup. - */ - private int mInitialActivityCount = ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT; - - /** - * Flag whether this view is attached to a window. - */ - private boolean mIsAttachedToWindow; - - /** - * String resource for formatting content description of the default target. - */ - private int mDefaultActionButtonContentDescription; - - private final Context mContext; - - /** - * Create a new instance. - * - * @param context The application environment. - */ - public ActivityChooserView(Context context) { - this(context, null); - } - - /** - * Create a new instance. - * - * @param context The application environment. - * @param attrs A collection of attributes. - */ - public ActivityChooserView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - /** - * Create a new instance. - * - * @param context The application environment. - * @param attrs A collection of attributes. - * @param defStyle The default style to apply to this view. - */ - public ActivityChooserView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mContext = context; - - TypedArray attributesArray = context.obtainStyledAttributes(attrs, - R.styleable.SherlockActivityChooserView, defStyle, 0); - - mInitialActivityCount = attributesArray.getInt( - R.styleable.SherlockActivityChooserView_initialActivityCount, - ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT); - - Drawable expandActivityOverflowButtonDrawable = attributesArray.getDrawable( - R.styleable.SherlockActivityChooserView_expandActivityOverflowButtonDrawable); - - attributesArray.recycle(); - - LayoutInflater inflater = LayoutInflater.from(mContext); - inflater.inflate(R.layout.abs__activity_chooser_view, this, true); - - mCallbacks = new Callbacks(); - - mActivityChooserContent = (IcsLinearLayout) findViewById(R.id.abs__activity_chooser_view_content); - mActivityChooserContentBackground = mActivityChooserContent.getBackground(); - - mDefaultActivityButton = (FrameLayout) findViewById(R.id.abs__default_activity_button); - mDefaultActivityButton.setOnClickListener(mCallbacks); - mDefaultActivityButton.setOnLongClickListener(mCallbacks); - mDefaultActivityButtonImage = (ImageView) mDefaultActivityButton.findViewById(R.id.abs__image); - - mExpandActivityOverflowButton = (FrameLayout) findViewById(R.id.abs__expand_activities_button); - mExpandActivityOverflowButton.setOnClickListener(mCallbacks); - mExpandActivityOverflowButtonImage = - (ImageView) mExpandActivityOverflowButton.findViewById(R.id.abs__image); - mExpandActivityOverflowButtonImage.setImageDrawable(expandActivityOverflowButtonDrawable); - - mAdapter = new ActivityChooserViewAdapter(); - mAdapter.registerDataSetObserver(new DataSetObserver() { - @Override - public void onChanged() { - super.onChanged(); - updateAppearance(); - } - }); - - Resources resources = context.getResources(); - mListPopupMaxWidth = Math.max(resources.getDisplayMetrics().widthPixels / 2, - resources.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth)); - } - - /** - * {@inheritDoc} - */ - public void setActivityChooserModel(ActivityChooserModel dataModel) { - mAdapter.setDataModel(dataModel); - if (isShowingPopup()) { - dismissPopup(); - showPopup(); - } - } - - /** - * Sets the background for the button that expands the activity - * overflow list. - * - * Note: Clients would like to set this drawable - * as a clue about the action the chosen activity will perform. For - * example, if a share activity is to be chosen the drawable should - * give a clue that sharing is to be performed. - * - * @param drawable The drawable. - */ - public void setExpandActivityOverflowButtonDrawable(Drawable drawable) { - mExpandActivityOverflowButtonImage.setImageDrawable(drawable); - } - - /** - * Sets the content description for the button that expands the activity - * overflow list. - * - * description as a clue about the action performed by the button. - * For example, if a share activity is to be chosen the content - * description should be something like "Share with". - * - * @param resourceId The content description resource id. - */ - public void setExpandActivityOverflowButtonContentDescription(int resourceId) { - CharSequence contentDescription = mContext.getString(resourceId); - mExpandActivityOverflowButtonImage.setContentDescription(contentDescription); - } - - /** - * Set the provider hosting this view, if applicable. - * @hide Internal use only - */ - public void setProvider(ActionProvider provider) { - mProvider = provider; - } - - /** - * Shows the popup window with activities. - * - * @return True if the popup was shown, false if already showing. - */ - public boolean showPopup() { - if (isShowingPopup() || !mIsAttachedToWindow) { - return false; - } - mIsSelectingDefaultActivity = false; - showPopupUnchecked(mInitialActivityCount); - return true; - } - - /** - * Shows the popup no matter if it was already showing. - * - * @param maxActivityCount The max number of activities to display. - */ - private void showPopupUnchecked(int maxActivityCount) { - if (mAdapter.getDataModel() == null) { - throw new IllegalStateException("No data model. Did you call #setDataModel?"); - } - - getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener); - - final boolean defaultActivityButtonShown = - mDefaultActivityButton.getVisibility() == VISIBLE; - - final int activityCount = mAdapter.getActivityCount(); - final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0; - if (maxActivityCount != ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED - && activityCount > maxActivityCount + maxActivityCountOffset) { - mAdapter.setShowFooterView(true); - mAdapter.setMaxActivityCount(maxActivityCount - 1); - } else { - mAdapter.setShowFooterView(false); - mAdapter.setMaxActivityCount(maxActivityCount); - } - - IcsListPopupWindow popupWindow = getListPopupWindow(); - if (!popupWindow.isShowing()) { - if (mIsSelectingDefaultActivity || !defaultActivityButtonShown) { - mAdapter.setShowDefaultActivity(true, defaultActivityButtonShown); - } else { - mAdapter.setShowDefaultActivity(false, false); - } - final int contentWidth = Math.min(mAdapter.measureContentWidth(), mListPopupMaxWidth); - popupWindow.setContentWidth(contentWidth); - popupWindow.show(); - if (mProvider != null) { - mProvider.subUiVisibilityChanged(true); - } - popupWindow.getListView().setContentDescription(mContext.getString( - R.string.abs__activitychooserview_choose_application)); - } - } - - /** - * Dismisses the popup window with activities. - * - * @return True if dismissed, false if already dismissed. - */ - public boolean dismissPopup() { - if (isShowingPopup()) { - getListPopupWindow().dismiss(); - ViewTreeObserver viewTreeObserver = getViewTreeObserver(); - if (viewTreeObserver.isAlive()) { - viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener); - } - } - return true; - } - - /** - * Gets whether the popup window with activities is shown. - * - * @return True if the popup is shown. - */ - public boolean isShowingPopup() { - return getListPopupWindow().isShowing(); - } - - @Override - protected void onAttachedToWindow() { - super.onAttachedToWindow(); - ActivityChooserModel dataModel = mAdapter.getDataModel(); - if (dataModel != null) { - dataModel.registerObserver(mModelDataSetOberver); - } - mIsAttachedToWindow = true; - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - ActivityChooserModel dataModel = mAdapter.getDataModel(); - if (dataModel != null) { - dataModel.unregisterObserver(mModelDataSetOberver); - } - ViewTreeObserver viewTreeObserver = getViewTreeObserver(); - if (viewTreeObserver.isAlive()) { - viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener); - } - mIsAttachedToWindow = false; - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - View child = mActivityChooserContent; - // If the default action is not visible we want to be as tall as the - // ActionBar so if this widget is used in the latter it will look as - // a normal action button. - if (mDefaultActivityButton.getVisibility() != VISIBLE) { - heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec), - MeasureSpec.EXACTLY); - } - measureChild(child, widthMeasureSpec, heightMeasureSpec); - setMeasuredDimension(child.getMeasuredWidth(), child.getMeasuredHeight()); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - mActivityChooserContent.layout(0, 0, right - left, bottom - top); - if (getListPopupWindow().isShowing()) { - showPopupUnchecked(mAdapter.getMaxActivityCount()); - } else { - dismissPopup(); - } - } - - public ActivityChooserModel getDataModel() { - return mAdapter.getDataModel(); - } - - /** - * Sets a listener to receive a callback when the popup is dismissed. - * - * @param listener The listener to be notified. - */ - public void setOnDismissListener(PopupWindow.OnDismissListener listener) { - mOnDismissListener = listener; - } - - /** - * Sets the initial count of items shown in the activities popup - * i.e. the items before the popup is expanded. This is an upper - * bound since it is not guaranteed that such number of intent - * handlers exist. - * - * @param itemCount The initial popup item count. - */ - public void setInitialActivityCount(int itemCount) { - mInitialActivityCount = itemCount; - } - - /** - * Sets a content description of the default action button. This - * resource should be a string taking one formatting argument and - * will be used for formatting the content description of the button - * dynamically as the default target changes. For example, a resource - * pointing to the string "share with %1$s" will result in a content - * description "share with Bluetooth" for the Bluetooth activity. - * - * @param resourceId The resource id. - */ - public void setDefaultActionButtonContentDescription(int resourceId) { - mDefaultActionButtonContentDescription = resourceId; - } - - /** - * Gets the list popup window which is lazily initialized. - * - * @return The popup. - */ - private IcsListPopupWindow getListPopupWindow() { - if (mListPopupWindow == null) { - mListPopupWindow = new IcsListPopupWindow(getContext()); - mListPopupWindow.setAdapter(mAdapter); - mListPopupWindow.setAnchorView(ActivityChooserView.this); - mListPopupWindow.setModal(true); - mListPopupWindow.setOnItemClickListener(mCallbacks); - mListPopupWindow.setOnDismissListener(mCallbacks); - } - return mListPopupWindow; - } - - /** - * Updates the buttons state. - */ - private void updateAppearance() { - // Expand overflow button. - if (mAdapter.getCount() > 0) { - mExpandActivityOverflowButton.setEnabled(true); - } else { - mExpandActivityOverflowButton.setEnabled(false); - } - // Default activity button. - final int activityCount = mAdapter.getActivityCount(); - final int historySize = mAdapter.getHistorySize(); - if (activityCount > 0 && historySize > 0) { - mDefaultActivityButton.setVisibility(VISIBLE); - ResolveInfo activity = mAdapter.getDefaultActivity(); - PackageManager packageManager = mContext.getPackageManager(); - mDefaultActivityButtonImage.setImageDrawable(activity.loadIcon(packageManager)); - if (mDefaultActionButtonContentDescription != 0) { - CharSequence label = activity.loadLabel(packageManager); - String contentDescription = mContext.getString( - mDefaultActionButtonContentDescription, label); - mDefaultActivityButton.setContentDescription(contentDescription); - } - } else { - mDefaultActivityButton.setVisibility(View.GONE); - } - // Activity chooser content. - if (mDefaultActivityButton.getVisibility() == VISIBLE) { - mActivityChooserContent.setBackgroundDrawable(mActivityChooserContentBackground); - } else { - mActivityChooserContent.setBackgroundDrawable(null); - } - } - - /** - * Interface implementation to avoid publishing them in the APIs. - */ - private class Callbacks implements AdapterView.OnItemClickListener, - View.OnClickListener, View.OnLongClickListener, PopupWindow.OnDismissListener { - - // AdapterView#OnItemClickListener - public void onItemClick(AdapterView parent, View view, int position, long id) { - ActivityChooserViewAdapter adapter = (ActivityChooserViewAdapter) parent.getAdapter(); - final int itemViewType = adapter.getItemViewType(position); - switch (itemViewType) { - case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_FOOTER: { - showPopupUnchecked(ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED); - } break; - case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_ACTIVITY: { - dismissPopup(); - if (mIsSelectingDefaultActivity) { - // The item at position zero is the default already. - if (position > 0) { - mAdapter.getDataModel().setDefaultActivity(position); - } - } else { - // If the default target is not shown in the list, the first - // item in the model is default action => adjust index - position = mAdapter.getShowDefaultActivity() ? position : position + 1; - Intent launchIntent = mAdapter.getDataModel().chooseActivity(position); - if (launchIntent != null) { - mContext.startActivity(launchIntent); - } - } - } break; - default: - throw new IllegalArgumentException(); - } - } - - // View.OnClickListener - public void onClick(View view) { - if (view == mDefaultActivityButton) { - dismissPopup(); - ResolveInfo defaultActivity = mAdapter.getDefaultActivity(); - final int index = mAdapter.getDataModel().getActivityIndex(defaultActivity); - Intent launchIntent = mAdapter.getDataModel().chooseActivity(index); - if (launchIntent != null) { - mContext.startActivity(launchIntent); - } - } else if (view == mExpandActivityOverflowButton) { - mIsSelectingDefaultActivity = false; - showPopupUnchecked(mInitialActivityCount); - } else { - throw new IllegalArgumentException(); - } - } - - // OnLongClickListener#onLongClick - @Override - public boolean onLongClick(View view) { - if (view == mDefaultActivityButton) { - if (mAdapter.getCount() > 0) { - mIsSelectingDefaultActivity = true; - showPopupUnchecked(mInitialActivityCount); - } - } else { - throw new IllegalArgumentException(); - } - return true; - } - - // PopUpWindow.OnDismissListener#onDismiss - public void onDismiss() { - notifyOnDismissListener(); - if (mProvider != null) { - mProvider.subUiVisibilityChanged(false); - } - } - - private void notifyOnDismissListener() { - if (mOnDismissListener != null) { - mOnDismissListener.onDismiss(); - } - } - } - - private static class SetActivated { - public static void invoke(View view, boolean activated) { - view.setActivated(activated); - } - } - - private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; - - /** - * Adapter for backing the list of activities shown in the popup. - */ - private class ActivityChooserViewAdapter extends BaseAdapter { - - public static final int MAX_ACTIVITY_COUNT_UNLIMITED = Integer.MAX_VALUE; - - public static final int MAX_ACTIVITY_COUNT_DEFAULT = 4; - - private static final int ITEM_VIEW_TYPE_ACTIVITY = 0; - - private static final int ITEM_VIEW_TYPE_FOOTER = 1; - - private static final int ITEM_VIEW_TYPE_COUNT = 3; - - private ActivityChooserModel mDataModel; - - private int mMaxActivityCount = MAX_ACTIVITY_COUNT_DEFAULT; - - private boolean mShowDefaultActivity; - - private boolean mHighlightDefaultActivity; - - private boolean mShowFooterView; - - public void setDataModel(ActivityChooserModel dataModel) { - ActivityChooserModel oldDataModel = mAdapter.getDataModel(); - if (oldDataModel != null && isShown()) { - oldDataModel.unregisterObserver(mModelDataSetOberver); - } - mDataModel = dataModel; - if (dataModel != null && isShown()) { - dataModel.registerObserver(mModelDataSetOberver); - } - notifyDataSetChanged(); - } - - @Override - public int getItemViewType(int position) { - if (mShowFooterView && position == getCount() - 1) { - return ITEM_VIEW_TYPE_FOOTER; - } else { - return ITEM_VIEW_TYPE_ACTIVITY; - } - } - - @Override - public int getViewTypeCount() { - return ITEM_VIEW_TYPE_COUNT; - } - - public int getCount() { - int count = 0; - int activityCount = mDataModel.getActivityCount(); - if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) { - activityCount--; - } - count = Math.min(activityCount, mMaxActivityCount); - if (mShowFooterView) { - count++; - } - return count; - } - - public Object getItem(int position) { - final int itemViewType = getItemViewType(position); - switch (itemViewType) { - case ITEM_VIEW_TYPE_FOOTER: - return null; - case ITEM_VIEW_TYPE_ACTIVITY: - if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) { - position++; - } - return mDataModel.getActivity(position); - default: - throw new IllegalArgumentException(); - } - } - - public long getItemId(int position) { - return position; - } - - public View getView(int position, View convertView, ViewGroup parent) { - final int itemViewType = getItemViewType(position); - switch (itemViewType) { - case ITEM_VIEW_TYPE_FOOTER: - if (convertView == null || convertView.getId() != ITEM_VIEW_TYPE_FOOTER) { - convertView = LayoutInflater.from(getContext()).inflate( - R.layout.abs__activity_chooser_view_list_item, parent, false); - convertView.setId(ITEM_VIEW_TYPE_FOOTER); - TextView titleView = (TextView) convertView.findViewById(R.id.abs__title); - titleView.setText(mContext.getString( - R.string.abs__activity_chooser_view_see_all)); - } - return convertView; - case ITEM_VIEW_TYPE_ACTIVITY: - if (convertView == null || convertView.getId() != R.id.abs__list_item) { - convertView = LayoutInflater.from(getContext()).inflate( - R.layout.abs__activity_chooser_view_list_item, parent, false); - } - PackageManager packageManager = mContext.getPackageManager(); - // Set the icon - ImageView iconView = (ImageView) convertView.findViewById(R.id.abs__icon); - ResolveInfo activity = (ResolveInfo) getItem(position); - iconView.setImageDrawable(activity.loadIcon(packageManager)); - // Set the title. - TextView titleView = (TextView) convertView.findViewById(R.id.abs__title); - titleView.setText(activity.loadLabel(packageManager)); - if (IS_HONEYCOMB) { - // Highlight the default. - if (mShowDefaultActivity && position == 0 && mHighlightDefaultActivity) { - SetActivated.invoke(convertView, true); - } else { - SetActivated.invoke(convertView, false); - } - } - return convertView; - default: - throw new IllegalArgumentException(); - } - } - - public int measureContentWidth() { - // The user may have specified some of the target not to be shown but we - // want to measure all of them since after expansion they should fit. - final int oldMaxActivityCount = mMaxActivityCount; - mMaxActivityCount = MAX_ACTIVITY_COUNT_UNLIMITED; - - int contentWidth = 0; - View itemView = null; - - final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - final int count = getCount(); - - for (int i = 0; i < count; i++) { - itemView = getView(i, itemView, null); - itemView.measure(widthMeasureSpec, heightMeasureSpec); - contentWidth = Math.max(contentWidth, itemView.getMeasuredWidth()); - } - - mMaxActivityCount = oldMaxActivityCount; - - return contentWidth; - } - - public void setMaxActivityCount(int maxActivityCount) { - if (mMaxActivityCount != maxActivityCount) { - mMaxActivityCount = maxActivityCount; - notifyDataSetChanged(); - } - } - - public ResolveInfo getDefaultActivity() { - return mDataModel.getDefaultActivity(); - } - - public void setShowFooterView(boolean showFooterView) { - if (mShowFooterView != showFooterView) { - mShowFooterView = showFooterView; - notifyDataSetChanged(); - } - } - - public int getActivityCount() { - return mDataModel.getActivityCount(); - } - - public int getHistorySize() { - return mDataModel.getHistorySize(); - } - - public int getMaxActivityCount() { - return mMaxActivityCount; - } - - public ActivityChooserModel getDataModel() { - return mDataModel; - } - - public void setShowDefaultActivity(boolean showDefaultActivity, - boolean highlightDefaultActivity) { - if (mShowDefaultActivity != showDefaultActivity - || mHighlightDefaultActivity != highlightDefaultActivity) { - mShowDefaultActivity = showDefaultActivity; - mHighlightDefaultActivity = highlightDefaultActivity; - notifyDataSetChanged(); - } - } - - public boolean getShowDefaultActivity() { - return mShowDefaultActivity; - } - } -} diff --git a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java deleted file mode 100644 index 83e9f0ca..00000000 --- a/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.actionbarsherlock.widget; - -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.graphics.drawable.Drawable; -import android.util.TypedValue; -import android.view.View; - -import com.actionbarsherlock.R; -import com.actionbarsherlock.view.ActionProvider; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener; -import com.actionbarsherlock.view.SubMenu; -import com.actionbarsherlock.widget.ActivityChooserModel.OnChooseActivityListener; - -/** - * This is a provider for a share action. It is responsible for creating views - * that enable data sharing and also to show a sub menu with sharing activities - * if the hosting item is placed on the overflow menu. - *

- * Here is how to use the action provider with custom backing file in a {@link MenuItem}: - *

- *

- *

- * 
- *  // In Activity#onCreateOptionsMenu
- *  public boolean onCreateOptionsMenu(Menu menu) {
- *      // Get the menu item.
- *      MenuItem menuItem = menu.findItem(R.id.my_menu_item);
- *      // Get the provider and hold onto it to set/change the share intent.
- *      mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
- *      // Set history different from the default before getting the action
- *      // view since a call to {@link MenuItem#getActionView() MenuItem.getActionView()} calls
- *      // {@link ActionProvider#onCreateActionView()} which uses the backing file name. Omit this
- *      // line if using the default share history file is desired.
- *      mShareActionProvider.setShareHistoryFileName("custom_share_history.xml");
- *      . . .
- *  }
- *
- *  // Somewhere in the application.
- *  public void doShare(Intent shareIntent) {
- *      // When you want to share set the share intent.
- *      mShareActionProvider.setShareIntent(shareIntent);
- *  }
- * 
- * - *

- *

- * Note: While the sample snippet demonstrates how to use this provider - * in the context of a menu item, the use of the provider is not limited to menu items. - *

- * - * @see ActionProvider - */ -public class ShareActionProvider extends ActionProvider { - - /** - * Listener for the event of selecting a share target. - */ - public interface OnShareTargetSelectedListener { - - /** - * Called when a share target has been selected. The client can - * decide whether to handle the intent or rely on the default - * behavior which is launching it. - *

- * Note: Modifying the intent is not permitted and - * any changes to the latter will be ignored. - *

- * - * @param source The source of the notification. - * @param intent The intent for launching the chosen share target. - * @return Whether the client has handled the intent. - */ - public boolean onShareTargetSelected(ShareActionProvider source, Intent intent); - } - - /** - * The default for the maximal number of activities shown in the sub-menu. - */ - private static final int DEFAULT_INITIAL_ACTIVITY_COUNT = 4; - - /** - * The the maximum number activities shown in the sub-menu. - */ - private int mMaxShownActivityCount = DEFAULT_INITIAL_ACTIVITY_COUNT; - - /** - * Listener for handling menu item clicks. - */ - private final ShareMenuItemOnMenuItemClickListener mOnMenuItemClickListener = - new ShareMenuItemOnMenuItemClickListener(); - - /** - * The default name for storing share history. - */ - public static final String DEFAULT_SHARE_HISTORY_FILE_NAME = "share_history.xml"; - - /** - * Context for accessing resources. - */ - private final Context mContext; - - /** - * The name of the file with share history data. - */ - private String mShareHistoryFileName = DEFAULT_SHARE_HISTORY_FILE_NAME; - - private OnShareTargetSelectedListener mOnShareTargetSelectedListener; - - private OnChooseActivityListener mOnChooseActivityListener; - - /** - * Creates a new instance. - * - * @param context Context for accessing resources. - */ - public ShareActionProvider(Context context) { - super(context); - mContext = context; - } - - /** - * Sets a listener to be notified when a share target has been selected. - * The listener can optionally decide to handle the selection and - * not rely on the default behavior which is to launch the activity. - *

- * Note: If you choose the backing share history file - * you will still be notified in this callback. - *

- * @param listener The listener. - */ - public void setOnShareTargetSelectedListener(OnShareTargetSelectedListener listener) { - mOnShareTargetSelectedListener = listener; - setActivityChooserPolicyIfNeeded(); - } - - /** - * {@inheritDoc} - */ - @Override - public View onCreateActionView() { - // Create the view and set its data model. - ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName); - ActivityChooserView activityChooserView = new ActivityChooserView(mContext); - activityChooserView.setActivityChooserModel(dataModel); - - // Lookup and set the expand action icon. - TypedValue outTypedValue = new TypedValue(); - mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true); - Drawable drawable = mContext.getResources().getDrawable(outTypedValue.resourceId); - activityChooserView.setExpandActivityOverflowButtonDrawable(drawable); - activityChooserView.setProvider(this); - - // Set content description. - activityChooserView.setDefaultActionButtonContentDescription( - R.string.abs__shareactionprovider_share_with_application); - activityChooserView.setExpandActivityOverflowButtonContentDescription( - R.string.abs__shareactionprovider_share_with); - - return activityChooserView; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasSubMenu() { - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public void onPrepareSubMenu(SubMenu subMenu) { - // Clear since the order of items may change. - subMenu.clear(); - - ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName); - PackageManager packageManager = mContext.getPackageManager(); - - final int expandedActivityCount = dataModel.getActivityCount(); - final int collapsedActivityCount = Math.min(expandedActivityCount, mMaxShownActivityCount); - - // Populate the sub-menu with a sub set of the activities. - for (int i = 0; i < collapsedActivityCount; i++) { - ResolveInfo activity = dataModel.getActivity(i); - subMenu.add(0, i, i, activity.loadLabel(packageManager)) - .setIcon(activity.loadIcon(packageManager)) - .setOnMenuItemClickListener(mOnMenuItemClickListener); - } - - if (collapsedActivityCount < expandedActivityCount) { - // Add a sub-menu for showing all activities as a list item. - SubMenu expandedSubMenu = subMenu.addSubMenu(Menu.NONE, collapsedActivityCount, - collapsedActivityCount, - mContext.getString(R.string.abs__activity_chooser_view_see_all)); - for (int i = 0; i < expandedActivityCount; i++) { - ResolveInfo activity = dataModel.getActivity(i); - expandedSubMenu.add(0, i, i, activity.loadLabel(packageManager)) - .setIcon(activity.loadIcon(packageManager)) - .setOnMenuItemClickListener(mOnMenuItemClickListener); - } - } - } - - /** - * Sets the file name of a file for persisting the share history which - * history will be used for ordering share targets. This file will be used - * for all view created by {@link #onCreateActionView()}. Defaults to - * {@link #DEFAULT_SHARE_HISTORY_FILE_NAME}. Set to null - * if share history should not be persisted between sessions. - *

- * Note: The history file name can be set any time, however - * only the action views created by {@link #onCreateActionView()} after setting - * the file name will be backed by the provided file. - *

- * - * @param shareHistoryFile The share history file name. - */ - public void setShareHistoryFileName(String shareHistoryFile) { - mShareHistoryFileName = shareHistoryFile; - setActivityChooserPolicyIfNeeded(); - } - - /** - * Sets an intent with information about the share action. Here is a - * sample for constructing a share intent: - *

- *

-     * 
-     *  Intent shareIntent = new Intent(Intent.ACTION_SEND);
-     *  shareIntent.setType("image/*");
-     *  Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
-     *  shareIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
-     * 
- * - *

- * - * @param shareIntent The share intent. - * - * @see Intent#ACTION_SEND - * @see Intent#ACTION_SEND_MULTIPLE - */ - public void setShareIntent(Intent shareIntent) { - ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, - mShareHistoryFileName); - dataModel.setIntent(shareIntent); - } - - /** - * Reusable listener for handling share item clicks. - */ - private class ShareMenuItemOnMenuItemClickListener implements OnMenuItemClickListener { - @Override - public boolean onMenuItemClick(MenuItem item) { - ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, - mShareHistoryFileName); - final int itemId = item.getItemId(); - Intent launchIntent = dataModel.chooseActivity(itemId); - if (launchIntent != null) { - mContext.startActivity(launchIntent); - } - return true; - } - } - - /** - * Set the activity chooser policy of the model backed by the current - * share history file if needed which is if there is a registered callback. - */ - private void setActivityChooserPolicyIfNeeded() { - if (mOnShareTargetSelectedListener == null) { - return; - } - if (mOnChooseActivityListener == null) { - mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy(); - } - ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName); - dataModel.setOnChooseActivityListener(mOnChooseActivityListener); - } - - /** - * Policy that delegates to the {@link OnShareTargetSelectedListener}, if such. - */ - private class ShareAcitivityChooserModelPolicy implements OnChooseActivityListener { - @Override - public boolean onChooseActivity(ActivityChooserModel host, Intent intent) { - if (mOnShareTargetSelectedListener != null) { - return mOnShareTargetSelectedListener.onShareTargetSelected( - ShareActionProvider.this, intent); - } - return false; - } - } -} diff --git a/android-libraries/TreeViewList/.classpath b/android-libraries/TreeViewList/.classpath deleted file mode 100644 index a4f1e405..00000000 --- a/android-libraries/TreeViewList/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/android-libraries/TreeViewList/.project b/android-libraries/TreeViewList/.project deleted file mode 100644 index c9d4fdac..00000000 --- a/android-libraries/TreeViewList/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - TreeViewList - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/android-libraries/TreeViewList/AndroidManifest.xml b/android-libraries/TreeViewList/AndroidManifest.xml deleted file mode 100644 index 28a7fe08..00000000 --- a/android-libraries/TreeViewList/AndroidManifest.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter$1.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter$1.class deleted file mode 100644 index 2b846618..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter$1.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter.class deleted file mode 100644 index 40535baa..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/BuildConfig.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/BuildConfig.class deleted file mode 100644 index 77562f42..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/BuildConfig.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeNode.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeNode.class deleted file mode 100644 index c2a6124d..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeNode.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeStateManager.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeStateManager.class deleted file mode 100644 index 791ae79a..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeStateManager.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeAlreadyInTreeException.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeAlreadyInTreeException.class deleted file mode 100644 index 35af40c6..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeAlreadyInTreeException.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeNotInTreeException.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeNotInTreeException.class deleted file mode 100644 index a9813987..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeNotInTreeException.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$attr.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$attr.class deleted file mode 100644 index 1a7b40c1..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$attr.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$drawable.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$drawable.class deleted file mode 100644 index f266770c..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$drawable.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$id.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$id.class deleted file mode 100644 index 7f119578..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$id.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$layout.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$layout.class deleted file mode 100644 index a13978fa..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$layout.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$style.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$style.class deleted file mode 100644 index 4a475b27..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$style.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$styleable.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$styleable.class deleted file mode 100644 index a992b85f..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$styleable.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R.class deleted file mode 100644 index ef23d5e4..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeBuilder.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeBuilder.class deleted file mode 100644 index 4ddc77cc..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeBuilder.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeConfigurationException.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeConfigurationException.class deleted file mode 100644 index d2e71937..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeConfigurationException.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeNodeInfo.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeNodeInfo.class deleted file mode 100644 index 683896ce..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeNodeInfo.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeStateManager.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeStateManager.class deleted file mode 100644 index f3beab57..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeStateManager.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList$1.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList$1.class deleted file mode 100644 index 2b9baacc..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList$1.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList.class deleted file mode 100644 index 53039993..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/overview.html b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/overview.html deleted file mode 100644 index bdd09ce9..00000000 --- a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/overview.html +++ /dev/null @@ -1,24 +0,0 @@ - - -This is a small utility that provides quite configurable tree view list. -It is based on standard android list view. It separates out different -aspects of the tree: there is a separate list view, tree adapter, tree -state manager and tree state builder. -

-

    -
  • Tree view provides the frame to display the view.
  • -
  • Adapter allows to create visual representation of each tree - node.
  • -
  • State manager provides storage for tree state (connections - between parents and children, collapsed/expanded state). It provides - all the low-level tree manipulation methods.
  • -
  • Tree builder allows to build tree easily providing higher - level methods. The tree can be build either from prepared sequentially - prepared list of nodes (node id, level) or using (parent/child - relationships).
  • -

    For now only in-memory state manager is provided, but Tree State - Manger interface is done in the way that database tree manager even for - large trees is potentially supported. -

- - \ No newline at end of file diff --git a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/package-info.class b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/package-info.class deleted file mode 100644 index d0a12754..00000000 Binary files a/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/package-info.class and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/jarlist.cache b/android-libraries/TreeViewList/bin/jarlist.cache deleted file mode 100644 index 1b5ec3f9..00000000 --- a/android-libraries/TreeViewList/bin/jarlist.cache +++ /dev/null @@ -1,3 +0,0 @@ -# cache for current jar dependecy. DO NOT EDIT. -# format is -# Encoding is UTF-8 diff --git a/android-libraries/TreeViewList/bin/res/drawable-hdpi/collapsed.png b/android-libraries/TreeViewList/bin/res/drawable-hdpi/collapsed.png deleted file mode 100644 index 84ca818c..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-hdpi/collapsed.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-hdpi/expanded.png b/android-libraries/TreeViewList/bin/res/drawable-hdpi/expanded.png deleted file mode 100644 index 27612315..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-hdpi/expanded.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-hdpi/ic_launcher.png b/android-libraries/TreeViewList/bin/res/drawable-hdpi/ic_launcher.png deleted file mode 100644 index 882eb148..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-ldpi/collapsed.png b/android-libraries/TreeViewList/bin/res/drawable-ldpi/collapsed.png deleted file mode 100644 index f9c06f4f..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-ldpi/collapsed.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-ldpi/expanded.png b/android-libraries/TreeViewList/bin/res/drawable-ldpi/expanded.png deleted file mode 100644 index 7ce50746..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-ldpi/expanded.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-ldpi/ic_launcher.png b/android-libraries/TreeViewList/bin/res/drawable-ldpi/ic_launcher.png deleted file mode 100644 index 18689f65..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-mdpi/collapsed.png b/android-libraries/TreeViewList/bin/res/drawable-mdpi/collapsed.png deleted file mode 100644 index d2e87746..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-mdpi/collapsed.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-mdpi/expanded.png b/android-libraries/TreeViewList/bin/res/drawable-mdpi/expanded.png deleted file mode 100644 index 4c5ad0f9..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-mdpi/expanded.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-mdpi/ic_launcher.png b/android-libraries/TreeViewList/bin/res/drawable-mdpi/ic_launcher.png deleted file mode 100644 index 02e96b96..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_disabled.9.png b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_disabled.9.png deleted file mode 100644 index 6bc40f6d..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_disabled.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_focus.9.png b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_focus.9.png deleted file mode 100644 index 38c67542..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_focus.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_longpress.9.png b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_longpress.9.png deleted file mode 100644 index 8d2894e1..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_longpress.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_pressed.9.png b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_pressed.9.png deleted file mode 100644 index 900623e1..00000000 Binary files a/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_pressed.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/bin/treeviewlist.jar b/android-libraries/TreeViewList/bin/treeviewlist.jar deleted file mode 100644 index 3445f56d..00000000 Binary files a/android-libraries/TreeViewList/bin/treeviewlist.jar and /dev/null differ diff --git a/android-libraries/TreeViewList/gen/pl/polidea/treeview/BuildConfig.java b/android-libraries/TreeViewList/gen/pl/polidea/treeview/BuildConfig.java deleted file mode 100644 index 18bc91b3..00000000 --- a/android-libraries/TreeViewList/gen/pl/polidea/treeview/BuildConfig.java +++ /dev/null @@ -1,6 +0,0 @@ -/** Automatically generated file. DO NOT MODIFY */ -package pl.polidea.treeview; - -public final class BuildConfig { - public final static boolean DEBUG = true; -} \ No newline at end of file diff --git a/android-libraries/TreeViewList/gen/pl/polidea/treeview/R.java b/android-libraries/TreeViewList/gen/pl/polidea/treeview/R.java deleted file mode 100644 index 3ef9b354..00000000 --- a/android-libraries/TreeViewList/gen/pl/polidea/treeview/R.java +++ /dev/null @@ -1,276 +0,0 @@ -/* AUTO-GENERATED FILE. DO NOT MODIFY. - * - * This class was automatically generated by the - * aapt tool from the resource data it found. It - * should not be modified by hand. - */ - -package pl.polidea.treeview; - -public final class R { - public static final class attr { - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int collapsible=0x7f010000; - /**

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int handle_trackball_press=0x7f010004; - /**

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - */ - public static int indent_width=0x7f010003; - /**

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int indicator_background=0x7f010006; - /**

Must be one or more (separated by '|') of the following constant values.

- ---- - - - - - - - - - - - - -
ConstantValueDescription
top0x30 Push object to the top of its container, not changing its size.
bottom0x50 Push object to the bottom of its container, not changing its size.
left0x03 Push object to the left of its container, not changing its size.
right0x05 Push object to the right of its container, not changing its size.
center_vertical0x10 Place object in the vertical center of its container, not changing its size.
fill_vertical0x70 Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal0x01 Place object in the horizontal center of its container, not changing its size.
fill_horizontal0x07 Grow the horizontal size of the object if needed so it completely fills its container.
center0x11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill0x77 Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical0x80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. - The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top - edge, and neither will clip both edges.
clip_horizontal0x08 Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. - The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the - left edge, and neither will clip both edges.
- */ - public static int indicator_gravity=0x7f010005; - /**

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int row_background=0x7f010007; - /**

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int src_collapsed=0x7f010002; - /**

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - */ - public static int src_expanded=0x7f010001; - } - public static final class drawable { - public static int collapsed=0x7f020000; - public static int divider=0x7f020001; - public static int expanded=0x7f020002; - public static int ic_launcher=0x7f020003; - public static int list_selector_background=0x7f020004; - public static int list_selector_background_disabled=0x7f020005; - public static int list_selector_background_focus=0x7f020006; - public static int list_selector_background_longpress=0x7f020007; - public static int list_selector_background_pressed=0x7f020008; - public static int list_selector_background_transition=0x7f020009; - } - public static final class id { - public static int bottom=0x7f040001; - public static int center=0x7f040008; - public static int center_horizontal=0x7f040006; - public static int center_vertical=0x7f040004; - public static int clip_horizontal=0x7f04000b; - public static int clip_vertical=0x7f04000a; - public static int fill=0x7f040009; - public static int fill_horizontal=0x7f040007; - public static int fill_vertical=0x7f040005; - public static int left=0x7f040002; - public static int right=0x7f040003; - public static int top=0x7f040000; - public static int treeview_list_item_frame=0x7f04000e; - public static int treeview_list_item_image=0x7f04000d; - public static int treeview_list_item_image_layout=0x7f04000c; - } - public static final class layout { - public static int tree_list_item_wrapper=0x7f030000; - } - public static final class style { - public static int treeViewListStyle=0x7f050000; - } - public static final class styleable { - /** Attributes that can be used with a TreeViewList. -

Includes the following attributes:

- - - - - - - - - - - - -
AttributeDescription
{@link #TreeViewList_collapsible pl.polidea.treeview:collapsible}
{@link #TreeViewList_handle_trackball_press pl.polidea.treeview:handle_trackball_press}
{@link #TreeViewList_indent_width pl.polidea.treeview:indent_width}
{@link #TreeViewList_indicator_background pl.polidea.treeview:indicator_background}
{@link #TreeViewList_indicator_gravity pl.polidea.treeview:indicator_gravity}
{@link #TreeViewList_row_background pl.polidea.treeview:row_background}
{@link #TreeViewList_src_collapsed pl.polidea.treeview:src_collapsed}
{@link #TreeViewList_src_expanded pl.polidea.treeview:src_expanded}
- @see #TreeViewList_collapsible - @see #TreeViewList_handle_trackball_press - @see #TreeViewList_indent_width - @see #TreeViewList_indicator_background - @see #TreeViewList_indicator_gravity - @see #TreeViewList_row_background - @see #TreeViewList_src_collapsed - @see #TreeViewList_src_expanded - */ - public static final int[] TreeViewList = { - 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, - 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007 - }; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#collapsible} - attribute's value can be found in the {@link #TreeViewList} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:collapsible - */ - public static final int TreeViewList_collapsible = 0; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#handle_trackball_press} - attribute's value can be found in the {@link #TreeViewList} array. - - -

Must be a boolean value, either "true" or "false". -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:handle_trackball_press - */ - public static final int TreeViewList_handle_trackball_press = 4; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#indent_width} - attribute's value can be found in the {@link #TreeViewList} array. - - -

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". -Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), -in (inches), mm (millimeters). -

This may also be a reference to a resource (in the form -"@[package:]type:name") or -theme attribute (in the form -"?[package:][type:]name") -containing a value of this type. - @attr name android:indent_width - */ - public static final int TreeViewList_indent_width = 3; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#indicator_background} - attribute's value can be found in the {@link #TreeViewList} array. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - @attr name android:indicator_background - */ - public static final int TreeViewList_indicator_background = 6; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#indicator_gravity} - attribute's value can be found in the {@link #TreeViewList} array. - - -

Must be one or more (separated by '|') of the following constant values.

- ---- - - - - - - - - - - - - -
ConstantValueDescription
top0x30 Push object to the top of its container, not changing its size.
bottom0x50 Push object to the bottom of its container, not changing its size.
left0x03 Push object to the left of its container, not changing its size.
right0x05 Push object to the right of its container, not changing its size.
center_vertical0x10 Place object in the vertical center of its container, not changing its size.
fill_vertical0x70 Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal0x01 Place object in the horizontal center of its container, not changing its size.
fill_horizontal0x07 Grow the horizontal size of the object if needed so it completely fills its container.
center0x11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill0x77 Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical0x80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. - The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top - edge, and neither will clip both edges.
clip_horizontal0x08 Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. - The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the - left edge, and neither will clip both edges.
- @attr name android:indicator_gravity - */ - public static final int TreeViewList_indicator_gravity = 5; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#row_background} - attribute's value can be found in the {@link #TreeViewList} array. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - @attr name android:row_background - */ - public static final int TreeViewList_row_background = 7; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#src_collapsed} - attribute's value can be found in the {@link #TreeViewList} array. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - @attr name android:src_collapsed - */ - public static final int TreeViewList_src_collapsed = 2; - /** -

This symbol is the offset where the {@link pl.polidea.treeview.R.attr#src_expanded} - attribute's value can be found in the {@link #TreeViewList} array. - - -

May be a reference to another resource, in the form "@[+][package:]type:name" -or to a theme attribute in the form "?[package:][type:]name". -

May be a color value, in the form of "#rgb", "#argb", -"#rrggbb", or "#aarrggbb". - @attr name android:src_expanded - */ - public static final int TreeViewList_src_expanded = 1; - }; -} diff --git a/android-libraries/TreeViewList/proguard.cfg b/android-libraries/TreeViewList/proguard.cfg deleted file mode 100644 index b1cdf17b..00000000 --- a/android-libraries/TreeViewList/proguard.cfg +++ /dev/null @@ -1,40 +0,0 @@ --optimizationpasses 5 --dontusemixedcaseclassnames --dontskipnonpubliclibraryclasses --dontpreverify --verbose --optimizations !code/simplification/arithmetic,!field/*,!class/merging/* - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference --keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native ; -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet); -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet, int); -} - --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} diff --git a/android-libraries/TreeViewList/project.properties b/android-libraries/TreeViewList/project.properties deleted file mode 100644 index 5fa344c9..00000000 --- a/android-libraries/TreeViewList/project.properties +++ /dev/null @@ -1,12 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-15 -android.library=true diff --git a/android-libraries/TreeViewList/res/drawable-hdpi/collapsed.png b/android-libraries/TreeViewList/res/drawable-hdpi/collapsed.png deleted file mode 100644 index c1e1f3d5..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-hdpi/collapsed.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-hdpi/expanded.png b/android-libraries/TreeViewList/res/drawable-hdpi/expanded.png deleted file mode 100644 index cec254aa..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-hdpi/expanded.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-hdpi/ic_launcher.png b/android-libraries/TreeViewList/res/drawable-hdpi/ic_launcher.png deleted file mode 100644 index 8074c4c5..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-ldpi/collapsed.png b/android-libraries/TreeViewList/res/drawable-ldpi/collapsed.png deleted file mode 100644 index a52e846a..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-ldpi/collapsed.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-ldpi/expanded.png b/android-libraries/TreeViewList/res/drawable-ldpi/expanded.png deleted file mode 100644 index d8b7ab89..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-ldpi/expanded.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-ldpi/ic_launcher.png b/android-libraries/TreeViewList/res/drawable-ldpi/ic_launcher.png deleted file mode 100644 index 1095584e..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-mdpi/collapsed.png b/android-libraries/TreeViewList/res/drawable-mdpi/collapsed.png deleted file mode 100644 index b2355514..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-mdpi/collapsed.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-mdpi/expanded.png b/android-libraries/TreeViewList/res/drawable-mdpi/expanded.png deleted file mode 100644 index f7377cb3..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-mdpi/expanded.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable-mdpi/ic_launcher.png b/android-libraries/TreeViewList/res/drawable-mdpi/ic_launcher.png deleted file mode 100644 index a07c69fa..00000000 Binary files a/android-libraries/TreeViewList/res/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable/divider.xml b/android-libraries/TreeViewList/res/drawable/divider.xml deleted file mode 100644 index 5f379499..00000000 --- a/android-libraries/TreeViewList/res/drawable/divider.xml +++ /dev/null @@ -1,6 +0,0 @@ - - diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background.xml b/android-libraries/TreeViewList/res/drawable/list_selector_background.xml deleted file mode 100644 index 2b21b0c1..00000000 --- a/android-libraries/TreeViewList/res/drawable/list_selector_background.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background_disabled.9.png b/android-libraries/TreeViewList/res/drawable/list_selector_background_disabled.9.png deleted file mode 100644 index bf970b05..00000000 Binary files a/android-libraries/TreeViewList/res/drawable/list_selector_background_disabled.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background_focus.9.png b/android-libraries/TreeViewList/res/drawable/list_selector_background_focus.9.png deleted file mode 100644 index c3e24158..00000000 Binary files a/android-libraries/TreeViewList/res/drawable/list_selector_background_focus.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background_longpress.9.png b/android-libraries/TreeViewList/res/drawable/list_selector_background_longpress.9.png deleted file mode 100644 index 5cbb251a..00000000 Binary files a/android-libraries/TreeViewList/res/drawable/list_selector_background_longpress.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background_pressed.9.png b/android-libraries/TreeViewList/res/drawable/list_selector_background_pressed.9.png deleted file mode 100644 index 02b4e9a5..00000000 Binary files a/android-libraries/TreeViewList/res/drawable/list_selector_background_pressed.9.png and /dev/null differ diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background_transition.xml b/android-libraries/TreeViewList/res/drawable/list_selector_background_transition.xml deleted file mode 100644 index 0dec1335..00000000 --- a/android-libraries/TreeViewList/res/drawable/list_selector_background_transition.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android-libraries/TreeViewList/res/layout/tree_list_item_wrapper.xml b/android-libraries/TreeViewList/res/layout/tree_list_item_wrapper.xml deleted file mode 100644 index 9512a0c8..00000000 --- a/android-libraries/TreeViewList/res/layout/tree_list_item_wrapper.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - diff --git a/android-libraries/TreeViewList/res/values/attrs.xml b/android-libraries/TreeViewList/res/values/attrs.xml deleted file mode 100644 index 30060a4c..00000000 --- a/android-libraries/TreeViewList/res/values/attrs.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/android-libraries/TreeViewList/res/values/styles.xml b/android-libraries/TreeViewList/res/values/styles.xml deleted file mode 100644 index 005c6007..00000000 --- a/android-libraries/TreeViewList/res/values/styles.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/AbstractTreeViewAdapter.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/AbstractTreeViewAdapter.java deleted file mode 100644 index 7f2b366a..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/AbstractTreeViewAdapter.java +++ /dev/null @@ -1,315 +0,0 @@ -package pl.polidea.treeview; - -import android.app.Activity; -import android.content.Context; -import android.database.DataSetObserver; -import android.graphics.drawable.Drawable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.FrameLayout; -import android.widget.FrameLayout.LayoutParams; -import android.widget.ImageView; -import android.widget.ImageView.ScaleType; -import android.widget.LinearLayout; -import android.widget.ListAdapter; - -/** - * Adapter used to feed the table view. - * - * @param - * class for ID of the tree - */ -public abstract class AbstractTreeViewAdapter extends BaseAdapter implements - ListAdapter { - private final TreeStateManager treeStateManager; - private final int numberOfLevels; - private final LayoutInflater layoutInflater; - - private int indentWidth = 0; - private int indicatorGravity = 0; - private Drawable collapsedDrawable; - private Drawable expandedDrawable; - private Drawable indicatorBackgroundDrawable; - private Drawable rowBackgroundDrawable; - - private final OnClickListener indicatorClickListener = new OnClickListener() { - @Override - public void onClick(final View v) { - @SuppressWarnings("unchecked") - final T id = (T) v.getTag(); - expandCollapse(id); - } - }; - - private boolean collapsible; - private final Activity activity; - - public Activity getActivity() { - return activity; - } - - protected TreeStateManager getManager() { - return treeStateManager; - } - - protected void expandCollapse(final T id) { - final TreeNodeInfo info = treeStateManager.getNodeInfo(id); - if (!info.isWithChildren()) { - // ignore - no default action - return; - } - if (info.isExpanded()) { - treeStateManager.collapseChildren(id); - } else { - treeStateManager.expandDirectChildren(id); - } - } - - private void calculateIndentWidth() { - if (expandedDrawable != null) { - indentWidth = Math.max(getIndentWidth(), - expandedDrawable.getIntrinsicWidth()); - } - if (collapsedDrawable != null) { - indentWidth = Math.max(getIndentWidth(), - collapsedDrawable.getIntrinsicWidth()); - } - } - - public AbstractTreeViewAdapter(final Activity activity, - final TreeStateManager treeStateManager, final int numberOfLevels) { - this.activity = activity; - this.treeStateManager = treeStateManager; - this.layoutInflater = (LayoutInflater) activity - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - this.numberOfLevels = numberOfLevels; - this.collapsedDrawable = null; - this.expandedDrawable = null; - this.rowBackgroundDrawable = null; - this.indicatorBackgroundDrawable = null; - } - - @Override - public void registerDataSetObserver(final DataSetObserver observer) { - treeStateManager.registerDataSetObserver(observer); - } - - @Override - public void unregisterDataSetObserver(final DataSetObserver observer) { - treeStateManager.unregisterDataSetObserver(observer); - } - - @Override - public int getCount() { - return treeStateManager.getVisibleCount(); - } - - @Override - public Object getItem(final int position) { - return getItemId(position); - } - - public T getTreeId(final int position) { - return treeStateManager.getVisibleList().get(position); - } - - public TreeNodeInfo getTreeNodeInfo(final int position) { - return treeStateManager.getNodeInfo(getTreeId(position)); - } - - @Override - public boolean hasStableIds() { // NOPMD - return true; - } - - @Override - public int getItemViewType(final int position) { - return getTreeNodeInfo(position).getLevel(); - } - - @Override - public int getViewTypeCount() { - return numberOfLevels; - } - - @Override - public boolean isEmpty() { - return getCount() == 0; - } - - @Override - public boolean areAllItemsEnabled() { // NOPMD - return true; - } - - @Override - public boolean isEnabled(final int position) { // NOPMD - return true; - } - - protected int getTreeListItemWrapperId() { - return R.layout.tree_list_item_wrapper; - } - - @Override - public final View getView(final int position, final View convertView, - final ViewGroup parent) { - final TreeNodeInfo nodeInfo = getTreeNodeInfo(position); - if (convertView == null) { - final LinearLayout layout = (LinearLayout) layoutInflater.inflate( - getTreeListItemWrapperId(), null); - return populateTreeItem(layout, getNewChildView(nodeInfo), - nodeInfo, true); - } else { - final LinearLayout linear = (LinearLayout) convertView; - final FrameLayout frameLayout = (FrameLayout) linear - .findViewById(R.id.treeview_list_item_frame); - final View childView = frameLayout.getChildAt(0); - updateView(childView, nodeInfo); - return populateTreeItem(linear, childView, nodeInfo, false); - } - } - - /** - * Called when new view is to be created. - * - * @param treeNodeInfo - * node info - * @return view that should be displayed as tree content - */ - public abstract View getNewChildView(TreeNodeInfo treeNodeInfo); - - /** - * Called when new view is going to be reused. You should update the view - * and fill it in with the data required to display the new information. You - * can also create a new view, which will mean that the old view will not be - * reused. - * - * @param view - * view that should be updated with the new values - * @param treeNodeInfo - * node info used to populate the view - * @return view to used as row indented content - */ - public abstract View updateView(View view, TreeNodeInfo treeNodeInfo); - - /** - * Retrieves background drawable for the node. - * - * @param treeNodeInfo - * node info - * @return drawable returned as background for the whole row. Might be null, - * then default background is used - */ - public Drawable getBackgroundDrawable(final TreeNodeInfo treeNodeInfo) { // NOPMD - return null; - } - - private Drawable getDrawableOrDefaultBackground(final Drawable r) { - if (r == null) { - return activity.getResources() - .getDrawable(R.drawable.list_selector_background).mutate(); - } else { - return r; - } - } - - public final LinearLayout populateTreeItem(final LinearLayout layout, - final View childView, final TreeNodeInfo nodeInfo, - final boolean newChildView) { - final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo); - layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable) - : individualRowDrawable); - final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( - calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT); - final LinearLayout indicatorLayout = (LinearLayout) layout - .findViewById(R.id.treeview_list_item_image_layout); - indicatorLayout.setGravity(indicatorGravity); - indicatorLayout.setLayoutParams(indicatorLayoutParams); - final ImageView image = (ImageView) layout - .findViewById(R.id.treeview_list_item_image); - image.setImageDrawable(getDrawable(nodeInfo)); - image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable)); - image.setScaleType(ScaleType.CENTER); - image.setTag(nodeInfo.getId()); - if (nodeInfo.isWithChildren() && collapsible) { - image.setOnClickListener(indicatorClickListener); - } else { - image.setOnClickListener(null); - } - layout.setTag(nodeInfo.getId()); - final FrameLayout frameLayout = (FrameLayout) layout - .findViewById(R.id.treeview_list_item_frame); - final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams( - LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); - if (newChildView) { - frameLayout.addView(childView, childParams); - } - frameLayout.setTag(nodeInfo.getId()); - return layout; - } - - protected int calculateIndentation(final TreeNodeInfo nodeInfo) { - return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0)); - } - - private Drawable getDrawable(final TreeNodeInfo nodeInfo) { - if (!nodeInfo.isWithChildren() || !collapsible) { - return getDrawableOrDefaultBackground(indicatorBackgroundDrawable); - } - if (nodeInfo.isExpanded()) { - return expandedDrawable; - } else { - return collapsedDrawable; - } - } - - public void setIndicatorGravity(final int indicatorGravity) { - this.indicatorGravity = indicatorGravity; - } - - public void setCollapsedDrawable(final Drawable collapsedDrawable) { - this.collapsedDrawable = collapsedDrawable; - calculateIndentWidth(); - } - - public void setExpandedDrawable(final Drawable expandedDrawable) { - this.expandedDrawable = expandedDrawable; - calculateIndentWidth(); - } - - public void setIndentWidth(final int indentWidth) { - this.indentWidth = indentWidth; - calculateIndentWidth(); - } - - public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { - this.rowBackgroundDrawable = rowBackgroundDrawable; - } - - public void setIndicatorBackgroundDrawable( - final Drawable indicatorBackgroundDrawable) { - this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; - } - - public void setCollapsible(final boolean collapsible) { - this.collapsible = collapsible; - } - - public void refresh() { - treeStateManager.refresh(); - } - - private int getIndentWidth() { - return indentWidth; - } - - @SuppressWarnings("unchecked") - public void handleItemClick(final View view, final Object id) { - expandCollapse((T) id); - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeNode.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeNode.java deleted file mode 100644 index 6035369f..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeNode.java +++ /dev/null @@ -1,116 +0,0 @@ -package pl.polidea.treeview; - -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - -/** - * Node. It is package protected so that it cannot be used outside. - * - * @param - * type of the identifier used by the tree - */ -class InMemoryTreeNode implements Serializable { - private static final long serialVersionUID = 1L; - private final T id; - private final T parent; - private final int level; - private boolean visible = true; - private final List> children = new LinkedList>(); - private List childIdListCache = null; - - public InMemoryTreeNode(final T id, final T parent, final int level, - final boolean visible) { - super(); - this.id = id; - this.parent = parent; - this.level = level; - this.visible = visible; - } - - public int indexOf(final T id) { - return getChildIdList().indexOf(id); - } - - /** - * Cache is built lasily only if needed. The cache is cleaned on any - * structure change for that node!). - * - * @return list of ids of children - */ - public synchronized List getChildIdList() { - if (childIdListCache == null) { - childIdListCache = new LinkedList(); - for (final InMemoryTreeNode n : children) { - childIdListCache.add(n.getId()); - } - } - return childIdListCache; - } - - public boolean isVisible() { - return visible; - } - - public void setVisible(final boolean visible) { - this.visible = visible; - } - - public int getChildrenListSize() { - return children.size(); - } - - public synchronized InMemoryTreeNode add(final int index, final T child, - final boolean visible) { - childIdListCache = null; - // Note! top levell children are always visible (!) - final InMemoryTreeNode newNode = new InMemoryTreeNode(child, - getId(), getLevel() + 1, getId() == null ? true : visible); - children.add(index, newNode); - return newNode; - } - - /** - * Note. This method should technically return unmodifiable collection, but - * for performance reason on small devices we do not do it. - * - * @return children list - */ - public List> getChildren() { - return children; - } - - public synchronized void clearChildren() { - children.clear(); - childIdListCache = null; - } - - public synchronized void removeChild(final T child) { - final int childIndex = indexOf(child); - if (childIndex != -1) { - children.remove(childIndex); - childIdListCache = null; - } - } - - @Override - public String toString() { - return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent() - + ", level=" + getLevel() + ", visible=" + visible - + ", children=" + children + ", childIdListCache=" - + childIdListCache + "]"; - } - - T getId() { - return id; - } - - T getParent() { - return parent; - } - - int getLevel() { - return level; - } - -} \ No newline at end of file diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeStateManager.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeStateManager.java deleted file mode 100644 index bae675bf..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeStateManager.java +++ /dev/null @@ -1,374 +0,0 @@ -package pl.polidea.treeview; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import android.database.DataSetObserver; - -/** - * In-memory manager of tree state. - * - * @param - * type of identifier - */ -public class InMemoryTreeStateManager implements TreeStateManager { - private static final long serialVersionUID = 1L; - private final Map> allNodes = new HashMap>(); - private final InMemoryTreeNode topSentinel = new InMemoryTreeNode( - null, null, -1, true); - private transient List visibleListCache = null; // lasy initialised - private transient List unmodifiableVisibleList = null; - private boolean visibleByDefault = true; - private final transient Set observers = new HashSet(); - - private synchronized void internalDataSetChanged() { - visibleListCache = null; - unmodifiableVisibleList = null; - for (final DataSetObserver observer : observers) { - observer.onChanged(); - } - } - - /** - * If true new nodes are visible by default. - * - * @param visibleByDefault - * if true, then newly added nodes are expanded by default - */ - public void setVisibleByDefault(final boolean visibleByDefault) { - this.visibleByDefault = visibleByDefault; - } - - private InMemoryTreeNode getNodeFromTreeOrThrow(final T id) { - if (id == null) { - throw new NodeNotInTreeException("(null)"); - } - final InMemoryTreeNode node = allNodes.get(id); - if (node == null) { - throw new NodeNotInTreeException(id.toString()); - } - return node; - } - - private InMemoryTreeNode getNodeFromTreeOrThrowAllowRoot(final T id) { - if (id == null) { - return topSentinel; - } - return getNodeFromTreeOrThrow(id); - } - - private void expectNodeNotInTreeYet(final T id) { - final InMemoryTreeNode node = allNodes.get(id); - if (node != null) { - throw new NodeAlreadyInTreeException(id.toString(), node.toString()); - } - } - - @Override - public synchronized TreeNodeInfo getNodeInfo(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrow(id); - final List> children = node.getChildren(); - boolean expanded = false; - if (!children.isEmpty() && children.get(0).isVisible()) { - expanded = true; - } - return new TreeNodeInfo(id, node.getLevel(), !children.isEmpty(), - node.isVisible(), expanded); - } - - @Override - public synchronized List getChildren(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - return node.getChildIdList(); - } - - @Override - public synchronized T getParent(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - return node.getParent(); - } - - private boolean getChildrenVisibility(final InMemoryTreeNode node) { - boolean visibility; - final List> children = node.getChildren(); - if (children.isEmpty()) { - visibility = visibleByDefault; - } else { - visibility = children.get(0).isVisible(); - } - return visibility; - } - - @Override - public synchronized void addBeforeChild(final T parent, final T newChild, - final T beforeChild) { - expectNodeNotInTreeYet(newChild); - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(parent); - final boolean visibility = getChildrenVisibility(node); - // top nodes are always expanded. - if (beforeChild == null) { - final InMemoryTreeNode added = node.add(0, newChild, visibility); - allNodes.put(newChild, added); - } else { - final int index = node.indexOf(beforeChild); - final InMemoryTreeNode added = node.add(index == -1 ? 0 : index, - newChild, visibility); - allNodes.put(newChild, added); - } - if (visibility) { - internalDataSetChanged(); - } - } - - @Override - public synchronized void addAfterChild(final T parent, final T newChild, - final T afterChild) { - expectNodeNotInTreeYet(newChild); - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(parent); - final boolean visibility = getChildrenVisibility(node); - if (afterChild == null) { - final InMemoryTreeNode added = node.add( - node.getChildrenListSize(), newChild, visibility); - allNodes.put(newChild, added); - } else { - final int index = node.indexOf(afterChild); - final InMemoryTreeNode added = node.add( - index == -1 ? node.getChildrenListSize() : index, newChild, - visibility); - allNodes.put(newChild, added); - } - if (visibility) { - internalDataSetChanged(); - } - } - - @Override - public synchronized void removeNodeRecursively(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - final boolean visibleNodeChanged = removeNodeRecursively(node); - final T parent = node.getParent(); - final InMemoryTreeNode parentNode = getNodeFromTreeOrThrowAllowRoot(parent); - parentNode.removeChild(id); - if (visibleNodeChanged) { - internalDataSetChanged(); - } - } - - private boolean removeNodeRecursively(final InMemoryTreeNode node) { - boolean visibleNodeChanged = false; - for (final InMemoryTreeNode child : node.getChildren()) { - if (removeNodeRecursively(child)) { - visibleNodeChanged = true; - } - } - node.clearChildren(); - if (node.getId() != null) { - allNodes.remove(node.getId()); - if (node.isVisible()) { - visibleNodeChanged = true; - } - } - return visibleNodeChanged; - } - - private void setChildrenVisibility(final InMemoryTreeNode node, - final boolean visible, final boolean recursive) { - for (final InMemoryTreeNode child : node.getChildren()) { - child.setVisible(visible); - if (recursive) { - setChildrenVisibility(child, visible, true); - } - } - } - - @Override - public synchronized void expandDirectChildren(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - setChildrenVisibility(node, true, false); - internalDataSetChanged(); - } - - @Override - public synchronized void expandEverythingBelow(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - setChildrenVisibility(node, true, true); - internalDataSetChanged(); - } - - @Override - public synchronized void collapseChildren(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - if (node == topSentinel) { - for (final InMemoryTreeNode n : topSentinel.getChildren()) { - setChildrenVisibility(n, false, true); - } - } else { - setChildrenVisibility(node, false, true); - } - internalDataSetChanged(); - } - - @Override - public synchronized T getNextSibling(final T id) { - final T parent = getParent(id); - final InMemoryTreeNode parentNode = getNodeFromTreeOrThrowAllowRoot(parent); - boolean returnNext = false; - for (final InMemoryTreeNode child : parentNode.getChildren()) { - if (returnNext) { - return child.getId(); - } - if (child.getId().equals(id)) { - returnNext = true; - } - } - return null; - } - - @Override - public synchronized T getPreviousSibling(final T id) { - final T parent = getParent(id); - final InMemoryTreeNode parentNode = getNodeFromTreeOrThrowAllowRoot(parent); - final T previousSibling = null; - for (final InMemoryTreeNode child : parentNode.getChildren()) { - if (child.getId().equals(id)) { - return previousSibling; - } - } - return null; - } - - @Override - public synchronized boolean isInTree(final T id) { - return allNodes.containsKey(id); - } - - @Override - public synchronized int getVisibleCount() { - return getVisibleList().size(); - } - - @Override - public synchronized List getVisibleList() { - T currentId = null; - if (visibleListCache == null) { - visibleListCache = new ArrayList(allNodes.size()); - do { - currentId = getNextVisible(currentId); - if (currentId == null) { - break; - } else { - visibleListCache.add(currentId); - } - } while (true); - } - if (unmodifiableVisibleList == null) { - unmodifiableVisibleList = Collections - .unmodifiableList(visibleListCache); - } - return unmodifiableVisibleList; - } - - public synchronized T getNextVisible(final T id) { - final InMemoryTreeNode node = getNodeFromTreeOrThrowAllowRoot(id); - if (!node.isVisible()) { - return null; - } - final List> children = node.getChildren(); - if (!children.isEmpty()) { - final InMemoryTreeNode firstChild = children.get(0); - if (firstChild.isVisible()) { - return firstChild.getId(); - } - } - final T sibl = getNextSibling(id); - if (sibl != null) { - return sibl; - } - T parent = node.getParent(); - do { - if (parent == null) { - return null; - } - final T parentSibling = getNextSibling(parent); - if (parentSibling != null) { - return parentSibling; - } - parent = getNodeFromTreeOrThrow(parent).getParent(); - } while (true); - } - - @Override - public synchronized void registerDataSetObserver( - final DataSetObserver observer) { - observers.add(observer); - } - - @Override - public synchronized void unregisterDataSetObserver( - final DataSetObserver observer) { - observers.remove(observer); - } - - @Override - public int getLevel(final T id) { - return getNodeFromTreeOrThrow(id).getLevel(); - } - - @Override - public Integer[] getHierarchyDescription(final T id) { - final int level = getLevel(id); - final Integer[] hierarchy = new Integer[level + 1]; - int currentLevel = level; - T currentId = id; - T parent = getParent(currentId); - while (currentLevel >= 0) { - hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId); - currentId = parent; - parent = getParent(parent); - } - return hierarchy; - } - - private void appendToSb(final StringBuilder sb, final T id) { - if (id != null) { - final TreeNodeInfo node = getNodeInfo(id); - final int indent = node.getLevel() * 4; - final char[] indentString = new char[indent]; - Arrays.fill(indentString, ' '); - sb.append(indentString); - sb.append(node.toString()); - sb.append(Arrays.asList(getHierarchyDescription(id)).toString()); - sb.append("\n"); - } - final List children = getChildren(id); - for (final T child : children) { - appendToSb(sb, child); - } - } - - @Override - public synchronized String toString() { - final StringBuilder sb = new StringBuilder(); - appendToSb(sb, null); - return sb.toString(); - } - - @Override - public synchronized void clear() { - allNodes.clear(); - topSentinel.clearChildren(); - internalDataSetChanged(); - } - - @Override - public void refresh() { - internalDataSetChanged(); - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeAlreadyInTreeException.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeAlreadyInTreeException.java deleted file mode 100644 index 680d0266..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeAlreadyInTreeException.java +++ /dev/null @@ -1,14 +0,0 @@ -package pl.polidea.treeview; - -/** - * The node being added is already in the tree. - * - */ -public class NodeAlreadyInTreeException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public NodeAlreadyInTreeException(final String id, final String oldNode) { - super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode); - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeNotInTreeException.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeNotInTreeException.java deleted file mode 100644 index f20450e1..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeNotInTreeException.java +++ /dev/null @@ -1,15 +0,0 @@ -package pl.polidea.treeview; - -/** - * This exception is thrown when the tree does not contain node requested. - * - */ -public class NodeNotInTreeException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public NodeNotInTreeException(final String id) { - super("The tree does not contain the node specified: " + id); - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeBuilder.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeBuilder.java deleted file mode 100644 index 13b499c4..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeBuilder.java +++ /dev/null @@ -1,126 +0,0 @@ -package pl.polidea.treeview; - -import android.util.Log; - -/** - * Allows to build tree easily in sequential mode (you have to know levels of - * all the tree elements upfront). You should rather use this class rather than - * manager if you build initial tree from some external data source. - * - * @param - */ -public class TreeBuilder { - private static final String TAG = TreeBuilder.class.getSimpleName(); - - private final TreeStateManager manager; - - private T lastAddedId = null; - private int lastLevel = -1; - - public TreeBuilder(final TreeStateManager manager) { - this.manager = manager; - } - - public void clear() { - manager.clear(); - } - - /** - * Adds new relation to existing tree. Child is set as the last child of the - * parent node. Parent has to already exist in the tree, child cannot yet - * exist. This method is mostly useful in case you add entries layer by - * layer - i.e. first top level entries, then children for all parents, then - * grand-children and so on. - * - * @param parent - * parent id - * @param child - * child id - */ - public synchronized void addRelation(final T parent, final T child) { - Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child); - manager.addAfterChild(parent, child, null); - lastAddedId = child; - lastLevel = manager.getLevel(child); - } - - /** - * Adds sequentially new node. Using this method is the simplest way of - * building tree - if you have all the elements in the sequence as they - * should be displayed in fully-expanded tree. You can combine it with add - * relation - for example you can add information about few levels using - * {@link addRelation} and then after the right level is added as parent, - * you can continue adding them using sequential operation. - * - * @param id - * id of the node - * @param level - * its level - */ - public synchronized void sequentiallyAddNextNode(final T id, final int level) { - Log.d(TAG, "Adding sequentiall node " + id + " at level " + level); - if (lastAddedId == null) { - addNodeToParentOneLevelDown(null, id, level); - } else { - if (level <= lastLevel) { - final T parent = findParentAtLevel(lastAddedId, level - 1); - addNodeToParentOneLevelDown(parent, id, level); - } else { - addNodeToParentOneLevelDown(lastAddedId, id, level); - } - } - } - - /** - * Find parent of the node at the level specified. - * - * @param node - * node from which we start - * @param levelToFind - * level which we are looking for - * @return the node found (null if it is topmost node). - */ - private T findParentAtLevel(final T node, final int levelToFind) { - T parent = manager.getParent(node); - while (parent != null) { - if (manager.getLevel(parent) == levelToFind) { - break; - } - parent = manager.getParent(parent); - } - return parent; - } - - /** - * Adds note to parent at the level specified. But it verifies that the - * level is one level down than the parent! - * - * @param parent - * parent parent - * @param id - * new node id - * @param level - * should always be parent's level + 1 - */ - private void addNodeToParentOneLevelDown(final T parent, final T id, - final int level) { - if (parent == null && level != 0) { - throw new TreeConfigurationException("Trying to add new id " + id - + " to top level with level != 0 (" + level + ")"); - } - if (parent != null && manager.getLevel(parent) != level - 1) { - throw new TreeConfigurationException("Trying to add new id " + id - + " <" + level + "> to " + parent + " <" - + manager.getLevel(parent) - + ">. The difference in levels up is bigger than 1."); - } - manager.addAfterChild(parent, id, null); - setLastAdded(id, level); - } - - private void setLastAdded(final T id, final int level) { - lastAddedId = id; - lastLevel = level; - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeConfigurationException.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeConfigurationException.java deleted file mode 100644 index 1fa72e04..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeConfigurationException.java +++ /dev/null @@ -1,15 +0,0 @@ -package pl.polidea.treeview; - -/** - * Exception thrown when there is a problem with configuring tree. - * - */ -public class TreeConfigurationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public TreeConfigurationException(final String detailMessage) { - super(detailMessage); - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeNodeInfo.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeNodeInfo.java deleted file mode 100644 index 32d18dd4..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeNodeInfo.java +++ /dev/null @@ -1,69 +0,0 @@ -package pl.polidea.treeview; - -/** - * Information about the node. - * - * @param - * type of the id for the tree - */ -public class TreeNodeInfo { - private final T id; - private final int level; - private final boolean withChildren; - private final boolean visible; - private final boolean expanded; - - /** - * Creates the node information. - * - * @param id - * id of the node - * @param level - * level of the node - * @param withChildren - * whether the node has children. - * @param visible - * whether the tree node is visible. - * @param expanded - * whether the tree node is expanded - * - */ - public TreeNodeInfo(final T id, final int level, - final boolean withChildren, final boolean visible, - final boolean expanded) { - super(); - this.id = id; - this.level = level; - this.withChildren = withChildren; - this.visible = visible; - this.expanded = expanded; - } - - public T getId() { - return id; - } - - public boolean isWithChildren() { - return withChildren; - } - - public boolean isVisible() { - return visible; - } - - public boolean isExpanded() { - return expanded; - } - - public int getLevel() { - return level; - } - - @Override - public String toString() { - return "TreeNodeInfo [id=" + id + ", level=" + level - + ", withChildren=" + withChildren + ", visible=" + visible - + ", expanded=" + expanded + "]"; - } - -} \ No newline at end of file diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeStateManager.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeStateManager.java deleted file mode 100644 index 781b70e5..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeStateManager.java +++ /dev/null @@ -1,193 +0,0 @@ -package pl.polidea.treeview; - -import java.io.Serializable; -import java.util.List; - -import android.database.DataSetObserver; - -/** - * Manages information about state of the tree. It only keeps information about - * tree elements, not the elements themselves. - * - * @param - * type of the identifier for nodes in the tree - */ -public interface TreeStateManager extends Serializable { - - /** - * Returns array of integers showing the location of the node in hierarchy. - * It corresponds to heading numbering. {0,0,0} in 3 level node is the first - * node {0,0,1} is second leaf (assuming that there are two leaves in first - * subnode of the first node). - * - * @param id - * id of the node - * @return textual description of the hierarchy in tree for the node. - */ - Integer[] getHierarchyDescription(T id); - - /** - * Returns level of the node. - * - * @param id - * id of the node - * @return level in the tree - */ - int getLevel(T id); - - /** - * Returns information about the node. - * - * @param id - * node id - * @return node info - */ - TreeNodeInfo getNodeInfo(T id); - - /** - * Returns children of the node. - * - * @param id - * id of the node or null if asking for top nodes - * @return children of the node - */ - List getChildren(T id); - - /** - * Returns parent of the node. - * - * @param id - * id of the node - * @return parent id or null if no parent - */ - T getParent(T id); - - /** - * Adds the node before child or at the beginning. - * - * @param parent - * id of the parent node. If null - adds at the top level - * @param newChild - * new child to add if null - adds at the beginning. - * @param beforeChild - * child before which to add the new child - */ - void addBeforeChild(T parent, T newChild, T beforeChild); - - /** - * Adds the node after child or at the end. - * - * @param parent - * id of the parent node. If null - adds at the top level. - * @param newChild - * new child to add. If null - adds at the end. - * @param afterChild - * child after which to add the new child - */ - void addAfterChild(T parent, T newChild, T afterChild); - - /** - * Removes the node and all children from the tree. - * - * @param id - * id of the node to remove or null if all nodes are to be - * removed. - */ - void removeNodeRecursively(T id); - - /** - * Expands all children of the node. - * - * @param id - * node which children should be expanded. cannot be null (top - * nodes are always expanded!). - */ - void expandDirectChildren(T id); - - /** - * Expands everything below the node specified. Might be null - then expands - * all. - * - * @param id - * node which children should be expanded or null if all nodes - * are to be expanded. - */ - void expandEverythingBelow(T id); - - /** - * Collapse children. - * - * @param id - * id collapses everything below node specified. If null, - * collapses everything but top-level nodes. - */ - void collapseChildren(T id); - - /** - * Returns next sibling of the node (or null if no further sibling). - * - * @param id - * node id - * @return the sibling (or null if no next) - */ - T getNextSibling(T id); - - /** - * Returns previous sibling of the node (or null if no previous sibling). - * - * @param id - * node id - * @return the sibling (or null if no previous) - */ - T getPreviousSibling(T id); - - /** - * Checks if given node is already in tree. - * - * @param id - * id of the node - * @return true if node is already in tree. - */ - boolean isInTree(T id); - - /** - * Count visible elements. - * - * @return number of currently visible elements. - */ - int getVisibleCount(); - - /** - * Returns visible node list. - * - * @return return the list of all visible nodes in the right sequence - */ - List getVisibleList(); - - /** - * Registers observers with the manager. - * - * @param observer - * observer - */ - void registerDataSetObserver(final DataSetObserver observer); - - /** - * Unregisters observers with the manager. - * - * @param observer - * observer - */ - void unregisterDataSetObserver(final DataSetObserver observer); - - /** - * Cleans tree stored in manager. After this operation the tree is empty. - * - */ - void clear(); - - /** - * Refreshes views connected to the manager. - */ - void refresh(); -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeViewList.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeViewList.java deleted file mode 100644 index fb48ab5c..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeViewList.java +++ /dev/null @@ -1,198 +0,0 @@ -package pl.polidea.treeview; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.Gravity; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ListAdapter; -import android.widget.ListView; - -/** - * Tree view, expandable multi-level. - * - *

- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background
- * attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background
- * 
- */ -public class TreeViewList extends ListView { - private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed; - private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded; - private static final int DEFAULT_INDENT = 0; - private static final int DEFAULT_GRAVITY = Gravity.LEFT - | Gravity.CENTER_VERTICAL; - private Drawable expandedDrawable; - private Drawable collapsedDrawable; - private Drawable rowBackgroundDrawable; - private Drawable indicatorBackgroundDrawable; - private int indentWidth = 0; - private int indicatorGravity = 0; - private AbstractTreeViewAdapter< ? > treeAdapter; - private boolean collapsible; - private boolean handleTrackballPress; - - public TreeViewList(final Context context, final AttributeSet attrs) { - this(context, attrs, R.style.treeViewListStyle); - } - - public TreeViewList(final Context context) { - this(context, null); - } - - public TreeViewList(final Context context, final AttributeSet attrs, - final int defStyle) { - super(context, attrs, defStyle); - parseAttributes(context, attrs); - } - - private void parseAttributes(final Context context, final AttributeSet attrs) { - final TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.TreeViewList); - expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded); - if (expandedDrawable == null) { - expandedDrawable = context.getResources().getDrawable( - DEFAULT_EXPANDED_RESOURCE); - } - collapsedDrawable = a - .getDrawable(R.styleable.TreeViewList_src_collapsed); - if (collapsedDrawable == null) { - collapsedDrawable = context.getResources().getDrawable( - DEFAULT_COLLAPSED_RESOURCE); - } - indentWidth = a.getDimensionPixelSize( - R.styleable.TreeViewList_indent_width, DEFAULT_INDENT); - indicatorGravity = a.getInteger( - R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY); - indicatorBackgroundDrawable = a - .getDrawable(R.styleable.TreeViewList_indicator_background); - rowBackgroundDrawable = a - .getDrawable(R.styleable.TreeViewList_row_background); - collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true); - handleTrackballPress = a.getBoolean( - R.styleable.TreeViewList_handle_trackball_press, true); - } - - @Override - public void setAdapter(final ListAdapter adapter) { - if (!(adapter instanceof AbstractTreeViewAdapter)) { - throw new TreeConfigurationException( - "The adapter is not of TreeViewAdapter type"); - } - treeAdapter = (AbstractTreeViewAdapter< ? >) adapter; - syncAdapter(); - super.setAdapter(treeAdapter); - } - - private void syncAdapter() { - treeAdapter.setCollapsedDrawable(collapsedDrawable); - treeAdapter.setExpandedDrawable(expandedDrawable); - treeAdapter.setIndicatorGravity(indicatorGravity); - treeAdapter.setIndentWidth(indentWidth); - treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable); - treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable); - treeAdapter.setCollapsible(collapsible); - if (handleTrackballPress) { - setOnItemClickListener(new OnItemClickListener() { - @Override - public void onItemClick(final AdapterView< ? > parent, - final View view, final int position, final long id) { - treeAdapter.handleItemClick(view, view.getTag()); - } - }); - } else { - setOnClickListener(null); - } - - } - - public void setExpandedDrawable(final Drawable expandedDrawable) { - this.expandedDrawable = expandedDrawable; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setCollapsedDrawable(final Drawable collapsedDrawable) { - this.collapsedDrawable = collapsedDrawable; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { - this.rowBackgroundDrawable = rowBackgroundDrawable; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setIndicatorBackgroundDrawable( - final Drawable indicatorBackgroundDrawable) { - this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setIndentWidth(final int indentWidth) { - this.indentWidth = indentWidth; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setIndicatorGravity(final int indicatorGravity) { - this.indicatorGravity = indicatorGravity; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setCollapsible(final boolean collapsible) { - this.collapsible = collapsible; - syncAdapter(); - treeAdapter.refresh(); - } - - public void setHandleTrackballPress(final boolean handleTrackballPress) { - this.handleTrackballPress = handleTrackballPress; - syncAdapter(); - treeAdapter.refresh(); - } - - public Drawable getExpandedDrawable() { - return expandedDrawable; - } - - public Drawable getCollapsedDrawable() { - return collapsedDrawable; - } - - public Drawable getRowBackgroundDrawable() { - return rowBackgroundDrawable; - } - - public Drawable getIndicatorBackgroundDrawable() { - return indicatorBackgroundDrawable; - } - - public int getIndentWidth() { - return indentWidth; - } - - public int getIndicatorGravity() { - return indicatorGravity; - } - - public boolean isCollapsible() { - return collapsible; - } - - public boolean isHandleTrackballPress() { - return handleTrackballPress; - } - -} diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/overview.html b/android-libraries/TreeViewList/src/pl/polidea/treeview/overview.html deleted file mode 100644 index bdd09ce9..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/overview.html +++ /dev/null @@ -1,24 +0,0 @@ - - -This is a small utility that provides quite configurable tree view list. -It is based on standard android list view. It separates out different -aspects of the tree: there is a separate list view, tree adapter, tree -state manager and tree state builder. -

-

    -
  • Tree view provides the frame to display the view.
  • -
  • Adapter allows to create visual representation of each tree - node.
  • -
  • State manager provides storage for tree state (connections - between parents and children, collapsed/expanded state). It provides - all the low-level tree manipulation methods.
  • -
  • Tree builder allows to build tree easily providing higher - level methods. The tree can be build either from prepared sequentially - prepared list of nodes (node id, level) or using (parent/child - relationships).
  • -

    For now only in-memory state manager is provided, but Tree State - Manger interface is done in the way that database tree manager even for - large trees is potentially supported. -

- - \ No newline at end of file diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/package-info.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/package-info.java deleted file mode 100644 index a622e091..00000000 --- a/android-libraries/TreeViewList/src/pl/polidea/treeview/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Provides expandable Tree View implementation. - */ -package pl.polidea.treeview; \ No newline at end of file diff --git a/android-libraries/achartengine/.classpath b/android-libraries/achartengine/.classpath deleted file mode 100644 index a4f1e405..00000000 --- a/android-libraries/achartengine/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/android-libraries/achartengine/.project b/android-libraries/achartengine/.project deleted file mode 100644 index fb1c7567..00000000 --- a/android-libraries/achartengine/.project +++ /dev/null @@ -1,33 +0,0 @@ - - - achartengine - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - diff --git a/android-libraries/achartengine/AndroidManifest.xml b/android-libraries/achartengine/AndroidManifest.xml deleted file mode 100644 index 083e05fc..00000000 --- a/android-libraries/achartengine/AndroidManifest.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - \ No newline at end of file diff --git a/android-libraries/achartengine/extra/LICENSE-2.0.txt b/android-libraries/achartengine/extra/LICENSE-2.0.txt deleted file mode 100644 index d6456956..00000000 --- a/android-libraries/achartengine/extra/LICENSE-2.0.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/android-libraries/achartengine/project.properties b/android-libraries/achartengine/project.properties deleted file mode 100644 index 337e8f37..00000000 --- a/android-libraries/achartengine/project.properties +++ /dev/null @@ -1,12 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-7 -android.library=true diff --git a/android-libraries/achartengine/src/org/achartengine/ChartFactory.java b/android-libraries/achartengine/src/org/achartengine/ChartFactory.java deleted file mode 100644 index 301f1a8f..00000000 --- a/android-libraries/achartengine/src/org/achartengine/ChartFactory.java +++ /dev/null @@ -1,708 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine; - -import org.achartengine.chart.BarChart; -import org.achartengine.chart.BarChart.Type; -import org.achartengine.chart.BubbleChart; -import org.achartengine.chart.CombinedXYChart; -import org.achartengine.chart.CubicLineChart; -import org.achartengine.chart.DialChart; -import org.achartengine.chart.DoughnutChart; -import org.achartengine.chart.LineChart; -import org.achartengine.chart.PieChart; -import org.achartengine.chart.RangeBarChart; -import org.achartengine.chart.ScatterChart; -import org.achartengine.chart.TimeChart; -import org.achartengine.chart.XYChart; -import org.achartengine.model.CategorySeries; -import org.achartengine.model.MultipleCategorySeries; -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.DialRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; - -import android.content.Context; -import android.content.Intent; - -/** - * Utility methods for creating chart views or intents. - */ -public class ChartFactory { - /** The key for the chart data. */ - public static final String CHART = "chart"; - - /** The key for the chart graphical activity title. */ - public static final String TITLE = "title"; - - private ChartFactory() { - // empty for now - } - - /** - * Creates a line chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a line chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getLineChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - checkParameters(dataset, renderer); - XYChart chart = new LineChart(dataset, renderer); - return new GraphicalView(context, chart); - } - - /** - * Creates a cubic line chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a line chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getCubeLineChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, float smoothness) { - checkParameters(dataset, renderer); - XYChart chart = new CubicLineChart(dataset, renderer, smoothness); - return new GraphicalView(context, chart); - } - - /** - * Creates a scatter chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a scatter chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getScatterChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - checkParameters(dataset, renderer); - XYChart chart = new ScatterChart(dataset, renderer); - return new GraphicalView(context, chart); - } - - /** - * Creates a bubble chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a scatter chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getBubbleChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - checkParameters(dataset, renderer); - XYChart chart = new BubbleChart(dataset, renderer); - return new GraphicalView(context, chart); - } - - /** - * Creates a time chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param format the date format pattern to be used for displaying the X axis - * date labels. If null, a default appropriate format will be used. - * @return a time chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getTimeChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, String format) { - checkParameters(dataset, renderer); - TimeChart chart = new TimeChart(dataset, renderer); - chart.setDateFormat(format); - return new GraphicalView(context, chart); - } - - /** - * Creates a bar chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param type the bar chart type - * @return a bar chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getBarChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) { - checkParameters(dataset, renderer); - XYChart chart = new BarChart(dataset, renderer, type); - return new GraphicalView(context, chart); - } - - /** - * Creates a range bar chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param type the range bar chart type - * @return a bar chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final GraphicalView getRangeBarChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) { - checkParameters(dataset, renderer); - XYChart chart = new RangeBarChart(dataset, renderer, type); - return new GraphicalView(context, chart); - } - - /** - * Creates a combined XY chart view. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param types the chart types (cannot be null) - * @return a combined XY chart graphical view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if a dataset number of items is different than the number of - * series renderers or number of chart types - */ - public static final GraphicalView getCombinedXYChartView(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, String[] types) { - if (dataset == null || renderer == null || types == null - || dataset.getSeriesCount() != types.length) { - throw new IllegalArgumentException( - "Dataset, renderer and types should be not null and the datasets series count should be equal to the types length"); - } - checkParameters(dataset, renderer); - CombinedXYChart chart = new CombinedXYChart(dataset, renderer, types); - return new GraphicalView(context, chart); - } - - /** - * Creates a pie chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the category series dataset (cannot be null) - * @param renderer the series renderer (cannot be null) - * @return a pie chart view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - public static final GraphicalView getPieChartView(Context context, CategorySeries dataset, - DefaultRenderer renderer) { - checkParameters(dataset, renderer); - PieChart chart = new PieChart(dataset, renderer); - return new GraphicalView(context, chart); - } - - /** - * Creates a dial chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the category series dataset (cannot be null) - * @param renderer the dial renderer (cannot be null) - * @return a pie chart view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - public static final GraphicalView getDialChartView(Context context, CategorySeries dataset, - DialRenderer renderer) { - checkParameters(dataset, renderer); - DialChart chart = new DialChart(dataset, renderer); - return new GraphicalView(context, chart); - } - - /** - * Creates a doughnut chart intent that can be used to start the graphical - * view activity. - * - * @param context the context - * @param dataset the multiple category series dataset (cannot be null) - * @param renderer the series renderer (cannot be null) - * @return a pie chart view - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - public static final GraphicalView getDoughnutChartView(Context context, - MultipleCategorySeries dataset, DefaultRenderer renderer) { - checkParameters(dataset, renderer); - DoughnutChart chart = new DoughnutChart(dataset, renderer); - return new GraphicalView(context, chart); - } - - /** - * - * Creates a line chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a line chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getLineChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer) { - return getLineChartIntent(context, dataset, renderer, ""); - } - - /** - * - * Creates a cubic line chart intent that can be used to start the graphical - * view activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a line chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getCubicLineChartIntent(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, float smoothness) { - return getCubicLineChartIntent(context, dataset, renderer, smoothness, ""); - } - - /** - * Creates a scatter chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a scatter chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getScatterChartIntent(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - return getScatterChartIntent(context, dataset, renderer, ""); - } - - /** - * Creates a bubble chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @return a scatter chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getBubbleChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer) { - return getBubbleChartIntent(context, dataset, renderer, ""); - } - - /** - * Creates a time chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param format the date format pattern to be used for displaying the X axis - * date labels. If null, a default appropriate format will be used. - * @return a time chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getTimeChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer, String format) { - return getTimeChartIntent(context, dataset, renderer, format, ""); - } - - /** - * Creates a bar chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param type the bar chart type - * @return a bar chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getBarChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer, Type type) { - return getBarChartIntent(context, dataset, renderer, type, ""); - } - - /** - * Creates a line chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param activityTitle the graphical chart activity title. If this is null, - * then the title bar will be hidden. If a blank title is passed in, - * then the title bar will be the default. Pass in any other string - * to set a custom title. - * @return a line chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getLineChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - XYChart chart = new LineChart(dataset, renderer); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a line chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param activityTitle the graphical chart activity title. If this is null, - * then the title bar will be hidden. If a blank title is passed in, - * then the title bar will be the default. Pass in any other string - * to set a custom title. - * @return a line chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getCubicLineChartIntent(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, float smoothness, - String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - XYChart chart = new CubicLineChart(dataset, renderer, smoothness); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a scatter chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param activityTitle the graphical chart activity title - * @return a scatter chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getScatterChartIntent(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - XYChart chart = new ScatterChart(dataset, renderer); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a bubble chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param activityTitle the graphical chart activity title - * @return a scatter chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getBubbleChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - XYChart chart = new BubbleChart(dataset, renderer); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a time chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param format the date format pattern to be used for displaying the X axis - * date labels. If null, a default appropriate format will be used - * @param activityTitle the graphical chart activity title - * @return a time chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getTimeChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer, String format, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - TimeChart chart = new TimeChart(dataset, renderer); - chart.setDateFormat(format); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a bar chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param type the bar chart type - * @param activityTitle the graphical chart activity title - * @return a bar chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getBarChartIntent(Context context, XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer, Type type, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - BarChart chart = new BarChart(dataset, renderer, type); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a range bar chart intent that can be used to start the graphical - * view activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param type the range bar chart type - * @param activityTitle the graphical chart activity title - * @return a range bar chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - public static final Intent getRangeBarChartIntent(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type, - String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - RangeBarChart chart = new RangeBarChart(dataset, renderer, type); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a combined XY chart intent that can be used to start the graphical - * view activity. - * - * @param context the context - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @param types the chart types (cannot be null) - * @param activityTitle the graphical chart activity title - * @return a combined XY chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if a dataset number of items is different than the number of - * series renderers or number of chart types - */ - public static final Intent getCombinedXYChartIntent(Context context, - XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, String[] types, - String activityTitle) { - if (dataset == null || renderer == null || types == null - || dataset.getSeriesCount() != types.length) { - throw new IllegalArgumentException( - "Datasets, renderers and types should be not null and the datasets series count should be equal to the types length"); - } - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - CombinedXYChart chart = new CombinedXYChart(dataset, renderer, types); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a pie chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the category series dataset (cannot be null) - * @param renderer the series renderer (cannot be null) - * @param activityTitle the graphical chart activity title - * @return a pie chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - public static final Intent getPieChartIntent(Context context, CategorySeries dataset, - DefaultRenderer renderer, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - PieChart chart = new PieChart(dataset, renderer); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a doughnut chart intent that can be used to start the graphical - * view activity. - * - * @param context the context - * @param dataset the multiple category series dataset (cannot be null) - * @param renderer the series renderer (cannot be null) - * @param activityTitle the graphical chart activity title - * @return a pie chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - public static final Intent getDoughnutChartIntent(Context context, - MultipleCategorySeries dataset, DefaultRenderer renderer, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - DoughnutChart chart = new DoughnutChart(dataset, renderer); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Creates a dial chart intent that can be used to start the graphical view - * activity. - * - * @param context the context - * @param dataset the category series dataset (cannot be null) - * @param renderer the dial renderer (cannot be null) - * @param activityTitle the graphical chart activity title - * @return a dial chart intent - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - public static final Intent getDialChartIntent(Context context, CategorySeries dataset, - DialRenderer renderer, String activityTitle) { - checkParameters(dataset, renderer); - Intent intent = new Intent(context, GraphicalActivity.class); - DialChart chart = new DialChart(dataset, renderer); - intent.putExtra(CHART, chart); - intent.putExtra(TITLE, activityTitle); - return intent; - } - - /** - * Checks the validity of the dataset and renderer parameters. - * - * @param dataset the multiple series dataset (cannot be null) - * @param renderer the multiple series renderer (cannot be null) - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset and the renderer don't include the same number of - * series - */ - private static void checkParameters(XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer) { - if (dataset == null || renderer == null - || dataset.getSeriesCount() != renderer.getSeriesRendererCount()) { - throw new IllegalArgumentException( - "Dataset and renderer should be not null and should have the same number of series"); - } - } - - /** - * Checks the validity of the dataset and renderer parameters. - * - * @param dataset the category series dataset (cannot be null) - * @param renderer the series renderer (cannot be null) - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - private static void checkParameters(CategorySeries dataset, DefaultRenderer renderer) { - if (dataset == null || renderer == null - || dataset.getItemCount() != renderer.getSeriesRendererCount()) { - throw new IllegalArgumentException( - "Dataset and renderer should be not null and the dataset number of items should be equal to the number of series renderers"); - } - } - - /** - * Checks the validity of the dataset and renderer parameters. - * - * @param dataset the category series dataset (cannot be null) - * @param renderer the series renderer (cannot be null) - * @throws IllegalArgumentException if dataset is null or renderer is null or - * if the dataset number of items is different than the number of - * series renderers - */ - private static void checkParameters(MultipleCategorySeries dataset, DefaultRenderer renderer) { - if (dataset == null || renderer == null - || !checkMultipleSeriesItems(dataset, renderer.getSeriesRendererCount())) { - throw new IllegalArgumentException( - "Titles and values should be not null and the dataset number of items should be equal to the number of series renderers"); - } - } - - private static boolean checkMultipleSeriesItems(MultipleCategorySeries dataset, int value) { - int count = dataset.getCategoriesCount(); - boolean equal = true; - for (int k = 0; k < count && equal; k++) { - equal = dataset.getValues(k).length == dataset.getTitles(k).length; - } - return equal; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/GraphicalActivity.java b/android-libraries/achartengine/src/org/achartengine/GraphicalActivity.java deleted file mode 100644 index 56c190ae..00000000 --- a/android-libraries/achartengine/src/org/achartengine/GraphicalActivity.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine; - -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); - 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-libraries/achartengine/src/org/achartengine/GraphicalView.java b/android-libraries/achartengine/src/org/achartengine/GraphicalView.java deleted file mode 100644 index e9aebff5..00000000 --- a/android-libraries/achartengine/src/org/achartengine/GraphicalView.java +++ /dev/null @@ -1,337 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.RoundChart; -import org.achartengine.chart.XYChart; -import org.achartengine.model.Point; -import org.achartengine.model.SeriesSelection; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.tools.FitZoom; -import org.achartengine.tools.PanListener; -import org.achartengine.tools.Zoom; -import org.achartengine.tools.ZoomListener; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.RectF; -import android.os.Build; -import android.os.Handler; -import android.view.MotionEvent; -import android.view.View; - -/** - * The view that encapsulates the graphical chart. - */ -public class GraphicalView extends View { - /** The chart to be drawn. */ - private AbstractChart mChart; - /** The chart renderer. */ - private DefaultRenderer mRenderer; - /** The view bounds. */ - private Rect mRect = new Rect(); - /** The user interface thread handler. */ - private Handler mHandler; - /** The zoom buttons rectangle. */ - private RectF mZoomR = new RectF(); - /** The zoom in icon. */ - private Bitmap zoomInImage; - /** The zoom out icon. */ - private Bitmap zoomOutImage; - /** The fit zoom icon. */ - private Bitmap fitZoomImage; - /** The zoom area size. */ - private int zoomSize = 50; - /** The zoom buttons background color. */ - private static final int ZOOM_BUTTONS_COLOR = Color.argb(175, 150, 150, 150); - /** The zoom in tool. */ - private Zoom mZoomIn; - /** The zoom out tool. */ - private Zoom mZoomOut; - /** The fit zoom tool. */ - private FitZoom mFitZoom; - /** The paint to be used when drawing the chart. */ - private Paint mPaint = new Paint(); - /** The touch handler. */ - private ITouchHandler mTouchHandler; - /** The old x coordinate. */ - private float oldX; - /** The old y coordinate. */ - private float oldY; - - /** - * Creates a new graphical view. - * - * @param context the context - * @param chart the chart to be drawn - */ - public GraphicalView(Context context, AbstractChart chart) { - super(context); - mChart = chart; - mHandler = new Handler(); - if (mChart instanceof XYChart) { - mRenderer = ((XYChart) mChart).getRenderer(); - } else { - mRenderer = ((RoundChart) mChart).getRenderer(); - } - if (mRenderer.isZoomButtonsVisible()) { - zoomInImage = BitmapFactory.decodeStream(GraphicalView.class - .getResourceAsStream("image/zoom_in.png")); - zoomOutImage = BitmapFactory.decodeStream(GraphicalView.class - .getResourceAsStream("image/zoom_out.png")); - fitZoomImage = BitmapFactory.decodeStream(GraphicalView.class - .getResourceAsStream("image/zoom-1.png")); - } - - if (mRenderer instanceof XYMultipleSeriesRenderer - && ((XYMultipleSeriesRenderer) mRenderer).getMarginsColor() == XYMultipleSeriesRenderer.NO_COLOR) { - ((XYMultipleSeriesRenderer) mRenderer).setMarginsColor(mPaint.getColor()); - } - if (mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible() - || mRenderer.isExternalZoomEnabled()) { - mZoomIn = new Zoom(mChart, true, mRenderer.getZoomRate()); - mZoomOut = new Zoom(mChart, false, mRenderer.getZoomRate()); - mFitZoom = new FitZoom(mChart); - } - int version = 7; - try { - version = Integer.valueOf(Build.VERSION.SDK); - } catch (Exception e) { - // do nothing - } - if (version < 7) { - mTouchHandler = new TouchHandlerOld(this, mChart); - } else { - mTouchHandler = new TouchHandler(this, mChart); - } - } - - /** - * Returns the current series selection object. - * - * @return the series selection - */ - public SeriesSelection getCurrentSeriesAndPoint() { - return mChart.getSeriesAndPointForScreenCoordinate(new Point(oldX, oldY)); - } - - /** - * Transforms the currently selected screen point to a real point. - * - * @param scale the scale - * @return the currently selected real point - */ - public double[] toRealPoint(int scale) { - if (mChart instanceof XYChart) { - XYChart chart = (XYChart) mChart; - return chart.toRealPoint(oldX, oldY, scale); - } - return null; - } - - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - canvas.getClipBounds(mRect); - int top = mRect.top; - int left = mRect.left; - int width = mRect.width(); - int height = mRect.height(); - if (mRenderer.isInScroll()) { - top = 0; - left = 0; - width = getMeasuredWidth(); - height = getMeasuredHeight(); - } - mChart.draw(canvas, left, top, width, height, mPaint); - if (mRenderer != null && mRenderer.isZoomEnabled() && mRenderer.isZoomButtonsVisible()) { - mPaint.setColor(ZOOM_BUTTONS_COLOR); - zoomSize = Math.max(zoomSize, Math.min(width, height) / 7); - mZoomR.set(left + width - zoomSize * 3, top + height - zoomSize * 0.775f, left + width, top - + height); - canvas.drawRoundRect(mZoomR, zoomSize / 3, zoomSize / 3, mPaint); - float buttonY = top + height - zoomSize * 0.625f; - canvas.drawBitmap(zoomInImage, left + width - zoomSize * 2.75f, buttonY, null); - canvas.drawBitmap(zoomOutImage, left + width - zoomSize * 1.75f, buttonY, null); - canvas.drawBitmap(fitZoomImage, left + width - zoomSize * 0.75f, buttonY, null); - } - } - - /** - * Sets the zoom rate. - * - * @param rate the zoom rate - */ - public void setZoomRate(float rate) { - if (mZoomIn != null && mZoomOut != null) { - mZoomIn.setZoomRate(rate); - mZoomOut.setZoomRate(rate); - } - } - - /** - * Do a chart zoom in. - */ - public void zoomIn() { - if (mZoomIn != null) { - mZoomIn.apply(Zoom.ZOOM_AXIS_XY); - repaint(); - } - } - - /** - * Do a chart zoom out. - */ - public void zoomOut() { - if (mZoomOut != null) { - mZoomOut.apply(Zoom.ZOOM_AXIS_XY); - repaint(); - } - } - - - - /** - * Do a chart zoom reset / fit zoom. - */ - public void zoomReset() { - if (mFitZoom != null) { - mFitZoom.apply(); - mZoomIn.notifyZoomResetListeners(); - repaint(); - } - } - - /** - * Adds a new zoom listener. - * - * @param listener zoom listener - */ - public void addZoomListener(ZoomListener listener, boolean onButtons, boolean onPinch) { - if (onButtons) { - if (mZoomIn != null) { - mZoomIn.addZoomListener(listener); - mZoomOut.addZoomListener(listener); - } - if (onPinch) { - mTouchHandler.addZoomListener(listener); - } - } - } - - /** - * Removes a zoom listener. - * - * @param listener zoom listener - */ - public synchronized void removeZoomListener(ZoomListener listener) { - if (mZoomIn != null) { - mZoomIn.removeZoomListener(listener); - mZoomOut.removeZoomListener(listener); - } - mTouchHandler.removeZoomListener(listener); - } - - /** - * Adds a new pan listener. - * - * @param listener pan listener - */ - public void addPanListener(PanListener listener) { - mTouchHandler.addPanListener(listener); - } - - /** - * Removes a pan listener. - * - * @param listener pan listener - */ - public void removePanListener(PanListener listener) { - mTouchHandler.removePanListener(listener); - } - - protected RectF getZoomRectangle() { - return mZoomR; - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - if (event.getAction() == MotionEvent.ACTION_DOWN) { - // save the x and y so they can be used in the click and long press - // listeners - oldX = event.getX(); - oldY = event.getY(); - } - if (mRenderer != null && (mRenderer.isPanEnabled() || mRenderer.isZoomEnabled())) { - if (mTouchHandler.handleTouch(event)) { - return true; - } - } - return super.onTouchEvent(event); - } - - /** - * Schedule a view content repaint. - */ - public void repaint() { - mHandler.post(new Runnable() { - public void run() { - invalidate(); - } - }); - } - - /** - * Schedule a view content repaint, in the specified rectangle area. - * - * @param left the left position of the area to be repainted - * @param top the top position of the area to be repainted - * @param right the right position of the area to be repainted - * @param bottom the bottom position of the area to be repainted - */ - public void repaint(final int left, final int top, final int right, final int bottom) { - mHandler.post(new Runnable() { - public void run() { - invalidate(left, top, right, bottom); - } - }); - } - - /** - * Saves the content of the graphical view to a bitmap. - * - * @return the bitmap - */ - public Bitmap toBitmap() { - setDrawingCacheEnabled(false); - if (!isDrawingCacheEnabled()) { - setDrawingCacheEnabled(true); - } - if (mRenderer.isApplyBackgroundColor()) { - setDrawingCacheBackgroundColor(mRenderer.getBackgroundColor()); - } - setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); - return getDrawingCache(true); - } - -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/ITouchHandler.java b/android-libraries/achartengine/src/org/achartengine/ITouchHandler.java deleted file mode 100644 index 4debe964..00000000 --- a/android-libraries/achartengine/src/org/achartengine/ITouchHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine; - -import org.achartengine.tools.PanListener; -import org.achartengine.tools.ZoomListener; - -import android.view.MotionEvent; - -/** - * The interface to be implemented by the touch handlers. - */ -public interface ITouchHandler { - /** - * Handles the touch event. - * - * @param event the touch event - * @return true if the event was handled - */ - boolean handleTouch(MotionEvent event); - - /** - * Adds a new zoom listener. - * - * @param listener zoom listener - */ - void addZoomListener(ZoomListener listener); - - /** - * Removes a zoom listener. - * - * @param listener zoom listener - */ - void removeZoomListener(ZoomListener listener); - - /** - * Adds a new pan listener. - * - * @param listener pan listener - */ - void addPanListener(PanListener listener); - - /** - * Removes a pan listener. - * - * @param listener pan listener - */ - void removePanListener(PanListener listener); - -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/TouchHandler.java b/android-libraries/achartengine/src/org/achartengine/TouchHandler.java deleted file mode 100644 index a06d05d6..00000000 --- a/android-libraries/achartengine/src/org/achartengine/TouchHandler.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.RoundChart; -import org.achartengine.chart.XYChart; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.tools.Pan; -import org.achartengine.tools.PanListener; -import org.achartengine.tools.Zoom; -import org.achartengine.tools.ZoomListener; - -import android.graphics.RectF; -import android.view.MotionEvent; - -/** - * The main handler of the touch events. - */ -public class TouchHandler implements ITouchHandler { - /** The chart renderer. */ - private DefaultRenderer mRenderer; - /** The old x coordinate. */ - private float oldX; - /** The old y coordinate. */ - private float oldY; - /** The old x2 coordinate. */ - private float oldX2; - /** The old y2 coordinate. */ - private float oldY2; - /** The zoom buttons rectangle. */ - private RectF zoomR = new RectF(); - /** The pan tool. */ - private Pan mPan; - /** The zoom for the pinch gesture. */ - private Zoom mPinchZoom; - /** The graphical view. */ - private GraphicalView graphicalView; - - /** - * Creates a new graphical view. - * - * @param view the graphical view - * @param chart the chart to be drawn - */ - public TouchHandler(GraphicalView view, AbstractChart chart) { - graphicalView = view; - zoomR = graphicalView.getZoomRectangle(); - if (chart instanceof XYChart) { - mRenderer = ((XYChart) chart).getRenderer(); - } else { - mRenderer = ((RoundChart) chart).getRenderer(); - } - if (mRenderer.isPanEnabled()) { - mPan = new Pan(chart); - } - if (mRenderer.isZoomEnabled()) { - mPinchZoom = new Zoom(chart, true, 1); - } - } - - /** - * Handles the touch event. - * - * @param event the touch event - */ - public boolean handleTouch(MotionEvent event) { - int action = event.getAction(); - if (mRenderer != null && action == MotionEvent.ACTION_MOVE) { - if (oldX >= 0 || oldY >= 0) { - float newX = event.getX(0); - float newY = event.getY(0); - if (event.getPointerCount() > 1 && (oldX2 >= 0 || oldY2 >= 0) && mRenderer.isZoomEnabled()) { - float newX2 = event.getX(1); - float newY2 = event.getY(1); - float newDeltaX = Math.abs(newX - newX2); - float newDeltaY = Math.abs(newY - newY2); - float oldDeltaX = Math.abs(oldX - oldX2); - float oldDeltaY = Math.abs(oldY - oldY2); - float zoomRate = 1; - - float tan1 = Math.abs(newY - oldY) / Math.abs(newX - oldX); - float tan2 = Math.abs(newY2 - oldY2) / Math.abs(newX2 - oldX2); - if ( tan1 <= 0.577 && tan2 <= 0.577) { - // horizontal pinch zoom, |deltaY| / |deltaX| is [0 ~ 0.577], 0.577 is the approximate value of tan(Pi/6) - zoomRate = newDeltaX / oldDeltaX; - if (zoomRate > 0.909 && zoomRate < 1.1) { - mPinchZoom.setZoomRate(zoomRate); - mPinchZoom.apply(Zoom.ZOOM_AXIS_X); - } - } else if ( tan1 >= 1.732 && tan2 >= 1.732 ) { - // pinch zoom vertically, |deltaY| / |deltaX| is [1.732 ~ infinity], 1.732 is the approximate value of tan(Pi/3) - zoomRate = newDeltaY / oldDeltaY; - if (zoomRate > 0.909 && zoomRate < 1.1) { - mPinchZoom.setZoomRate(zoomRate); - mPinchZoom.apply(Zoom.ZOOM_AXIS_Y); - } - } else if ( (tan1 > 0.577 && tan1 < 1.732) && (tan2 > 0.577 && tan2 < 1.732) ){ - // pinch zoom diagonally - if (Math.abs(newX - oldX) >= Math.abs(newY - oldY)) { - zoomRate = newDeltaX / oldDeltaX; - } else { - zoomRate = newDeltaY / oldDeltaY; - } - if (zoomRate > 0.909 && zoomRate < 1.1) { - mPinchZoom.setZoomRate(zoomRate); - mPinchZoom.apply(Zoom.ZOOM_AXIS_XY); - } - } - oldX2 = newX2; - oldY2 = newY2; - } else if (mRenderer.isPanEnabled()) { - mPan.apply(oldX, oldY, newX, newY); - oldX2 = 0; - oldY2 = 0; - } - oldX = newX; - oldY = newY; - graphicalView.repaint(); - return true; - } - } else if (action == MotionEvent.ACTION_DOWN) { - oldX = event.getX(0); - oldY = event.getY(0); - if (mRenderer != null && mRenderer.isZoomEnabled() && zoomR.contains(oldX, oldY)) { - if (oldX < zoomR.left + zoomR.width() / 3) { - graphicalView.zoomIn(); - } else if (oldX < zoomR.left + zoomR.width() * 2 / 3) { - graphicalView.zoomOut(); - } else { - graphicalView.zoomReset(); - } - return true; - } - } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { - oldX = 0; - oldY = 0; - oldX2 = 0; - oldY2 = 0; - if (action == MotionEvent.ACTION_POINTER_UP) { - oldX = -1; - oldY = -1; - } - } - return !mRenderer.isClickEnabled(); - } - - /** - * Adds a new zoom listener. - * - * @param listener zoom listener - */ - public void addZoomListener(ZoomListener listener) { - if (mPinchZoom != null) { - mPinchZoom.addZoomListener(listener); - } - } - - /** - * Removes a zoom listener. - * - * @param listener zoom listener - */ - public void removeZoomListener(ZoomListener listener) { - if (mPinchZoom != null) { - mPinchZoom.removeZoomListener(listener); - } - } - - /** - * Adds a new pan listener. - * - * @param listener pan listener - */ - public void addPanListener(PanListener listener) { - if (mPan != null) { - mPan.addPanListener(listener); - } - } - - /** - * Removes a pan listener. - * - * @param listener pan listener - */ - public void removePanListener(PanListener listener) { - if (mPan != null) { - mPan.removePanListener(listener); - } - } -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/TouchHandlerOld.java b/android-libraries/achartengine/src/org/achartengine/TouchHandlerOld.java deleted file mode 100644 index 38b4f227..00000000 --- a/android-libraries/achartengine/src/org/achartengine/TouchHandlerOld.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.RoundChart; -import org.achartengine.chart.XYChart; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.tools.Pan; -import org.achartengine.tools.PanListener; -import org.achartengine.tools.ZoomListener; - -import android.graphics.RectF; -import android.view.MotionEvent; - -/** - * A handler implementation for touch events for older platforms. - */ -public class TouchHandlerOld implements ITouchHandler { - /** The chart renderer. */ - private DefaultRenderer mRenderer; - /** The old x coordinate. */ - private float oldX; - /** The old y coordinate. */ - private float oldY; - /** The zoom buttons rectangle. */ - private RectF zoomR = new RectF(); - /** The pan tool. */ - private Pan mPan; - /** The graphical view. */ - private GraphicalView graphicalView; - - /** - * Creates an implementation of the old version of the touch handler. - * - * @param view the graphical view - * @param chart the chart to be drawn - */ - public TouchHandlerOld(GraphicalView view, AbstractChart chart) { - graphicalView = view; - zoomR = graphicalView.getZoomRectangle(); - if (chart instanceof XYChart) { - mRenderer = ((XYChart) chart).getRenderer(); - } else { - mRenderer = ((RoundChart) chart).getRenderer(); - } - if (mRenderer.isPanEnabled()) { - mPan = new Pan(chart); - } - } - - public boolean handleTouch(MotionEvent event) { - int action = event.getAction(); - if (mRenderer != null && action == MotionEvent.ACTION_MOVE) { - if (oldX >= 0 || oldY >= 0) { - float newX = event.getX(); - float newY = event.getY(); - if (mRenderer.isPanEnabled()) { - mPan.apply(oldX, oldY, newX, newY); - } - oldX = newX; - oldY = newY; - graphicalView.repaint(); - return true; - } - } else if (action == MotionEvent.ACTION_DOWN) { - oldX = event.getX(); - oldY = event.getY(); - if (mRenderer != null && mRenderer.isZoomEnabled() && zoomR.contains(oldX, oldY)) { - if (oldX < zoomR.left + zoomR.width() / 3) { - graphicalView.zoomIn(); - } else if (oldX < zoomR.left + zoomR.width() * 2 / 3) { - graphicalView.zoomOut(); - } else { - graphicalView.zoomReset(); - } - return true; - } - } else if (action == MotionEvent.ACTION_UP) { - oldX = 0; - oldY = 0; - } - return !mRenderer.isClickEnabled(); - } - - /** - * Adds a new zoom listener. - * - * @param listener zoom listener - */ - public void addZoomListener(ZoomListener listener) { - } - - /** - * Removes a zoom listener. - * - * @param listener zoom listener - */ - public void removeZoomListener(ZoomListener listener) { - } - - /** - * Adds a new pan listener. - * - * @param listener pan listener - */ - public void addPanListener(PanListener listener) { - if (mPan != null) { - mPan.addPanListener(listener); - } - } - - /** - * Removes a pan listener. - * - * @param listener pan listener - */ - public void removePanListener(PanListener listener) { - if (mPan != null) { - mPan.removePanListener(listener); - } - } - -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/chart/AbstractChart.java b/android-libraries/achartengine/src/org/achartengine/chart/AbstractChart.java deleted file mode 100644 index f99a5c2a..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/AbstractChart.java +++ /dev/null @@ -1,475 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.io.Serializable; -import java.util.List; - -import org.achartengine.model.Point; -import org.achartengine.model.SeriesSelection; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation; -import org.achartengine.util.MathHelper; - -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Paint.Align; -import android.graphics.Paint.Style; -import android.graphics.Path; -import android.graphics.Rect; -import android.graphics.RectF; - -/** - * An abstract class to be implemented by the chart rendering classes. - */ -public abstract class AbstractChart implements Serializable { - /** - * The graphical representation of the chart. - * - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param height the height of the view to draw to - * @param paint the paint - */ - public abstract void draw(Canvas canvas, int x, int y, int width, int height, Paint paint); - - /** - * Draws the chart background. - * - * @param renderer the chart renderer - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param height the height of the view to draw to - * @param paint the paint used for drawing - * @param newColor if a new color is to be used - * @param color the color to be used - */ - protected void drawBackground(DefaultRenderer renderer, Canvas canvas, int x, int y, int width, - int height, Paint paint, boolean newColor, int color) { - if (renderer.isApplyBackgroundColor() || newColor) { - if (newColor) { - paint.setColor(color); - } else { - paint.setColor(renderer.getBackgroundColor()); - } - paint.setStyle(Style.FILL); - canvas.drawRect(x, y, x + width, y + height, paint); - } - } - - /** - * Draws the chart legend. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param titles the titles to go to the legend - * @param left the left X value of the area to draw to - * @param right the right X value of the area to draw to - * @param y the y value of the area to draw to - * @param width the width of the area to draw to - * @param height the height of the area to draw to - * @param legendSize the legend size - * @param paint the paint to be used for drawing - * @param calculate if only calculating the legend size - * - * @return the legend height - */ - protected int drawLegend(Canvas canvas, DefaultRenderer renderer, String[] titles, int left, - int right, int y, int width, int height, int legendSize, Paint paint, boolean calculate) { - float size = 32; - if (renderer.isShowLegend()) { - float currentX = left; - float currentY = y + height - legendSize + size; - paint.setTextAlign(Align.LEFT); - paint.setTextSize(renderer.getLegendTextSize()); - int sLength = Math.min(titles.length, renderer.getSeriesRendererCount()); - for (int i = 0; i < sLength; i++) { - final float lineSize = getLegendShapeWidth(i); - String text = titles[i]; - if (titles.length == renderer.getSeriesRendererCount()) { - paint.setColor(renderer.getSeriesRendererAt(i).getColor()); - } else { - paint.setColor(Color.LTGRAY); - } - float[] widths = new float[text.length()]; - paint.getTextWidths(text, widths); - float sum = 0; - for (float value : widths) { - sum += value; - } - float extraSize = lineSize + 10 + sum; - float currentWidth = currentX + extraSize; - - if (i > 0 && getExceed(currentWidth, renderer, right, width)) { - currentX = left; - currentY += renderer.getLegendTextSize(); - size += renderer.getLegendTextSize(); - currentWidth = currentX + extraSize; - } - if (getExceed(currentWidth, renderer, right, width)) { - float maxWidth = right - currentX - lineSize - 10; - if (isVertical(renderer)) { - maxWidth = width - currentX - lineSize - 10; - } - int nr = paint.breakText(text, true, maxWidth, widths); - text = text.substring(0, nr) + "..."; - } - if (!calculate) { - drawLegendShape(canvas, renderer.getSeriesRendererAt(i), currentX, currentY, i, paint); - drawString(canvas, text, currentX + lineSize + 5, currentY + 5, paint); - } - currentX += extraSize; - } - } - return Math.round(size + renderer.getLegendTextSize()); - } - - /** - * Draw a multiple lines string. - * - * @param canvas the canvas to paint to - * @param text the text to be painted - * @param x the x value of the area to draw to - * @param y the y value of the area to draw to - * @param paint the paint to be used for drawing - */ - protected void drawString(Canvas canvas, String text, float x, float y, Paint paint) { - String[] lines = text.split("\n"); - Rect rect = new Rect(); - int yOff = 0; - for (int i = 0; i < lines.length; ++i) { - canvas.drawText(lines[i], x, y + yOff, paint); - paint.getTextBounds(lines[i], 0, lines[i].length(), rect); - yOff = yOff + rect.height() + 5; // space between lines is 5 - } - } - - /** - * Calculates if the current width exceeds the total width. - * - * @param currentWidth the current width - * @param renderer the renderer - * @param right the right side pixel value - * @param width the total width - * @return if the current width exceeds the total width - */ - protected boolean getExceed(float currentWidth, DefaultRenderer renderer, int right, int width) { - boolean exceed = currentWidth > right; - if (isVertical(renderer)) { - exceed = currentWidth > width; - } - return exceed; - } - - /** - * Checks if the current chart is rendered as vertical. - * - * @param renderer the renderer - * @return if the chart is rendered as a vertical one - */ - public boolean isVertical(DefaultRenderer renderer) { - return renderer instanceof XYMultipleSeriesRenderer - && ((XYMultipleSeriesRenderer) renderer).getOrientation() == Orientation.VERTICAL; - } - - /** - * Makes sure the fraction digit is not displayed, if not needed. - * - * @param label the input label value - * @return the label without the useless fraction digit - */ - protected String getLabel(double label) { - String text = ""; - if (label == Math.round(label)) { - text = Math.round(label) + ""; - } else { - text = label + ""; - } - return text; - } - - private static float[] calculateDrawPoints(float p1x, float p1y, float p2x, float p2y, - int screenHeight, int screenWidth) { - float drawP1x; - float drawP1y; - float drawP2x; - float drawP2y; - - if (p1y > screenHeight) { - // Intersection with the top of the screen - float m = (p2y - p1y) / (p2x - p1x); - drawP1x = (screenHeight - p1y + m * p1x) / m; - drawP1y = screenHeight; - - if (drawP1x < 0) { - // If Intersection is left of the screen we calculate the intersection - // with the left border - drawP1x = 0; - drawP1y = p1y - m * p1x; - } else if (drawP1x > screenWidth) { - // If Intersection is right of the screen we calculate the intersection - // with the right border - drawP1x = screenWidth; - drawP1y = m * screenWidth + p1y - m * p1x; - } - } else if (p1y < 0) { - float m = (p2y - p1y) / (p2x - p1x); - drawP1x = (-p1y + m * p1x) / m; - drawP1y = 0; - if (drawP1x < 0) { - drawP1x = 0; - drawP1y = p1y - m * p1x; - } else if (drawP1x > screenWidth) { - drawP1x = screenWidth; - drawP1y = m * screenWidth + p1y - m * p1x; - } - } else { - // If the point is in the screen use it - drawP1x = p1x; - drawP1y = p1y; - } - - if (p2y > screenHeight) { - float m = (p2y - p1y) / (p2x - p1x); - drawP2x = (screenHeight - p1y + m * p1x) / m; - drawP2y = screenHeight; - if (drawP2x < 0) { - drawP2x = 0; - drawP2y = p1y - m * p1x; - } else if (drawP2x > screenWidth) { - drawP2x = screenWidth; - drawP2y = m * screenWidth + p1y - m * p1x; - } - } else if (p2y < 0) { - float m = (p2y - p1y) / (p2x - p1x); - drawP2x = (-p1y + m * p1x) / m; - drawP2y = 0; - if (drawP2x < 0) { - drawP2x = 0; - drawP2y = p1y - m * p1x; - } else if (drawP2x > screenWidth) { - drawP2x = screenWidth; - drawP2y = m * screenWidth + p1y - m * p1x; - } - } else { - // If the point is in the screen use it - drawP2x = p2x; - drawP2y = p2y; - } - - return new float[] { drawP1x, drawP1y, drawP2x, drawP2y }; - } - - /** - * The graphical representation of a path. - * - * @param canvas the canvas to paint to - * @param points the points that are contained in the path to paint - * @param paint the paint to be used for painting - * @param circular if the path ends with the start point - */ - protected void drawPath(Canvas canvas, float[] points, Paint paint, boolean circular) { - Path path = new Path(); - int height = canvas.getHeight(); - int width = canvas.getWidth(); - - float[] tempDrawPoints; - if (points.length < 4) { - return; - } - tempDrawPoints = calculateDrawPoints(points[0], points[1], points[2], points[3], height, width); - path.moveTo(tempDrawPoints[0], tempDrawPoints[1]); - path.lineTo(tempDrawPoints[2], tempDrawPoints[3]); - - for (int i = 4; i < points.length; i += 2) { - if ((points[i - 1] < 0 && points[i + 1] < 0) - || (points[i - 1] > height && points[i + 1] > height)) { - continue; - } - tempDrawPoints = calculateDrawPoints(points[i - 2], points[i - 1], points[i], points[i + 1], - height, width); - if (!circular) { - path.moveTo(tempDrawPoints[0], tempDrawPoints[1]); - } - path.lineTo(tempDrawPoints[2], tempDrawPoints[3]); - } - if (circular) { - path.lineTo(points[0], points[1]); - } - canvas.drawPath(path, paint); - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public abstract int getLegendShapeWidth(int seriesIndex); - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public abstract void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, - float y, int seriesIndex, Paint paint); - - /** - * Calculates the best text to fit into the available space. - * - * @param text the entire text - * @param width the width to fit the text into - * @param paint the paint - * @return the text to fit into the space - */ - private String getFitText(String text, float width, Paint paint) { - String newText = text; - int length = text.length(); - int diff = 0; - while (paint.measureText(newText) > width && diff < length) { - diff++; - newText = text.substring(0, length - diff) + "..."; - } - if (diff == length) { - newText = "..."; - } - return newText; - } - - /** - * Calculates the current legend size. - * - * @param renderer the renderer - * @param defaultHeight the default height - * @param extraHeight the added extra height - * @return the legend size - */ - protected int getLegendSize(DefaultRenderer renderer, int defaultHeight, float extraHeight) { - int legendSize = renderer.getLegendHeight(); - if (renderer.isShowLegend() && legendSize == 0) { - legendSize = defaultHeight; - } - if (!renderer.isShowLegend() && renderer.isShowLabels()) { - legendSize = (int) (renderer.getLabelsTextSize() * 4 / 3 + extraHeight); - } - return legendSize; - } - - /** - * Draws a text label. - * - * @param canvas the canvas - * @param labelText the label text - * @param renderer the renderer - * @param prevLabelsBounds the previous rendered label bounds - * @param centerX the round chart center on X axis - * @param centerY the round chart center on Y axis - * @param shortRadius the short radius for the round chart - * @param longRadius the long radius for the round chart - * @param currentAngle the current angle - * @param angle the label extra angle - * @param left the left side - * @param right the right side - * @param color the label color - * @param paint the paint - * @param line if a line to the label should be drawn - */ - protected void drawLabel(Canvas canvas, String labelText, DefaultRenderer renderer, - List prevLabelsBounds, int centerX, int centerY, float shortRadius, float longRadius, - float currentAngle, float angle, int left, int right, int color, Paint paint, boolean line) { - if (renderer.isShowLabels()) { - paint.setColor(color); - double rAngle = Math.toRadians(90 - (currentAngle + angle / 2)); - double sinValue = Math.sin(rAngle); - double cosValue = Math.cos(rAngle); - int x1 = Math.round(centerX + (float) (shortRadius * sinValue)); - int y1 = Math.round(centerY + (float) (shortRadius * cosValue)); - int x2 = Math.round(centerX + (float) (longRadius * sinValue)); - int y2 = Math.round(centerY + (float) (longRadius * cosValue)); - - float size = renderer.getLabelsTextSize(); - float extra = Math.max(size / 2, 10); - paint.setTextAlign(Align.LEFT); - if (x1 > x2) { - extra = -extra; - paint.setTextAlign(Align.RIGHT); - } - float xLabel = x2 + extra; - float yLabel = y2; - float width = right - xLabel; - if (x1 > x2) { - width = xLabel - left; - } - labelText = getFitText(labelText, width, paint); - float widthLabel = paint.measureText(labelText); - boolean okBounds = false; - while (!okBounds && line) { - boolean intersects = false; - int length = prevLabelsBounds.size(); - for (int j = 0; j < length && !intersects; j++) { - RectF prevLabelBounds = prevLabelsBounds.get(j); - if (prevLabelBounds.intersects(xLabel, yLabel, xLabel + widthLabel, yLabel + size)) { - intersects = true; - yLabel = Math.max(yLabel, prevLabelBounds.bottom); - } - } - okBounds = !intersects; - } - - if (line) { - y2 = (int) (yLabel - size / 2); - canvas.drawLine(x1, y1, x2, y2, paint); - canvas.drawLine(x2, y2, x2 + extra, y2, paint); - } else { - paint.setTextAlign(Align.CENTER); - } - canvas.drawText(labelText, xLabel, yLabel, paint); - if (line) { - prevLabelsBounds.add(new RectF(xLabel, yLabel, xLabel + widthLabel, yLabel + size)); - } - } - } - - public boolean isNullValue(double value) { - return Double.isNaN(value) || Double.isInfinite(value) || value == MathHelper.NULL_VALUE; - } - - /** - * Given screen coordinates, returns the series and point indexes of a chart - * element. If there is no chart element (line, point, bar, etc) at those - * coordinates, null is returned. - * - * @param screenPoint - * @return the series and point indexes - */ - public SeriesSelection getSeriesAndPointForScreenCoordinate(Point screenPoint) { - return null; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/BarChart.java b/android-libraries/achartengine/src/org/achartengine/chart/BarChart.java deleted file mode 100644 index d5d0fb23..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/BarChart.java +++ /dev/null @@ -1,329 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.RectF; -import android.graphics.drawable.GradientDrawable; -import android.graphics.drawable.GradientDrawable.Orientation; - -/** - * The bar chart rendering class. - */ -public class BarChart extends XYChart { - /** The constant to identify this chart type. */ - public static final String TYPE = "Bar"; - /** The legend shape width. */ - private static final int SHAPE_WIDTH = 12; - /** The chart type. */ - protected Type mType = Type.DEFAULT; - - /** - * The bar chart type enum. - */ - public enum Type { - DEFAULT, STACKED; - } - - BarChart() { - } - - BarChart(Type type) { - mType = type; - } - - /** - * Builds a new bar chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - * @param type the bar chart type - */ - public BarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) { - super(dataset, renderer); - mType = type; - } - - @Override - protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, - float yAxisValue, int seriesIndex, int startIndex) { - int seriesNr = mDataset.getSeriesCount(); - int length = points.length; - ClickableArea[] ret = new ClickableArea[length / 2]; - float halfDiffX = getHalfDiffX(points, length, seriesNr); - for (int i = 0; i < length; i += 2) { - float x = points[i]; - float y = points[i + 1]; - if (mType == Type.STACKED) { - ret[i / 2] = new ClickableArea(new RectF(x - halfDiffX, y, x + halfDiffX, yAxisValue), - values[i], values[i + 1]); - } else { - float startX = x - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX; - ret[i / 2] = new ClickableArea(new RectF(startX, y, startX + 2 * halfDiffX, yAxisValue), - values[i], values[i + 1]); - } - } - return ret; - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { - int seriesNr = mDataset.getSeriesCount(); - int length = points.length; - paint.setColor(seriesRenderer.getColor()); - paint.setStyle(Style.FILL); - float halfDiffX = getHalfDiffX(points, length, seriesNr); - for (int i = 0; i < length; i += 2) { - float x = points[i]; - float y = points[i + 1]; - drawBar(canvas, x, yAxisValue, x, y, halfDiffX, seriesNr, seriesIndex, paint); - } - paint.setColor(seriesRenderer.getColor()); - } - - /** - * Draws a bar. - * - * @param canvas the canvas - * @param xMin the X axis minimum - * @param yMin the Y axis minimum - * @param xMax the X axis maximum - * @param yMax the Y axis maximum - * @param halfDiffX half the size of a bar - * @param seriesNr the total number of series - * @param seriesIndex the current series index - * @param paint the paint - */ - protected void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, - float halfDiffX, int seriesNr, int seriesIndex, Paint paint) { - int scale = mDataset.getSeriesAt(seriesIndex).getScaleNumber(); - if (mType == Type.STACKED) { - drawBar(canvas, xMin - halfDiffX, yMax, xMax + halfDiffX, yMin, scale, seriesIndex, paint); - } else { - float startX = xMin - seriesNr * halfDiffX + seriesIndex * 2 * halfDiffX; - drawBar(canvas, startX, yMax, startX + 2 * halfDiffX, yMin, scale, seriesIndex, paint); - } - } - - /** - * Draws a bar. - * - * @param canvas the canvas - * @param xMin the X axis minimum - * @param yMin the Y axis minimum - * @param xMax the X axis maximum - * @param yMax the Y axis maximum - * @param scale the scale index - * @param seriesIndex the current series index - * @param paint the paint - */ - private void drawBar(Canvas canvas, float xMin, float yMin, float xMax, float yMax, int scale, - int seriesIndex, Paint paint) { - SimpleSeriesRenderer renderer = mRenderer.getSeriesRendererAt(seriesIndex); - if (renderer.isGradientEnabled()) { - float minY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStopValue() }, scale)[1]; - float maxY = (float) toScreenPoint(new double[] { 0, renderer.getGradientStartValue() }, - scale)[1]; - float gradientMinY = Math.max(minY, Math.min(yMin, yMax)); - float gradientMaxY = Math.min(maxY, Math.max(yMin, yMax)); - int gradientMinColor = renderer.getGradientStopColor(); - int gradientMaxColor = renderer.getGradientStartColor(); - int gradientStartColor = gradientMaxColor; - int gradientStopColor = gradientMinColor; - - if (yMin < minY) { - paint.setColor(gradientMinColor); - canvas.drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), - Math.round(gradientMinY), paint); - } else { - gradientStopColor = getGradientPartialColor(gradientMinColor, gradientMaxColor, - (maxY - gradientMinY) / (maxY - minY)); - } - if (yMax > maxY) { - paint.setColor(gradientMaxColor); - canvas.drawRect(Math.round(xMin), Math.round(gradientMaxY), Math.round(xMax), - Math.round(yMax), paint); - } else { - gradientStartColor = getGradientPartialColor(gradientMaxColor, gradientMinColor, - (gradientMaxY - minY) / (maxY - minY)); - } - GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] { - gradientStartColor, gradientStopColor }); - gradient.setBounds(Math.round(xMin), Math.round(gradientMinY), Math.round(xMax), - Math.round(gradientMaxY)); - gradient.draw(canvas); - } else { - if (Math.abs(yMin - yMax) < 1) { - if (yMin < yMax) { - yMax = yMin + 1; - } else { - yMax = yMin - 1; - } - } - canvas - .drawRect(Math.round(xMin), Math.round(yMin), Math.round(xMax), Math.round(yMax), paint); - } - } - - private int getGradientPartialColor(int minColor, int maxColor, float fraction) { - int alpha = Math.round(fraction * Color.alpha(minColor) + (1 - fraction) - * Color.alpha(maxColor)); - int r = Math.round(fraction * Color.red(minColor) + (1 - fraction) * Color.red(maxColor)); - int g = Math.round(fraction * Color.green(minColor) + (1 - fraction) * Color.green(maxColor)); - int b = Math.round(fraction * Color.blue(minColor) + (1 - fraction) * Color.blue((maxColor))); - return Color.argb(alpha, r, g, b); - } - - /** - * The graphical representation of the series values as text. - * - * @param canvas the canvas to paint to - * @param series the series to be painted - * @param renderer the series renderer - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer, - Paint paint, float[] points, int seriesIndex, int startIndex) { - int seriesNr = mDataset.getSeriesCount(); - float halfDiffX = getHalfDiffX(points, points.length, seriesNr); - for (int i = 0; i < points.length; i += 2) { - int index = startIndex + i / 2; - double value = series.getY(index); - if (!isNullValue(value)) { - float x = points[i]; - if (mType == Type.DEFAULT) { - x += seriesIndex * 2 * halfDiffX - (seriesNr - 1.5f) * halfDiffX; - } - if (value >= 0) { - drawText(canvas, getLabel(value), x, points[i + 1] - renderer.getChartValuesSpacing(), - paint, 0); - } else { - drawText(canvas, getLabel(value), x, points[i + 1] + renderer.getChartValuesTextSize() - + renderer.getChartValuesSpacing() - 3, paint, 0); - } - } - } - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return SHAPE_WIDTH; - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - float halfShapeWidth = SHAPE_WIDTH / 2; - canvas.drawRect(x, y - halfShapeWidth, x + SHAPE_WIDTH, y + halfShapeWidth, paint); - } - - /** - * Calculates and returns the half-distance in the graphical representation of - * 2 consecutive points. - * - * @param points the points - * @param length the points length - * @param seriesNr the series number - * @return the calculated half-distance value - */ - protected float getHalfDiffX(float[] points, int length, int seriesNr) { - int div = length; - if (length > 2) { - div = length - 2; - } - float halfDiffX = (points[length - 2] - points[0]) / div; - if (halfDiffX == 0) { - halfDiffX = 10; - } - - if (mType != Type.STACKED) { - halfDiffX /= seriesNr; - } - return (float) (halfDiffX / (getCoeficient() * (1 + mRenderer.getBarSpacing()))); - } - - /** - * Returns the value of a constant used to calculate the half-distance. - * - * @return the constant value - */ - protected float getCoeficient() { - return 1f; - } - - /** - * Returns if the chart should display the null values. - * - * @return if null values should be rendered - */ - protected boolean isRenderNullValues() { - return true; - } - - /** - * Returns the default axis minimum. - * - * @return the default axis minimum - */ - public double getDefaultMinimum() { - return 0; - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/BubbleChart.java b/android-libraries/achartengine/src/org/achartengine/chart/BubbleChart.java deleted file mode 100644 index f3125713..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/BubbleChart.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYValueSeries; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.RectF; - -/** - * The bubble chart rendering class. - */ -public class BubbleChart extends XYChart { - /** The constant to identify this chart type. */ - public static final String TYPE = "Bubble"; - /** The legend shape width. */ - private static final int SHAPE_WIDTH = 10; - /** The minimum bubble size. */ - private static final int MIN_BUBBLE_SIZE = 2; - /** The maximum bubble size. */ - private static final int MAX_BUBBLE_SIZE = 20; - - BubbleChart() { - } - - /** - * Builds a new bubble chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - */ - public BubbleChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - super(dataset, renderer); - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { - XYSeriesRenderer renderer = (XYSeriesRenderer) seriesRenderer; - paint.setColor(renderer.getColor()); - paint.setStyle(Style.FILL); - int length = points.length; - XYValueSeries series = (XYValueSeries) mDataset.getSeriesAt(seriesIndex); - double max = series.getMaxValue(); - double coef = MAX_BUBBLE_SIZE / max; - for (int i = 0; i < length; i += 2) { - double size = series.getValue(startIndex + i / 2) * coef + MIN_BUBBLE_SIZE; - drawCircle(canvas, paint, points[i], points[i + 1], (float) size); - } - } - - @Override - protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, - float yAxisValue, int seriesIndex, int startIndex) { - int length = points.length; - XYValueSeries series = (XYValueSeries) mDataset.getSeriesAt(seriesIndex); - double max = series.getMaxValue(); - double coef = MAX_BUBBLE_SIZE / max; - ClickableArea[] ret = new ClickableArea[length / 2]; - for (int i = 0; i < length; i += 2) { - double size = series.getValue(startIndex + i / 2) * coef + MIN_BUBBLE_SIZE; - ret[i / 2] = new ClickableArea(new RectF(points[i] - (float) size, points[i + 1] - - (float) size, points[i] + (float) size, points[i + 1] + (float) size), values[i], - values[i + 1]); - } - return ret; - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return SHAPE_WIDTH; - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - paint.setStyle(Style.FILL); - drawCircle(canvas, paint, x + SHAPE_WIDTH, y, 3); - } - - /** - * The graphical representation of a circle point shape. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param radius the bubble radius - */ - private void drawCircle(Canvas canvas, Paint paint, float x, float y, float radius) { - canvas.drawCircle(x, y, radius, paint); - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } - -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/chart/ClickableArea.java b/android-libraries/achartengine/src/org/achartengine/chart/ClickableArea.java deleted file mode 100644 index d2d306ca..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/ClickableArea.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import android.graphics.RectF; - -public class ClickableArea { - private RectF rect; - private double x; - private double y; - - public ClickableArea(RectF rect, double x, double y) { - super(); - this.rect = rect; - this.x = x; - this.y = y; - } - - public RectF getRect() { - return rect; - } - - public double getX() { - return x; - } - - public double getY() { - return y; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/CombinedXYChart.java b/android-libraries/achartengine/src/org/achartengine/chart/CombinedXYChart.java deleted file mode 100644 index d684c3a2..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/CombinedXYChart.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.util.List; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation; - -import android.graphics.Canvas; -import android.graphics.Paint; - -/** - * The combined XY chart rendering class. - */ -public class CombinedXYChart extends XYChart { - /** The embedded XY charts. */ - private XYChart[] mCharts; - /** The supported charts for being combined. */ - private Class[] xyChartTypes = new Class[] { TimeChart.class, LineChart.class, - CubicLineChart.class, BarChart.class, BubbleChart.class, ScatterChart.class, - RangeBarChart.class, RangeStackedBarChart.class }; - - /** - * Builds a new combined XY chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - * @param types the XY chart types - */ - public CombinedXYChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, - String[] types) { - super(dataset, renderer); - int length = types.length; - mCharts = new XYChart[length]; - for (int i = 0; i < length; i++) { - try { - mCharts[i] = getXYChart(types[i]); - } catch (Exception e) { - // ignore - } - if (mCharts[i] == null) { - throw new IllegalArgumentException("Unknown chart type " + types[i]); - } else { - XYMultipleSeriesDataset newDataset = new XYMultipleSeriesDataset(); - newDataset.addSeries(dataset.getSeriesAt(i)); - XYMultipleSeriesRenderer newRenderer = new XYMultipleSeriesRenderer(); - // TODO: copy other parameters here - newRenderer.setBarSpacing(renderer.getBarSpacing()); - newRenderer.setPointSize(renderer.getPointSize()); - int scale = dataset.getSeriesAt(i).getScaleNumber(); - if (renderer.isMinXSet(scale)) { - newRenderer.setXAxisMin(renderer.getXAxisMin(scale)); - } - if (renderer.isMaxXSet(scale)) { - newRenderer.setXAxisMax(renderer.getXAxisMax(scale)); - } - if (renderer.isMinYSet(scale)) { - newRenderer.setYAxisMin(renderer.getYAxisMin(scale)); - } - if (renderer.isMaxYSet(scale)) { - newRenderer.setYAxisMax(renderer.getYAxisMax(scale)); - } - newRenderer.addSeriesRenderer(renderer.getSeriesRendererAt(i)); - mCharts[i].setDatasetRenderer(newDataset, newRenderer); - } - } - } - - /** - * Returns a chart instance based on the provided type. - * - * @param type the chart type - * @return an instance of a chart implementation - * @throws IllegalAccessException - * @throws InstantiationException - */ - private XYChart getXYChart(String type) throws IllegalAccessException, InstantiationException { - XYChart chart = null; - int length = xyChartTypes.length; - for (int i = 0; i < length && chart == null; i++) { - XYChart newChart = (XYChart) xyChartTypes[i].newInstance(); - if (type.equals(newChart.getChartType())) { - chart = newChart; - } - } - return chart; - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { - mCharts[seriesIndex].setScreenR(getScreenR()); - mCharts[seriesIndex].setCalcRange(getCalcRange(mDataset.getSeriesAt(seriesIndex) - .getScaleNumber()), 0); - mCharts[seriesIndex].drawSeries(canvas, paint, points, seriesRenderer, yAxisValue, 0, - startIndex); - } - - @Override - protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, - float yAxisValue, int seriesIndex, int startIndex) { - return mCharts[seriesIndex].clickableAreasForPoints(points, values, yAxisValue, 0, startIndex); - } - - @Override - protected void drawSeries(XYSeries series, Canvas canvas, Paint paint, List pointsList, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, Orientation or, - int startIndex) { - mCharts[seriesIndex].setScreenR(getScreenR()); - mCharts[seriesIndex].setCalcRange(getCalcRange(mDataset.getSeriesAt(seriesIndex) - .getScaleNumber()), 0); - mCharts[seriesIndex].drawSeries(series, canvas, paint, pointsList, seriesRenderer, yAxisValue, - 0, or, startIndex); - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return mCharts[seriesIndex].getLegendShapeWidth(0); - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - mCharts[seriesIndex].drawLegendShape(canvas, renderer, x, y, 0, paint); - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return "Combined"; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/CubicLineChart.java b/android-libraries/achartengine/src/org/achartengine/chart/CubicLineChart.java deleted file mode 100644 index 2011318f..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/CubicLineChart.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.Point; -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.renderer.XYMultipleSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Path; - -/** - * The interpolated (cubic) line chart rendering class. - */ -public class CubicLineChart extends LineChart { - /** The chart type. */ - public static final String TYPE = "Cubic"; - - private float firstMultiplier; - - private float secondMultiplier; - - private Point p1 = new Point(); - - private Point p2 = new Point(); - - private Point p3 = new Point(); - - public CubicLineChart() { - // default is to have first control point at about 33% of the distance, - firstMultiplier = 0.33f; - // and the next at 66% of the distance. - secondMultiplier = 1 - firstMultiplier; - } - - /** - * Builds a cubic line chart. - * - * @param dataset the dataset - * @param renderer the renderer - * @param smoothness smoothness determines how smooth the curve should be, - * range [0->0.5] super smooth, 0.5, means that it might not get - * close to control points if you have random data // less smooth, - * (close to 0) means that it will most likely touch all control // - * points - */ - public CubicLineChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, - float smoothness) { - super(dataset, renderer); - firstMultiplier = smoothness; - secondMultiplier = 1 - firstMultiplier; - } - - @Override - protected void drawPath(Canvas canvas, float[] points, Paint paint, boolean circular) { - Path p = new Path(); - float x = points[0]; - float y = points[1]; - p.moveTo(x, y); - - int length = points.length; - if (circular) { - length -= 4; - } - - for (int i = 0; i < length; i += 2) { - int nextIndex = i + 2 < length ? i + 2 : i; - int nextNextIndex = i + 4 < length ? i + 4 : nextIndex; - calc(points, p1, i, nextIndex, secondMultiplier); - p2.setX(points[nextIndex]); - p2.setY(points[nextIndex + 1]); - calc(points, p3, nextIndex, nextNextIndex, firstMultiplier); - // From last point, approaching x1/y1 and x2/y2 and ends up at x3/y3 - p.cubicTo(p1.getX(), p1.getY(), p2.getX(), p2.getY(), p3.getX(), p3.getY()); - } - if (circular) { - for (int i = length; i < length + 4; i += 2) { - p.lineTo(points[i], points[i + 1]); - } - p.lineTo(points[0], points[1]); - } - canvas.drawPath(p, paint); - } - - private void calc(float[] points, Point result, int index1, int index2, final float multiplier) { - float p1x = points[index1]; - float p1y = points[index1 + 1]; - float p2x = points[index2]; - float p2y = points[index2 + 1]; - - float diffX = p2x - p1x; // p2.x - p1.x; - float diffY = p2y - p1y; // p2.y - p1.y; - result.setX(p1x + (diffX * multiplier)); - result.setY(p1y + (diffY * multiplier)); - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/DialChart.java b/android-libraries/achartengine/src/org/achartengine/chart/DialChart.java deleted file mode 100644 index ebfcbbb1..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/DialChart.java +++ /dev/null @@ -1,236 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.CategorySeries; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.DialRenderer; -import org.achartengine.renderer.DialRenderer.Type; -import org.achartengine.util.MathHelper; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Align; -import android.graphics.Paint.Style; - -/** - * The dial chart rendering class. - */ -public class DialChart extends RoundChart { - /** The radius of the needle. */ - private static final int NEEDLE_RADIUS = 10; - /** The series renderer. */ - private DialRenderer mRenderer; - - /** - * Builds a new dial chart instance. - * - * @param dataset the series dataset - * @param renderer the dial renderer - */ - public DialChart(CategorySeries dataset, DialRenderer renderer) { - super(dataset, renderer); - mRenderer = renderer; - } - - /** - * The graphical representation of the dial chart. - * - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param height the height of the view to draw to - * @param paint the paint - */ - @Override - public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) { - paint.setAntiAlias(mRenderer.isAntialiasing()); - paint.setStyle(Style.FILL); - paint.setTextSize(mRenderer.getLabelsTextSize()); - int legendSize = getLegendSize(mRenderer, height / 5, 0); - int left = x; - int top = y; - int right = x + width; - - int sLength = mDataset.getItemCount(); - String[] titles = new String[sLength]; - for (int i = 0; i < sLength; i++) { - titles[i] = mDataset.getCategory(i); - } - - if (mRenderer.isFitLegend()) { - legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, - paint, true); - } - int bottom = y + height - legendSize; - drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR); - - int mRadius = Math.min(Math.abs(right - left), Math.abs(bottom - top)); - int radius = (int) (mRadius * 0.35 * mRenderer.getScale()); - if (mCenterX == NO_VALUE) { - mCenterX = (left + right) / 2; - } - if (mCenterY == NO_VALUE) { - mCenterY = (bottom + top) / 2; - } - float shortRadius = radius * 0.9f; - float longRadius = radius * 1.1f; - double min = mRenderer.getMinValue(); - double max = mRenderer.getMaxValue(); - double angleMin = mRenderer.getAngleMin(); - double angleMax = mRenderer.getAngleMax(); - if (!mRenderer.isMinValueSet() || !mRenderer.isMaxValueSet()) { - int count = mRenderer.getSeriesRendererCount(); - for (int i = 0; i < count; i++) { - double value = mDataset.getValue(i); - if (!mRenderer.isMinValueSet()) { - min = Math.min(min, value); - } - if (!mRenderer.isMaxValueSet()) { - max = Math.max(max, value); - } - } - } - if (min == max) { - min = min * 0.5; - max = max * 1.5; - } - - paint.setColor(mRenderer.getLabelsColor()); - double minorTicks = mRenderer.getMinorTicksSpacing(); - double majorTicks = mRenderer.getMajorTicksSpacing(); - if (minorTicks == MathHelper.NULL_VALUE) { - minorTicks = (max - min) / 30; - } - if (majorTicks == MathHelper.NULL_VALUE) { - majorTicks = (max - min) / 10; - } - drawTicks(canvas, min, max, angleMin, angleMax, mCenterX, mCenterY, longRadius, radius, - minorTicks, paint, false); - drawTicks(canvas, min, max, angleMin, angleMax, mCenterX, mCenterY, longRadius, shortRadius, - majorTicks, paint, true); - - int count = mRenderer.getSeriesRendererCount(); - for (int i = 0; i < count; i++) { - double angle = getAngleForValue(mDataset.getValue(i), angleMin, angleMax, min, max); - paint.setColor(mRenderer.getSeriesRendererAt(i).getColor()); - boolean type = mRenderer.getVisualTypeForIndex(i) == Type.ARROW; - drawNeedle(canvas, angle, mCenterX, mCenterY, shortRadius, type, paint); - } - drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, paint, false); - drawTitle(canvas, x, y, width, paint); - } - - /** - * Returns the angle for a specific chart value. - * - * @param value the chart value - * @param minAngle the minimum chart angle value - * @param maxAngle the maximum chart angle value - * @param min the minimum chart value - * @param max the maximum chart value - * @return the angle - */ - private double getAngleForValue(double value, double minAngle, double maxAngle, double min, - double max) { - double angleDiff = maxAngle - minAngle; - double diff = max - min; - return Math.toRadians(minAngle + (value - min) * angleDiff / diff); - } - - /** - * Draws the chart tick lines. - * - * @param canvas the canvas - * @param min the minimum chart value - * @param max the maximum chart value - * @param minAngle the minimum chart angle value - * @param maxAngle the maximum chart angle value - * @param centerX the center x value - * @param centerY the center y value - * @param longRadius the long radius - * @param shortRadius the short radius - * @param ticks the tick spacing - * @param paint the paint settings - * @param labels paint the labels - * @return the angle - */ - private void drawTicks(Canvas canvas, double min, double max, double minAngle, double maxAngle, - int centerX, int centerY, double longRadius, double shortRadius, double ticks, Paint paint, - boolean labels) { - for (double i = min; i <= max; i += ticks) { - double angle = getAngleForValue(i, minAngle, maxAngle, min, max); - double sinValue = Math.sin(angle); - double cosValue = Math.cos(angle); - int x1 = Math.round(centerX + (float) (shortRadius * sinValue)); - int y1 = Math.round(centerY + (float) (shortRadius * cosValue)); - int x2 = Math.round(centerX + (float) (longRadius * sinValue)); - int y2 = Math.round(centerY + (float) (longRadius * cosValue)); - canvas.drawLine(x1, y1, x2, y2, paint); - if (labels) { - paint.setTextAlign(Align.LEFT); - if (x1 <= x2) { - paint.setTextAlign(Align.RIGHT); - } - String text = i + ""; - if (Math.round(i) == (long) i) { - text = (long) i + ""; - } - canvas.drawText(text, x1, y1, paint); - } - } - } - - /** - * Returns the angle for a specific chart value. - * - * @param canvas the canvas - * @param angle the needle angle value - * @param centerX the center x value - * @param centerY the center y value - * @param radius the radius - * @param arrow if a needle or an arrow to be painted - * @param paint the paint settings - * @return the angle - */ - private void drawNeedle(Canvas canvas, double angle, int centerX, int centerY, double radius, - boolean arrow, Paint paint) { - double diff = Math.toRadians(90); - int needleSinValue = (int) (NEEDLE_RADIUS * Math.sin(angle - diff)); - int needleCosValue = (int) (NEEDLE_RADIUS * Math.cos(angle - diff)); - int needleX = (int) (radius * Math.sin(angle)); - int needleY = (int) (radius * Math.cos(angle)); - int needleCenterX = centerX + needleX; - int needleCenterY = centerY + needleY; - float[] points; - if (arrow) { - int arrowBaseX = centerX + (int) (radius * 0.85 * Math.sin(angle)); - int arrowBaseY = centerY + (int) (radius * 0.85 * Math.cos(angle)); - points = new float[] { arrowBaseX - needleSinValue, arrowBaseY - needleCosValue, - needleCenterX, needleCenterY, arrowBaseX + needleSinValue, arrowBaseY + needleCosValue }; - float width = paint.getStrokeWidth(); - paint.setStrokeWidth(5); - canvas.drawLine(centerX, centerY, needleCenterX, needleCenterY, paint); - paint.setStrokeWidth(width); - } else { - points = new float[] { centerX - needleSinValue, centerY - needleCosValue, needleCenterX, - needleCenterY, centerX + needleSinValue, centerY + needleCosValue }; - } - drawPath(canvas, points, paint, true); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/DoughnutChart.java b/android-libraries/achartengine/src/org/achartengine/chart/DoughnutChart.java deleted file mode 100644 index ad67b076..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/DoughnutChart.java +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.model.MultipleCategorySeries; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.SimpleSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.RectF; - -/** - * The doughnut chart rendering class. - */ -public class DoughnutChart extends RoundChart { - /** The series dataset. */ - private MultipleCategorySeries mDataset; - /** A step variable to control the size of the legend shape. */ - private int mStep; - - /** - * Builds a new doughnut chart instance. - * - * @param dataset the series dataset - * @param renderer the series renderer - */ - public DoughnutChart(MultipleCategorySeries dataset, DefaultRenderer renderer) { - super(null, renderer); - mDataset = dataset; - } - - /** - * The graphical representation of the doughnut chart. - * - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param height the height of the view to draw to - * @param paint the paint - */ - @Override - public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) { - paint.setAntiAlias(mRenderer.isAntialiasing()); - paint.setStyle(Style.FILL); - paint.setTextSize(mRenderer.getLabelsTextSize()); - int legendSize = getLegendSize(mRenderer, height / 5, 0); - int left = x; - int top = y; - int right = x + width; - int cLength = mDataset.getCategoriesCount(); - String[] categories = new String[cLength]; - for (int category = 0; category < cLength; category++) { - categories[category] = mDataset.getCategory(category); - } - if (mRenderer.isFitLegend()) { - legendSize = drawLegend(canvas, mRenderer, categories, left, right, y, width, height, - legendSize, paint, true); - } - - int bottom = y + height - legendSize; - drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR); - mStep = SHAPE_WIDTH * 3 / 4; - - int mRadius = Math.min(Math.abs(right - left), Math.abs(bottom - top)); - double rCoef = 0.35 * mRenderer.getScale(); - double decCoef = 0.2 / cLength; - int radius = (int) (mRadius * rCoef); - if (mCenterX == NO_VALUE) { - mCenterX = (left + right) / 2; - } - if (mCenterY == NO_VALUE) { - mCenterY = (bottom + top) / 2; - } - float shortRadius = radius * 0.9f; - float longRadius = radius * 1.1f; - List prevLabelsBounds = new ArrayList(); - for (int category = 0; category < cLength; category++) { - int sLength = mDataset.getItemCount(category); - double total = 0; - String[] titles = new String[sLength]; - for (int i = 0; i < sLength; i++) { - total += mDataset.getValues(category)[i]; - titles[i] = mDataset.getTitles(category)[i]; - } - float currentAngle = mRenderer.getStartAngle(); - RectF oval = new RectF(mCenterX - radius, mCenterY - radius, mCenterX + radius, mCenterY - + radius); - for (int i = 0; i < sLength; i++) { - paint.setColor(mRenderer.getSeriesRendererAt(i).getColor()); - float value = (float) mDataset.getValues(category)[i]; - float angle = (float) (value / total * 360); - canvas.drawArc(oval, currentAngle, angle, true, paint); - drawLabel(canvas, mDataset.getTitles(category)[i], mRenderer, prevLabelsBounds, mCenterX, - mCenterY, shortRadius, longRadius, currentAngle, angle, left, right, - mRenderer.getLabelsColor(), paint, true); - currentAngle += angle; - } - radius -= (int) mRadius * decCoef; - shortRadius -= mRadius * decCoef - 2; - if (mRenderer.getBackgroundColor() != 0) { - paint.setColor(mRenderer.getBackgroundColor()); - } else { - paint.setColor(Color.WHITE); - } - paint.setStyle(Style.FILL); - oval = new RectF(mCenterX - radius, mCenterY - radius, mCenterX + radius, mCenterY + radius); - canvas.drawArc(oval, 0, 360, true, paint); - radius -= 1; - } - prevLabelsBounds.clear(); - drawLegend(canvas, mRenderer, categories, left, right, y, width, height, legendSize, paint, - false); - drawTitle(canvas, x, y, width, paint); - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return SHAPE_WIDTH; - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - mStep--; - canvas.drawCircle(x + SHAPE_WIDTH - mStep, y, mStep, paint); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/LineChart.java b/android-libraries/achartengine/src/org/achartengine/chart/LineChart.java deleted file mode 100644 index 2c458986..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/LineChart.java +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.RectF; - -/** - * The line chart rendering class. - */ -public class LineChart extends XYChart { - /** The constant to identify this chart type. */ - public static final String TYPE = "Line"; - /** The legend shape width. */ - private static final int SHAPE_WIDTH = 30; - /** The scatter chart to be used to draw the data points. */ - private ScatterChart pointsChart; - - LineChart() { - } - - /** - * Builds a new line chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - */ - public LineChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - super(dataset, renderer); - pointsChart = new ScatterChart(dataset, renderer); - } - - /** - * Sets the series and the renderer. - * - * @param dataset the series dataset - * @param renderer the series renderer - */ - protected void setDatasetRenderer(XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer) { - super.setDatasetRenderer(dataset, renderer); - pointsChart = new ScatterChart(dataset, renderer); - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { - int length = points.length; - XYSeriesRenderer renderer = (XYSeriesRenderer) seriesRenderer; - float lineWidth = paint.getStrokeWidth(); - paint.setStrokeWidth(renderer.getLineWidth()); - if (renderer.isFillBelowLine()) { - paint.setColor(renderer.getFillBelowLineColor()); - int pLength = points.length; - float[] fillPoints = new float[pLength + 4]; - System.arraycopy(points, 0, fillPoints, 0, length); - fillPoints[0] = points[0] + 1; - fillPoints[length] = fillPoints[length - 2]; - fillPoints[length + 1] = yAxisValue; - fillPoints[length + 2] = fillPoints[0]; - fillPoints[length + 3] = fillPoints[length + 1]; - for (int i = 0; i < length + 4; i += 2) { - if (fillPoints[i + 1] < 0) { - fillPoints[i + 1] = 0; - } - } - paint.setStyle(Style.FILL); - drawPath(canvas, fillPoints, paint, true); - } - paint.setColor(seriesRenderer.getColor()); - paint.setStyle(Style.STROKE); - drawPath(canvas, points, paint, false); - paint.setStrokeWidth(lineWidth); - } - - @Override - protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, - float yAxisValue, int seriesIndex, int startIndex) { - int length = points.length; - ClickableArea[] ret = new ClickableArea[length / 2]; - for (int i = 0; i < length; i += 2) { - int selectableBuffer = mRenderer.getSelectableBuffer(); - ret[i / 2] = new ClickableArea(new RectF(points[i] - selectableBuffer, points[i + 1] - - selectableBuffer, points[i] + selectableBuffer, points[i + 1] + selectableBuffer), - values[i], values[i + 1]); - } - return ret; - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return SHAPE_WIDTH; - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - canvas.drawLine(x, y, x + SHAPE_WIDTH, y, paint); - if (isRenderPoints(renderer)) { - pointsChart.drawLegendShape(canvas, renderer, x + 5, y, seriesIndex, paint); - } - } - - /** - * Returns if the chart should display the points as a certain shape. - * - * @param renderer the series renderer - */ - public boolean isRenderPoints(SimpleSeriesRenderer renderer) { - return ((XYSeriesRenderer) renderer).getPointStyle() != PointStyle.POINT; - } - - /** - * Returns the scatter chart to be used for drawing the data points. - * - * @return the data points scatter chart - */ - public ScatterChart getPointsChart() { - return pointsChart; - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/PieChart.java b/android-libraries/achartengine/src/org/achartengine/chart/PieChart.java deleted file mode 100644 index d656a95e..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/PieChart.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.model.CategorySeries; -import org.achartengine.model.Point; -import org.achartengine.model.SeriesSelection; -import org.achartengine.renderer.DefaultRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.RectF; - -/** - * The pie chart rendering class. - */ -public class PieChart extends RoundChart { - /** Handles returning values when tapping on PieChart. */ - private PieMapper mPieMapper; - - /** - * Builds a new pie chart instance. - * - * @param dataset the series dataset - * @param renderer the series renderer - */ - public PieChart(CategorySeries dataset, DefaultRenderer renderer) { - super(dataset, renderer); - mPieMapper = new PieMapper(); - } - - /** - * The graphical representation of the pie chart. - * - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param height the height of the view to draw to - * @param paint the paint - */ - @Override - public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) { - paint.setAntiAlias(mRenderer.isAntialiasing()); - paint.setStyle(Style.FILL); - paint.setTextSize(mRenderer.getLabelsTextSize()); - int legendSize = getLegendSize(mRenderer, height / 5, 0); - int left = x; - int top = y; - int right = x + width; - int sLength = mDataset.getItemCount(); - double total = 0; - String[] titles = new String[sLength]; - for (int i = 0; i < sLength; i++) { - total += mDataset.getValue(i); - titles[i] = mDataset.getCategory(i); - } - if (mRenderer.isFitLegend()) { - legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, - paint, true); - } - int bottom = y + height - legendSize; - drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR); - - float currentAngle = mRenderer.getStartAngle(); - int mRadius = Math.min(Math.abs(right - left), Math.abs(bottom - top)); - int radius = (int) (mRadius * 0.35 * mRenderer.getScale()); - - if (mCenterX == NO_VALUE) { - mCenterX = (left + right) / 2; - } - if (mCenterY == NO_VALUE) { - mCenterY = (bottom + top) / 2; - } - - // Hook in clip detection after center has been calculated - mPieMapper.setDimensions(radius, mCenterX, mCenterY); - boolean loadPieCfg = !mPieMapper.areAllSegmentPresent(sLength); - if (loadPieCfg) { - mPieMapper.clearPieSegments(); - } - - float shortRadius = radius * 0.9f; - float longRadius = radius * 1.1f; - - RectF oval = new RectF(mCenterX - radius, mCenterY - radius, mCenterX + radius, mCenterY - + radius); - List prevLabelsBounds = new ArrayList(); - - for (int i = 0; i < sLength; i++) { - paint.setColor(mRenderer.getSeriesRendererAt(i).getColor()); - float value = (float) mDataset.getValue(i); - float angle = (float) (value / total * 360); - canvas.drawArc(oval, currentAngle, angle, true, paint); - drawLabel(canvas, mDataset.getCategory(i), mRenderer, prevLabelsBounds, mCenterX, mCenterY, - shortRadius, longRadius, currentAngle, angle, left, right, mRenderer.getLabelsColor(), - paint, true); - if (mRenderer.isDisplayValues()) { - drawLabel(canvas, getLabel(mDataset.getValue(i)), mRenderer, prevLabelsBounds, mCenterX, - mCenterY, shortRadius / 2, longRadius / 2, currentAngle, angle, left, right, - mRenderer.getLabelsColor(), paint, false); - } - - // Save details for getSeries functionality - if (loadPieCfg) { - mPieMapper.addPieSegment(i, value, currentAngle, angle); - } - currentAngle += angle; - } - prevLabelsBounds.clear(); - drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, paint, false); - drawTitle(canvas, x, y, width, paint); - } - - public SeriesSelection getSeriesAndPointForScreenCoordinate(Point screenPoint) { - return mPieMapper.getSeriesAndPointForScreenCoordinate(screenPoint); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/PieMapper.java b/android-libraries/achartengine/src/org/achartengine/chart/PieMapper.java deleted file mode 100644 index 6e4b7150..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/PieMapper.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.model.Point; -import org.achartengine.model.SeriesSelection; - -/** - * PieChart Segment Selection Management. - */ -public class PieMapper implements Serializable { - - private List mPieSegmentList = new ArrayList(); - - private int mPieChartRadius; - - private int mCenterX, mCenterY; - - /** - * Set PieChart location on screen. - * - * @param pieRadius - * @param centerX - * @param centerY - */ - public void setDimensions(int pieRadius, int centerX, int centerY) { - mPieChartRadius = pieRadius; - mCenterX = centerX; - mCenterY = centerY; - } - - /** - * If we have all PieChart Config then there is no point in reloading it - * - * @param datasetSize - * @return true if cfg for each segment is present - */ - public boolean areAllSegmentPresent(int datasetSize) { - return mPieSegmentList.size() == datasetSize; - } - - /** - * Add configuration for a PieChart Segment - * - * @param dataIndex - * @param value - * @param startAngle - * @param angle - */ - public void addPieSegment(int dataIndex, float value, float startAngle, float angle) { - mPieSegmentList.add(new PieSegment(dataIndex, value, startAngle, angle)); - } - - /** - * Clears the pie segments list. - */ - public void clearPieSegments() { - mPieSegmentList.clear(); - } - - /** - * Fetches angle relative to pie chart center point where 3 O'Clock is 0 and - * 12 O'Clock is 270degrees - * - * @param screenPoint - * @return angle in degress from 0-360. - */ - public double getAngle(Point screenPoint) { - double dx = screenPoint.getX() - mCenterX; - // Minus to correct for coord re-mapping - double dy = -(screenPoint.getY() - mCenterY); - - double inRads = Math.atan2(dy, dx); - - // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 - // O'clock - if (inRads < 0) - inRads = Math.abs(inRads); - else - inRads = 2 * Math.PI - inRads; - - return Math.toDegrees(inRads); - } - - /** - * Checks if Point falls within PieChart - * - * @param screenPoint - * @return true if in PieChart - */ - public boolean isOnPieChart(Point screenPoint) { - // Using a bit of Pythagoras - // inside circle if (x-center_x)**2 + (y-center_y)**2 <= radius**2: - - double sqValue = (Math.pow(mCenterX - screenPoint.getX(), 2) + Math.pow( - mCenterY - screenPoint.getY(), 2)); - - double radiusSquared = mPieChartRadius * mPieChartRadius; - boolean isOnPieChart = sqValue <= radiusSquared; - return isOnPieChart; - } - - /** - * Fetches the SeriesSelection for the PieSegment selected. - * - * @param screenPoint - the user tap location - * @return null if screen point is not in PieChart or its config if it is - */ - public SeriesSelection getSeriesAndPointForScreenCoordinate(Point screenPoint) { - if (isOnPieChart(screenPoint)) { - double angleFromPieCenter = getAngle(screenPoint); - - for (PieSegment pieSeg : mPieSegmentList) { - if (pieSeg.isInSegment(angleFromPieCenter)) { - return new SeriesSelection(0, pieSeg.getDataIndex(), pieSeg.getValue(), - pieSeg.getValue()); - } - } - } - return null; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/PieSegment.java b/android-libraries/achartengine/src/org/achartengine/chart/PieSegment.java deleted file mode 100644 index 0fb0a2e4..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/PieSegment.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.io.Serializable; - -/** - * Holds An PieChart Segment - */ -public class PieSegment implements Serializable { - private float mStartAngle; - - private float mEndAngle; - - private int mDataIndex; - - private float mValue; - - public PieSegment(int dataIndex, float value, float startAngle, float angle) { - mStartAngle = startAngle; - mEndAngle = angle + startAngle; - mDataIndex = dataIndex; - mValue = value; - } - - /** - * Checks if angle falls in segment. - * - * @param angle - * @return true if in segment, false otherwise. - */ - public boolean isInSegment(double angle) { - return angle >= mStartAngle && angle <= mEndAngle; - } - - protected float getStartAngle() { - return mStartAngle; - } - - protected float getEndAngle() { - return mEndAngle; - } - - protected int getDataIndex() { - return mDataIndex; - } - - protected float getValue() { - return mValue; - } - - public String toString() { - return "mDataIndex=" + mDataIndex + ",mValue=" + mValue + ",mStartAngle=" + mStartAngle - + ",mEndAngle=" + mEndAngle; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/PointStyle.java b/android-libraries/achartengine/src/org/achartengine/chart/PointStyle.java deleted file mode 100644 index 29a2311a..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/PointStyle.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -/** - * The chart point style enumerator. - */ -public enum PointStyle { - X("x"), CIRCLE("circle"), TRIANGLE("triangle"), SQUARE("square"), DIAMOND("diamond"), POINT( - "point"); - - /** The point shape name. */ - private String mName; - - /** - * The point style enum constructor. - * - * @param name the name - */ - private PointStyle(String name) { - mName = name; - } - - /** - * Returns the point shape name. - * - * @return the point shape name - */ - public String getName() { - return mName; - } - - /** - * Returns the point shape name. - * - * @return the point shape name - */ - public String toString() { - return getName(); - } - - /** - * Return the point shape that has the provided symbol. - * - * @param name the point style name - * @return the point shape - */ - public static PointStyle getPointStyleForName(String name) { - PointStyle pointStyle = null; - PointStyle[] styles = values(); - int length = styles.length; - for (int i = 0; i < length && pointStyle == null; i++) { - if (styles[i].mName.equals(name)) { - pointStyle = styles[i]; - } - } - return pointStyle; - } - - /** - * Returns the point shape index based on the given name. - * - * @return the point shape index - */ - public static int getIndexForName(String name) { - int index = -1; - PointStyle[] styles = values(); - int length = styles.length; - for (int i = 0; i < length && index < 0; i++) { - if (styles[i].mName.equals(name)) { - index = i; - } - } - return Math.max(0, index); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/RangeBarChart.java b/android-libraries/achartengine/src/org/achartengine/chart/RangeBarChart.java deleted file mode 100644 index 105f509a..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/RangeBarChart.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Style; - -/** - * The range bar chart rendering class. - */ -public class RangeBarChart extends BarChart { - /** The chart type. */ - public static final String TYPE = "RangeBar"; - - RangeBarChart() { - } - - RangeBarChart(Type type) { - super(type); - } - - /** - * Builds a new range bar chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - * @param type the range bar chart type - */ - public RangeBarChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer, Type type) { - super(dataset, renderer, type); - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { - int seriesNr = mDataset.getSeriesCount(); - int length = points.length; - paint.setColor(seriesRenderer.getColor()); - paint.setStyle(Style.FILL); - float halfDiffX = getHalfDiffX(points, length, seriesNr); - int start = 0; - if (startIndex > 0) { - start = 2; - } - for (int i = start; i < length; i += 4) { - if (points.length > i + 3) { - float xMin = points[i]; - float yMin = points[i + 1]; - // xMin = xMax - float xMax = points[i + 2]; - float yMax = points[i + 3]; - drawBar(canvas, xMin, yMin, xMax, yMax, halfDiffX, seriesNr, seriesIndex, paint); - } - } - paint.setColor(seriesRenderer.getColor()); - } - - /** - * The graphical representation of the series values as text. - * - * @param canvas the canvas to paint to - * @param series the series to be painted - * @param renderer the series renderer - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer, - Paint paint, float[] points, int seriesIndex, int startIndex) { - int seriesNr = mDataset.getSeriesCount(); - float halfDiffX = getHalfDiffX(points, points.length, seriesNr); - int start = 0; - if (startIndex > 0) { - start = 2; - } - for (int i = start; i < points.length; i += 4) { - int index = startIndex + i / 2; - float x = points[i]; - if (mType == Type.DEFAULT) { - x += seriesIndex * 2 * halfDiffX - (seriesNr - 1.5f) * halfDiffX; - } - - if (!isNullValue(series.getY(index + 1)) && points.length > i + 3) { - // draw the maximum value - drawText(canvas, getLabel(series.getY(index + 1)), x, - points[i + 3] - renderer.getChartValuesSpacing(), paint, 0); - } - if (!isNullValue(series.getY(index)) && points.length > i + 1) { - // draw the minimum value - drawText(canvas, getLabel(series.getY(index)), x, - points[i + 1] + renderer.getChartValuesTextSize() + renderer.getChartValuesSpacing() - - 3, paint, 0); - } - } - } - - /** - * Returns the value of a constant used to calculate the half-distance. - * - * @return the constant value - */ - protected float getCoeficient() { - return 0.5f; - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/RangeStackedBarChart.java b/android-libraries/achartengine/src/org/achartengine/chart/RangeStackedBarChart.java deleted file mode 100644 index 4da4f006..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/RangeStackedBarChart.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -public class RangeStackedBarChart extends RangeBarChart { - /** The chart type. */ - public static final String TYPE = "RangeStackedBar"; - - RangeStackedBarChart() { - super(Type.STACKED); - } - - public String getChartType() { - return TYPE; - } -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/chart/RoundChart.java b/android-libraries/achartengine/src/org/achartengine/chart/RoundChart.java deleted file mode 100644 index 1a2121d4..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/RoundChart.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.CategorySeries; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.SimpleSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Align; - -/** - * An abstract class to be extended by round like chart rendering classes. - */ -public abstract class RoundChart extends AbstractChart { - /** The legend shape width. */ - protected static final int SHAPE_WIDTH = 10; - /** The series dataset. */ - protected CategorySeries mDataset; - /** The series renderer. */ - protected DefaultRenderer mRenderer; - /** A no value constant. */ - protected static final int NO_VALUE = Integer.MAX_VALUE; - /** The chart center X axis. */ - protected int mCenterX = NO_VALUE; - /** The chart center y axis. */ - protected int mCenterY = NO_VALUE; - - /** - * Round chart. - * - * @param dataset the series dataset - * @param renderer the series renderer - */ - public RoundChart(CategorySeries dataset, DefaultRenderer renderer) { - mDataset = dataset; - mRenderer = renderer; - } - - /** - * The graphical representation of the round chart title. - * - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param paint the paint - */ - public void drawTitle(Canvas canvas, int x, int y, int width, Paint paint) { - if (mRenderer.isShowLabels()) { - paint.setColor(mRenderer.getLabelsColor()); - paint.setTextAlign(Align.CENTER); - paint.setTextSize(mRenderer.getChartTitleTextSize()); - drawString(canvas, mRenderer.getChartTitle(), x + width / 2, - y + mRenderer.getChartTitleTextSize(), paint); - } - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return SHAPE_WIDTH; - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - canvas.drawRect(x, y - SHAPE_WIDTH / 2, x + SHAPE_WIDTH, y + SHAPE_WIDTH / 2, paint); - } - - /** - * Returns the renderer. - * - * @return the renderer - */ - public DefaultRenderer getRenderer() { - return mRenderer; - } - - /** - * Returns the center on X axis. - * - * @return the center on X axis - */ - public int getCenterX() { - return mCenterX; - } - - /** - * Returns the center on Y axis. - * - * @return the center on Y axis - */ - public int getCenterY() { - return mCenterY; - } - - /** - * Sets a new center on X axis. - * - * @param centerX center on X axis - */ - public void setCenterX(int centerX) { - mCenterX = centerX; - } - - /** - * Sets a new center on Y axis. - * - * @param centerY center on Y axis - */ - public void setCenterY(int centerY) { - mCenterY = centerY; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/ScatterChart.java b/android-libraries/achartengine/src/org/achartengine/chart/ScatterChart.java deleted file mode 100644 index 1d3b2a18..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/ScatterChart.java +++ /dev/null @@ -1,266 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.RectF; - -/** - * The scatter chart rendering class. - */ -public class ScatterChart extends XYChart { - /** The constant to identify this chart type. */ - public static final String TYPE = "Scatter"; - /** The default point shape size. */ - private static final float SIZE = 3; - /** The legend shape width. */ - private static final int SHAPE_WIDTH = 10; - /** The point shape size. */ - private float size = SIZE; - - ScatterChart() { - } - - /** - * Builds a new scatter chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - */ - public ScatterChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - super(dataset, renderer); - size = renderer.getPointSize(); - } - - // TODO: javadoc - protected void setDatasetRenderer(XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer) { - super.setDatasetRenderer(dataset, renderer); - size = renderer.getPointSize(); - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) { - XYSeriesRenderer renderer = (XYSeriesRenderer) seriesRenderer; - paint.setColor(renderer.getColor()); - if (renderer.isFillPoints()) { - paint.setStyle(Style.FILL); - } else { - paint.setStyle(Style.STROKE); - } - int length = points.length; - switch (renderer.getPointStyle()) { - case X: - for (int i = 0; i < length; i += 2) { - drawX(canvas, paint, points[i], points[i + 1]); - } - break; - case CIRCLE: - for (int i = 0; i < length; i += 2) { - drawCircle(canvas, paint, points[i], points[i + 1]); - } - break; - case TRIANGLE: - float[] path = new float[6]; - for (int i = 0; i < length; i += 2) { - drawTriangle(canvas, paint, path, points[i], points[i + 1]); - } - break; - case SQUARE: - for (int i = 0; i < length; i += 2) { - drawSquare(canvas, paint, points[i], points[i + 1]); - } - break; - case DIAMOND: - path = new float[8]; - for (int i = 0; i < length; i += 2) { - drawDiamond(canvas, paint, path, points[i], points[i + 1]); - } - break; - case POINT: - canvas.drawPoints(points, paint); - break; - } - } - - @Override - protected ClickableArea[] clickableAreasForPoints(float[] points, double[] values, - float yAxisValue, int seriesIndex, int startIndex) { - int length = points.length; - ClickableArea[] ret = new ClickableArea[length / 2]; - for (int i = 0; i < length; i += 2) { - int selectableBuffer = mRenderer.getSelectableBuffer(); - ret[i / 2] = new ClickableArea(new RectF(points[i] - selectableBuffer, points[i + 1] - - selectableBuffer, points[i] + selectableBuffer, points[i + 1] + selectableBuffer), - values[i], values[i + 1]); - } - return ret; - } - - /** - * Returns the legend shape width. - * - * @param seriesIndex the series index - * @return the legend shape width - */ - public int getLegendShapeWidth(int seriesIndex) { - return SHAPE_WIDTH; - } - - /** - * The graphical representation of the legend shape. - * - * @param canvas the canvas to paint to - * @param renderer the series renderer - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - * @param seriesIndex the series index - * @param paint the paint to be used for drawing - */ - public void drawLegendShape(Canvas canvas, SimpleSeriesRenderer renderer, float x, float y, - int seriesIndex, Paint paint) { - if (((XYSeriesRenderer) renderer).isFillPoints()) { - paint.setStyle(Style.FILL); - } else { - paint.setStyle(Style.STROKE); - } - switch (((XYSeriesRenderer) renderer).getPointStyle()) { - case X: - drawX(canvas, paint, x + SHAPE_WIDTH, y); - break; - case CIRCLE: - drawCircle(canvas, paint, x + SHAPE_WIDTH, y); - break; - case TRIANGLE: - drawTriangle(canvas, paint, new float[6], x + SHAPE_WIDTH, y); - break; - case SQUARE: - drawSquare(canvas, paint, x + SHAPE_WIDTH, y); - break; - case DIAMOND: - drawDiamond(canvas, paint, new float[8], x + SHAPE_WIDTH, y); - break; - case POINT: - canvas.drawPoint(x + SHAPE_WIDTH, y, paint); - break; - } - } - - /** - * The graphical representation of an X point shape. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - */ - private void drawX(Canvas canvas, Paint paint, float x, float y) { - canvas.drawLine(x - size, y - size, x + size, y + size, paint); - canvas.drawLine(x + size, y - size, x - size, y + size, paint); - } - - /** - * The graphical representation of a circle point shape. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - */ - private void drawCircle(Canvas canvas, Paint paint, float x, float y) { - canvas.drawCircle(x, y, size, paint); - } - - /** - * The graphical representation of a triangle point shape. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param path the triangle path - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - */ - private void drawTriangle(Canvas canvas, Paint paint, float[] path, float x, float y) { - path[0] = x; - path[1] = y - size - size / 2; - path[2] = x - size; - path[3] = y + size; - path[4] = x + size; - path[5] = path[3]; - drawPath(canvas, path, paint, true); - } - - /** - * The graphical representation of a square point shape. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - */ - private void drawSquare(Canvas canvas, Paint paint, float x, float y) { - canvas.drawRect(x - size, y - size, x + size, y + size, paint); - } - - /** - * The graphical representation of a diamond point shape. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param path the diamond path - * @param x the x value of the point the shape should be drawn at - * @param y the y value of the point the shape should be drawn at - */ - private void drawDiamond(Canvas canvas, Paint paint, float[] path, float x, float y) { - path[0] = x; - path[1] = y - size; - path[2] = x - size; - path[3] = y; - path[4] = x; - path[5] = y + size; - path[6] = x + size; - path[7] = y; - drawPath(canvas, path, paint, true); - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } - -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/chart/TimeChart.java b/android-libraries/achartengine/src/org/achartengine/chart/TimeChart.java deleted file mode 100644 index ba201de7..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/TimeChart.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.XYMultipleSeriesRenderer; - -import android.graphics.Canvas; -import android.graphics.Paint; - -/** - * The time chart rendering class. - */ -public class TimeChart extends LineChart { - /** The constant to identify this chart type. */ - public static final String TYPE = "Time"; - /** The number of milliseconds in a day. */ - public static final long DAY = 24 * 60 * 60 * 1000; - /** The date format pattern to be used in formatting the X axis labels. */ - private String mDateFormat; - /** The starting point for labels. */ - private Double mStartPoint; - - TimeChart() { - } - - /** - * Builds a new time chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - */ - public TimeChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - super(dataset, renderer); - } - - /** - * Returns the date format pattern to be used for formatting the X axis - * labels. - * - * @return the date format pattern for the X axis labels - */ - public String getDateFormat() { - return mDateFormat; - } - - /** - * Sets the date format pattern to be used for formatting the X axis labels. - * - * @param format the date format pattern for the X axis labels. If null, an - * appropriate default format will be used. - */ - public void setDateFormat(String format) { - mDateFormat = format; - } - - /** - * The graphical representation of the labels on the X axis. - * - * @param xLabels the X labels values - * @param xTextLabelLocations the X text label locations - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param left the left value of the labels area - * @param top the top value of the labels area - * @param bottom the bottom value of the labels area - * @param xPixelsPerUnit the amount of pixels per one unit in the chart labels - * @param minX the minimum value on the X axis in the chart - * @param maxX the maximum value on the X axis in the chart - */ - @Override - protected void drawXLabels(List xLabels, Double[] xTextLabelLocations, Canvas canvas, - Paint paint, int left, int top, int bottom, double xPixelsPerUnit, double minX, double maxX) { - int length = xLabels.size(); - if (length > 0) { - boolean showLabels = mRenderer.isShowLabels(); - boolean showGridY = mRenderer.isShowGridY(); - DateFormat format = getDateFormat(xLabels.get(0), xLabels.get(length - 1)); - for (int i = 0; i < length; i++) { - long label = Math.round(xLabels.get(i)); - float xLabel = (float) (left + xPixelsPerUnit * (label - minX)); - if (showLabels) { - paint.setColor(mRenderer.getXLabelsColor()); - canvas - .drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint); - drawText(canvas, format.format(new Date(label)), xLabel, - bottom + mRenderer.getLabelsTextSize() * 4 / 3, paint, mRenderer.getXLabelsAngle()); - } - if (showGridY) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(xLabel, bottom, xLabel, top, paint); - } - } - } - drawXTextLabels(xTextLabelLocations, canvas, paint, true, left, top, bottom, xPixelsPerUnit, - minX, maxX); - } - - /** - * Returns the date format pattern to be used, based on the date range. - * - * @param start the start date in milliseconds - * @param end the end date in milliseconds - * @return the date format - */ - private DateFormat getDateFormat(double start, double end) { - if (mDateFormat != null) { - SimpleDateFormat format = null; - try { - format = new SimpleDateFormat(mDateFormat); - return format; - } catch (Exception e) { - // do nothing here - } - } - DateFormat format = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM); - double diff = end - start; - if (diff > DAY && diff < 5 * DAY) { - format = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT); - } else if (diff < DAY) { - format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM); - } - return format; - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public String getChartType() { - return TYPE; - } - - protected List getXLabels(double min, double max, int count) { - final List result = new ArrayList(); - if (!mRenderer.isXRoundedLabels()) { - if (mDataset.getSeriesCount() > 0) { - XYSeries series = mDataset.getSeriesAt(0); - int length = series.getItemCount(); - int intervalLength = 0; - int startIndex = -1; - for (int i = 0; i < length; i++) { - double value = series.getX(i); - if (min <= value && value <= max) { - intervalLength++; - if (startIndex < 0) { - startIndex = i; - } - } - } - if (intervalLength < count) { - for (int i = startIndex; i < startIndex + intervalLength; i++) { - result.add(series.getX(i)); - } - } else { - float step = (float) intervalLength / count; - int intervalCount = 0; - for (int i = 0; i < length && intervalCount < count; i++) { - double value = series.getX(Math.round(i * step)); - if (min <= value && value <= max) { - result.add(value); - intervalCount++; - } - } - } - return result; - } else { - return super.getXLabels(min, max, count); - } - } - if (mStartPoint == null) { - mStartPoint = min - (min % DAY) + DAY + new Date(Math.round(min)).getTimezoneOffset() * 60 - * 1000; - } - if (count > 25) { - count = 25; - } - - - final double cycleMath = (max - min) / count; - if (cycleMath <= 0) { - return result; - } - double cycle = DAY; - - if (cycleMath <= DAY) { - while (cycleMath < cycle / 2) { - cycle = cycle / 2; - } - } else { - while (cycleMath > cycle) { - cycle = cycle * 2; - } - } - - double val = mStartPoint - Math.floor((mStartPoint - min) / cycle) * cycle; - int i = 0; - while (val < max && i++ <= count) { - result.add(val); - val += cycle; - } - - return result; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/XYChart.java b/android-libraries/achartengine/src/org/achartengine/chart/XYChart.java deleted file mode 100644 index 6b531d60..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/XYChart.java +++ /dev/null @@ -1,905 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.chart; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; - -import org.achartengine.model.Point; -import org.achartengine.model.SeriesSelection; -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.BasicStroke; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.renderer.SimpleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation; -import org.achartengine.util.MathHelper; - -import android.graphics.Canvas; -import android.graphics.DashPathEffect; -import android.graphics.Paint; -import android.graphics.Paint.Align; -import android.graphics.Paint.Cap; -import android.graphics.Paint.Join; -import android.graphics.Paint.Style; -import android.graphics.PathEffect; -import android.graphics.Rect; -import android.graphics.RectF; -import android.graphics.Typeface; - -/** - * The XY chart rendering class. - */ -public abstract class XYChart extends AbstractChart { - /** The multiple series dataset. */ - protected XYMultipleSeriesDataset mDataset; - /** The multiple series renderer. */ - protected XYMultipleSeriesRenderer mRenderer; - /** The current scale value. */ - private float mScale; - /** The current translate value. */ - private float mTranslate; - /** The canvas center point. */ - private Point mCenter; - /** The visible chart area, in screen coordinates. */ - private Rect mScreenR; - /** The calculated range. */ - private final Map mCalcRange = new HashMap(); - - /** - * The clickable areas for all points. The array index is the series index, - * and the RectF list index is the point index in that series. - */ - private Map> clickableAreas = new HashMap>(); - - protected XYChart() { - } - - /** - * Builds a new XY chart instance. - * - * @param dataset the multiple series dataset - * @param renderer the multiple series renderer - */ - public XYChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) { - mDataset = dataset; - mRenderer = renderer; - } - - // TODO: javadoc - protected void setDatasetRenderer(XYMultipleSeriesDataset dataset, - XYMultipleSeriesRenderer renderer) { - mDataset = dataset; - mRenderer = renderer; - } - - /** - * The graphical representation of the XY chart. - * - * @param canvas the canvas to paint to - * @param x the top left x value of the view to draw to - * @param y the top left y value of the view to draw to - * @param width the width of the view to draw to - * @param height the height of the view to draw to - * @param paint the paint - */ - public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) { - paint.setAntiAlias(mRenderer.isAntialiasing()); - int legendSize = getLegendSize(mRenderer, height / 5, mRenderer.getAxisTitleTextSize()); - int[] margins = mRenderer.getMargins(); - int left = x + margins[1]; - int top = y + margins[0]; - int right = x + width - margins[3]; - int sLength = mDataset.getSeriesCount(); - String[] titles = new String[sLength]; - for (int i = 0; i < sLength; i++) { - titles[i] = mDataset.getSeriesAt(i).getTitle(); - } - if (mRenderer.isFitLegend() && mRenderer.isShowLegend()) { - legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, - paint, true); - } - int bottom = y + height - margins[2] - legendSize; - if (mScreenR == null) { - mScreenR = new Rect(); - } - mScreenR.set(left, top, right, bottom); - drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR); - - if (paint.getTypeface() == null - || !paint.getTypeface().toString().equals(mRenderer.getTextTypefaceName()) - || paint.getTypeface().getStyle() != mRenderer.getTextTypefaceStyle()) { - paint.setTypeface(Typeface.create(mRenderer.getTextTypefaceName(), - mRenderer.getTextTypefaceStyle())); - } - Orientation or = mRenderer.getOrientation(); - if (or == Orientation.VERTICAL) { - right -= legendSize; - bottom += legendSize - 20; - } - int angle = or.getAngle(); - boolean rotate = angle == 90; - mScale = (float) (height) / width; - mTranslate = Math.abs(width - height) / 2; - if (mScale < 1) { - mTranslate *= -1; - } - mCenter = new Point((x + width) / 2, (y + height) / 2); - if (rotate) { - transform(canvas, angle, false); - } - - int maxScaleNumber = -Integer.MAX_VALUE; - for (int i = 0; i < sLength; i++) { - maxScaleNumber = Math.max(maxScaleNumber, mDataset.getSeriesAt(i).getScaleNumber()); - } - maxScaleNumber++; - if (maxScaleNumber < 0) { - return; - } - double[] minX = new double[maxScaleNumber]; - double[] maxX = new double[maxScaleNumber]; - double[] minY = new double[maxScaleNumber]; - double[] maxY = new double[maxScaleNumber]; - boolean[] isMinXSet = new boolean[maxScaleNumber]; - boolean[] isMaxXSet = new boolean[maxScaleNumber]; - boolean[] isMinYSet = new boolean[maxScaleNumber]; - boolean[] isMaxYSet = new boolean[maxScaleNumber]; - - for (int i = 0; i < maxScaleNumber; i++) { - minX[i] = mRenderer.getXAxisMin(i); - maxX[i] = mRenderer.getXAxisMax(i); - minY[i] = mRenderer.getYAxisMin(i); - maxY[i] = mRenderer.getYAxisMax(i); - isMinXSet[i] = mRenderer.isMinXSet(i); - isMaxXSet[i] = mRenderer.isMaxXSet(i); - isMinYSet[i] = mRenderer.isMinYSet(i); - isMaxYSet[i] = mRenderer.isMaxYSet(i); - if (mCalcRange.get(i) == null) { - mCalcRange.put(i, new double[4]); - } - } - double[] xPixelsPerUnit = new double[maxScaleNumber]; - double[] yPixelsPerUnit = new double[maxScaleNumber]; - for (int i = 0; i < sLength; i++) { - XYSeries series = mDataset.getSeriesAt(i); - int scale = series.getScaleNumber(); - if (series.getItemCount() == 0) { - continue; - } - if (!isMinXSet[scale]) { - double minimumX = series.getMinX(); - minX[scale] = Math.min(minX[scale], minimumX); - mCalcRange.get(scale)[0] = minX[scale]; - } - if (!isMaxXSet[scale]) { - double maximumX = series.getMaxX(); - maxX[scale] = Math.max(maxX[scale], maximumX); - mCalcRange.get(scale)[1] = maxX[scale]; - } - if (!isMinYSet[scale]) { - double minimumY = series.getMinY(); - minY[scale] = Math.min(minY[scale], (float) minimumY); - mCalcRange.get(scale)[2] = minY[scale]; - } - if (!isMaxYSet[scale]) { - double maximumY = series.getMaxY(); - maxY[scale] = Math.max(maxY[scale], (float) maximumY); - mCalcRange.get(scale)[3] = maxY[scale]; - } - } - for (int i = 0; i < maxScaleNumber; i++) { - if (maxX[i] - minX[i] != 0) { - xPixelsPerUnit[i] = (right - left) / (maxX[i] - minX[i]); - } - if (maxY[i] - minY[i] != 0) { - yPixelsPerUnit[i] = (float) ((bottom - top) / (maxY[i] - minY[i])); - } - } - - boolean hasValues = false; - // use a linked list for these reasons: - // 1) Avoid a large contiguous memory allocation - // 2) We don't need random seeking, only sequential reading/writing, so - // linked list makes sense - clickableAreas = new HashMap>(); - for (int i = 0; i < sLength; i++) { - XYSeries series = mDataset.getSeriesAt(i); - int scale = series.getScaleNumber(); - if (series.getItemCount() == 0) { - continue; - } - - hasValues = true; - SimpleSeriesRenderer seriesRenderer = mRenderer.getSeriesRendererAt(i); - - // int originalValuesLength = series.getItemCount(); - // int valuesLength = originalValuesLength; - // int length = valuesLength * 2; - - List points = new ArrayList(); - List values = new ArrayList(); - float yAxisValue = Math.min(bottom, (float) (bottom + yPixelsPerUnit[scale] * minY[scale])); - LinkedList clickableArea = new LinkedList(); - - clickableAreas.put(i, clickableArea); - - SortedMap range = series.getRange(minX[scale], maxX[scale], 1); - int startIndex = -1; - - for (Entry value : range.entrySet()) { - - double xValue = value.getKey(); - double yValue = value.getValue(); - if (startIndex < 0) { - startIndex = series.getIndexForKey(xValue); - } - - // points.add((float) (left + xPixelsPerUnit[scale] - // * (value.getKey().floatValue() - minX[scale]))); - // points.add((float) (bottom - yPixelsPerUnit[scale] - // * (value.getValue().floatValue() - minY[scale]))); - values.add(value.getKey()); - values.add(value.getValue()); - - if (!isNullValue(yValue)) { - points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale]))); - points.add((float) (bottom - yPixelsPerUnit[scale] * (yValue - minY[scale]))); - } else if (isRenderNullValues()) { - points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale]))); - points.add((float) (bottom - yPixelsPerUnit[scale] * (-minY[scale]))); - } else { - if (points.size() > 0) { - drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or, startIndex); - ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints( - MathHelper.getFloats(points), MathHelper.getDoubles(values), yAxisValue, i, - startIndex); - clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries)); - points.clear(); - values.clear(); - } - clickableArea.add(null); - } - } - - if (points.size() > 0) { - drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or, startIndex); - ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints( - MathHelper.getFloats(points), MathHelper.getDoubles(values), yAxisValue, i, startIndex); - clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries)); - } - } - - // draw stuff over the margins such as data doesn't render on these areas - drawBackground(mRenderer, canvas, x, bottom, width, height - bottom, paint, true, - mRenderer.getMarginsColor()); - drawBackground(mRenderer, canvas, x, y, width, margins[0], paint, true, - mRenderer.getMarginsColor()); - if (or == Orientation.HORIZONTAL) { - drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true, - mRenderer.getMarginsColor()); - drawBackground(mRenderer, canvas, right, y, margins[3], height - y, paint, true, - mRenderer.getMarginsColor()); - } else if (or == Orientation.VERTICAL) { - drawBackground(mRenderer, canvas, right, y, width - right, height - y, paint, true, - mRenderer.getMarginsColor()); - drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true, - mRenderer.getMarginsColor()); - } - - boolean showLabels = mRenderer.isShowLabels() && hasValues; - boolean showGridX = mRenderer.isShowGridX(); - boolean showCustomTextGrid = mRenderer.isShowCustomTextGrid(); - if (showLabels || showGridX) { - List xLabels = getValidLabels(getXLabels(minX[0], maxX[0], mRenderer.getXLabels())); - Map> allYLabels = getYLabels(minY, maxY, maxScaleNumber); - - int xLabelsLeft = left; - if (showLabels) { - paint.setColor(mRenderer.getXLabelsColor()); - paint.setTextSize(mRenderer.getLabelsTextSize()); - paint.setTextAlign(mRenderer.getXLabelsAlign()); - if (mRenderer.getXLabelsAlign() == Align.LEFT) { - xLabelsLeft += mRenderer.getLabelsTextSize() / 4; - } - } - drawXLabels(xLabels, mRenderer.getXTextLabelLocations(), canvas, paint, xLabelsLeft, top, - bottom, xPixelsPerUnit[0], minX[0], maxX[0]); - drawYLabels(allYLabels, canvas, paint, maxScaleNumber, left, right, bottom, yPixelsPerUnit, - minY); - - if (showLabels) { - paint.setColor(mRenderer.getLabelsColor()); - for (int i = 0; i < maxScaleNumber; i++) { - Align axisAlign = mRenderer.getYAxisAlign(i); - Double[] yTextLabelLocations = mRenderer.getYTextLabelLocations(i); - for (Double location : yTextLabelLocations) { - if (minY[i] <= location && location <= maxY[i]) { - float yLabel = (float) (bottom - yPixelsPerUnit[i] - * (location.doubleValue() - minY[i])); - String label = mRenderer.getYTextLabel(location, i); - paint.setColor(mRenderer.getYLabelsColor(i)); - paint.setTextAlign(mRenderer.getYLabelsAlign(i)); - if (or == Orientation.HORIZONTAL) { - if (axisAlign == Align.LEFT) { - canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint); - drawText(canvas, label, left, yLabel - 2, paint, mRenderer.getYLabelsAngle()); - } else { - canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint); - drawText(canvas, label, right, yLabel - 2, paint, mRenderer.getYLabelsAngle()); - } - - if (showCustomTextGrid) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(left, yLabel, right, yLabel, paint); - } - } else { - canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint); - drawText(canvas, label, right + 10, yLabel - 2, paint, mRenderer.getYLabelsAngle()); - if (showCustomTextGrid) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(right, yLabel, left, yLabel, paint); - } - } - } - } - } - } - - if (showLabels) { - paint.setColor(mRenderer.getLabelsColor()); - float size = mRenderer.getAxisTitleTextSize(); - paint.setTextSize(size); - paint.setTextAlign(Align.CENTER); - if (or == Orientation.HORIZONTAL) { - drawText(canvas, mRenderer.getXTitle(), x + width / 2, - bottom + mRenderer.getLabelsTextSize() * 4 / 3 + size, paint, 0); - for (int i = 0; i < maxScaleNumber; i++) { - Align axisAlign = mRenderer.getYAxisAlign(i); - if (axisAlign == Align.LEFT) { - drawText(canvas, mRenderer.getYTitle(i), x + size, y + height / 2, paint, -90); - } else { - drawText(canvas, mRenderer.getYTitle(i), x + width, y + height / 2, paint, -90); - } - } - paint.setTextSize(mRenderer.getChartTitleTextSize()); - drawText(canvas, mRenderer.getChartTitle(), x + width / 2, - y + mRenderer.getChartTitleTextSize(), paint, 0); - } else if (or == Orientation.VERTICAL) { - drawText(canvas, mRenderer.getXTitle(), x + width / 2, y + height - size, paint, -90); - drawText(canvas, mRenderer.getYTitle(), right + 20, y + height / 2, paint, 0); - paint.setTextSize(mRenderer.getChartTitleTextSize()); - drawText(canvas, mRenderer.getChartTitle(), x + size, top + height / 2, paint, 0); - } - } - } - if (or == Orientation.HORIZONTAL) { - drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, paint, false); - } else if (or == Orientation.VERTICAL) { - transform(canvas, angle, true); - drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize, paint, false); - transform(canvas, angle, false); - } - if (mRenderer.isShowAxes()) { - paint.setColor(mRenderer.getAxesColor()); - canvas.drawLine(left, bottom, right, bottom, paint); - boolean rightAxis = false; - for (int i = 0; i < maxScaleNumber && !rightAxis; i++) { - rightAxis = mRenderer.getYAxisAlign(i) == Align.RIGHT; - } - if (or == Orientation.HORIZONTAL) { - canvas.drawLine(left, top, left, bottom, paint); - if (rightAxis) { - canvas.drawLine(right, top, right, bottom, paint); - } - } else if (or == Orientation.VERTICAL) { - canvas.drawLine(right, top, right, bottom, paint); - } - } - if (rotate) { - transform(canvas, angle, true); - } - } - - protected List getXLabels(double min, double max, int count) { - return MathHelper.getLabels(min, max, count); - } - - protected Map> getYLabels(double[] minY, double[] maxY, int maxScaleNumber) { - Map> allYLabels = new HashMap>(); - for (int i = 0; i < maxScaleNumber; i++) { - allYLabels.put(i, - getValidLabels(MathHelper.getLabels(minY[i], maxY[i], mRenderer.getYLabels()))); - } - return allYLabels; - } - - protected Rect getScreenR() { - return mScreenR; - } - - protected void setScreenR(Rect screenR) { - mScreenR = screenR; - } - - private List getValidLabels(List labels) { - List result = new ArrayList(labels); - for (Double label : labels) { - if (label.isNaN()) { - result.remove(label); - } - } - return result; - } - - /** - * Draws the series. - * - * @param series the series - * @param canvas the canvas - * @param paint the paint object - * @param pointsList the points to be rendered - * @param seriesRenderer the series renderer - * @param yAxisValue the y axis value in pixels - * @param seriesIndex the series index - * @param or the orientation - * @param startIndex the start index of the rendering points - */ - protected void drawSeries(XYSeries series, Canvas canvas, Paint paint, List pointsList, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, Orientation or, - int startIndex) { - BasicStroke stroke = seriesRenderer.getStroke(); - Cap cap = paint.getStrokeCap(); - Join join = paint.getStrokeJoin(); - float miter = paint.getStrokeMiter(); - PathEffect pathEffect = paint.getPathEffect(); - Style style = paint.getStyle(); - if (stroke != null) { - PathEffect effect = null; - if (stroke.getIntervals() != null) { - effect = new DashPathEffect(stroke.getIntervals(), stroke.getPhase()); - } - setStroke(stroke.getCap(), stroke.getJoin(), stroke.getMiter(), Style.FILL_AND_STROKE, - effect, paint); - } - float[] points = MathHelper.getFloats(pointsList); - drawSeries(canvas, paint, points, seriesRenderer, yAxisValue, seriesIndex, startIndex); - if (isRenderPoints(seriesRenderer)) { - ScatterChart pointsChart = getPointsChart(); - if (pointsChart != null) { - pointsChart.drawSeries(canvas, paint, points, seriesRenderer, yAxisValue, seriesIndex, - startIndex); - } - } - paint.setTextSize(seriesRenderer.getChartValuesTextSize()); - if (or == Orientation.HORIZONTAL) { - paint.setTextAlign(Align.CENTER); - } else { - paint.setTextAlign(Align.LEFT); - } - if (seriesRenderer.isDisplayChartValues()) { - paint.setTextAlign(seriesRenderer.getChartValuesTextAlign()); - drawChartValuesText(canvas, series, seriesRenderer, paint, points, seriesIndex, startIndex); - } - if (stroke != null) { - setStroke(cap, join, miter, style, pathEffect, paint); - } - } - - private void setStroke(Cap cap, Join join, float miter, Style style, PathEffect pathEffect, - Paint paint) { - paint.setStrokeCap(cap); - paint.setStrokeJoin(join); - paint.setStrokeMiter(miter); - paint.setPathEffect(pathEffect); - paint.setStyle(style); - } - - /** - * The graphical representation of the series values as text. - * - * @param canvas the canvas to paint to - * @param series the series to be painted - * @param renderer the series renderer - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer, - Paint paint, float[] points, int seriesIndex, int startIndex) { - if (points.length > 1) { // there are more than one point - // record the first point's position - float previousPointX = points[0]; - float previousPointY = points[1]; - for (int k = 0; k < points.length; k += 2) { - if (k == 2) { // decide whether to display first two points' values or not - if (Math.abs(points[2]- points[0]) > 100 || Math.abs(points[3] - points[1]) > 100) { - // first point - drawText(canvas, getLabel(series.getY(startIndex)), points[0], points[1] - - renderer.getChartValuesSpacing(), paint, 0); - // second point - drawText(canvas, getLabel(series.getY(startIndex + 1)), points[2], points[3] - - renderer.getChartValuesSpacing(), paint, 0); - - previousPointX = points[2]; - previousPointY = points[3]; - } - } else if (k > 2) { - // compare current point's position with the previous point's, if they are not too close, display - if (Math.abs(points[k]- previousPointX) > 100 || Math.abs(points[k+1] - previousPointY) > 100) { - drawText(canvas, getLabel(series.getY(startIndex + k / 2)), points[k], points[k + 1] - - renderer.getChartValuesSpacing(), paint, 0); - previousPointX = points[k]; - previousPointY = points[k+1]; - } - } - } - } else { // if only one point, display it - for (int k = 0; k < points.length; k += 2) { - drawText(canvas, getLabel(series.getY(startIndex + k / 2)), points[k], points[k + 1] - - renderer.getChartValuesSpacing(), paint, 0); - } - } - } - - /** - * The graphical representation of a text, to handle both HORIZONTAL and - * VERTICAL orientations and extra rotation angles. - * - * @param canvas the canvas to paint to - * @param text the text to be rendered - * @param x the X axis location of the text - * @param y the Y axis location of the text - * @param paint the paint to be used for drawing - * @param extraAngle the text angle - */ - protected void drawText(Canvas canvas, String text, float x, float y, Paint paint, - float extraAngle) { - float angle = -mRenderer.getOrientation().getAngle() + extraAngle; - if (angle != 0) { - // canvas.scale(1 / mScale, mScale); - canvas.rotate(angle, x, y); - } - drawString(canvas, text, x, y, paint); - if (angle != 0) { - canvas.rotate(-angle, x, y); - // canvas.scale(mScale, 1 / mScale); - } - } - - /** - * Transform the canvas such as it can handle both HORIZONTAL and VERTICAL - * orientations. - * - * @param canvas the canvas to paint to - * @param angle the angle of rotation - * @param inverse if the inverse transform needs to be applied - */ - private void transform(Canvas canvas, float angle, boolean inverse) { - if (inverse) { - canvas.scale(1 / mScale, mScale); - canvas.translate(mTranslate, -mTranslate); - canvas.rotate(-angle, mCenter.getX(), mCenter.getY()); - } else { - canvas.rotate(angle, mCenter.getX(), mCenter.getY()); - canvas.translate(-mTranslate, mTranslate); - canvas.scale(mScale, 1 / mScale); - } - } - - /** - * The graphical representation of the labels on the X axis. - * - * @param xLabels the X labels values - * @param xTextLabelLocations the X text label locations - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param left the left value of the labels area - * @param top the top value of the labels area - * @param bottom the bottom value of the labels area - * @param xPixelsPerUnit the amount of pixels per one unit in the chart labels - * @param minX the minimum value on the X axis in the chart - * @param maxX the maximum value on the X axis in the chart - */ - protected void drawXLabels(List xLabels, Double[] xTextLabelLocations, Canvas canvas, - Paint paint, int left, int top, int bottom, double xPixelsPerUnit, double minX, double maxX) { - int length = xLabels.size(); - boolean showLabels = mRenderer.isShowLabels(); - boolean showGridY = mRenderer.isShowGridY(); - for (int i = 0; i < length; i++) { - double label = xLabels.get(i); - float xLabel = (float) (left + xPixelsPerUnit * (label - minX)); - if (showLabels) { - paint.setColor(mRenderer.getXLabelsColor()); - canvas.drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint); - drawText(canvas, getLabel(label), xLabel, bottom + mRenderer.getLabelsTextSize() * 4 / 3, - paint, mRenderer.getXLabelsAngle()); - } - if (showGridY) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(xLabel, bottom, xLabel, top, paint); - } - } - drawXTextLabels(xTextLabelLocations, canvas, paint, showLabels, left, top, bottom, - xPixelsPerUnit, minX, maxX); - } - - /** - * The graphical representation of the labels on the X axis. - * - * @param allYLabels the Y labels values - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param maxScaleNumber the maximum scale number - * @param left the left value of the labels area - * @param right the right value of the labels area - * @param bottom the bottom value of the labels area - * @param yPixelsPerUnit the amount of pixels per one unit in the chart labels - * @param minY the minimum value on the Y axis in the chart - */ - protected void drawYLabels(Map> allYLabels, Canvas canvas, Paint paint, - int maxScaleNumber, int left, int right, int bottom, double[] yPixelsPerUnit, double[] minY) { - Orientation or = mRenderer.getOrientation(); - boolean showGridX = mRenderer.isShowGridX(); - boolean showLabels = mRenderer.isShowLabels(); - for (int i = 0; i < maxScaleNumber; i++) { - paint.setTextAlign(mRenderer.getYLabelsAlign(i)); - List yLabels = allYLabels.get(i); - int length = yLabels.size(); - for (int j = 0; j < length; j++) { - double label = yLabels.get(j); - Align axisAlign = mRenderer.getYAxisAlign(i); - boolean textLabel = mRenderer.getYTextLabel(label, i) != null; - float yLabel = (float) (bottom - yPixelsPerUnit[i] * (label - minY[i])); - if (or == Orientation.HORIZONTAL) { - if (showLabels && !textLabel) { - paint.setColor(mRenderer.getYLabelsColor(i)); - if (axisAlign == Align.LEFT) { - canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint); - drawText(canvas, getLabel(label), left, yLabel - 2, paint, - mRenderer.getYLabelsAngle()); - } else { - canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint); - drawText(canvas, getLabel(label), right, yLabel - 2, paint, - mRenderer.getYLabelsAngle()); - } - } - if (showGridX) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(left, yLabel, right, yLabel, paint); - } - } else if (or == Orientation.VERTICAL) { - if (showLabels && !textLabel) { - paint.setColor(mRenderer.getYLabelsColor(i)); - canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint); - drawText(canvas, getLabel(label), right + 10, yLabel - 2, paint, - mRenderer.getYLabelsAngle()); - } - if (showGridX) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(right, yLabel, left, yLabel, paint); - } - } - } - } - } - - /** - * The graphical representation of the text labels on the X axis. - * - * @param xTextLabelLocations the X text label locations - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param left the left value of the labels area - * @param top the top value of the labels area - * @param bottom the bottom value of the labels area - * @param xPixelsPerUnit the amount of pixels per one unit in the chart labels - * @param minX the minimum value on the X axis in the chart - * @param maxX the maximum value on the X axis in the chart - */ - protected void drawXTextLabels(Double[] xTextLabelLocations, Canvas canvas, Paint paint, - boolean showLabels, int left, int top, int bottom, double xPixelsPerUnit, double minX, - double maxX) { - boolean showCustomTextGrid = mRenderer.isShowCustomTextGrid(); - if (showLabels) { - paint.setColor(mRenderer.getXLabelsColor()); - for (Double location : xTextLabelLocations) { - if (minX <= location && location <= maxX) { - float xLabel = (float) (left + xPixelsPerUnit * (location.doubleValue() - minX)); - paint.setColor(mRenderer.getXLabelsColor()); - canvas - .drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint); - drawText(canvas, mRenderer.getXTextLabel(location), xLabel, - bottom + mRenderer.getLabelsTextSize() * 4 / 3, paint, mRenderer.getXLabelsAngle()); - if (showCustomTextGrid) { - paint.setColor(mRenderer.getGridColor()); - canvas.drawLine(xLabel, bottom, xLabel, top, paint); - } - } - } - } - } - - // TODO: docs - public XYMultipleSeriesRenderer getRenderer() { - return mRenderer; - } - - public XYMultipleSeriesDataset getDataset() { - return mDataset; - } - - public double[] getCalcRange(int scale) { - return mCalcRange.get(scale); - } - - public void setCalcRange(double[] range, int scale) { - mCalcRange.put(scale, range); - } - - public double[] toRealPoint(float screenX, float screenY) { - return toRealPoint(screenX, screenY, 0); - } - - public double[] toScreenPoint(double[] realPoint) { - return toScreenPoint(realPoint, 0); - } - - private int getLabelLinePos(Align align) { - int pos = 4; - if (align == Align.LEFT) { - pos = -pos; - } - return pos; - } - - /** - * Transforms a screen point to a real coordinates point. - * - * @param screenX the screen x axis value - * @param screenY the screen y axis value - * @return the real coordinates point - */ - public double[] toRealPoint(float screenX, float screenY, int scale) { - double realMinX = mRenderer.getXAxisMin(scale); - double realMaxX = mRenderer.getXAxisMax(scale); - double realMinY = mRenderer.getYAxisMin(scale); - double realMaxY = mRenderer.getYAxisMax(scale); - return new double[] { - (screenX - mScreenR.left) * (realMaxX - realMinX) / mScreenR.width() + realMinX, - (mScreenR.top + mScreenR.height() - screenY) * (realMaxY - realMinY) / mScreenR.height() - + realMinY }; - } - - public double[] toScreenPoint(double[] realPoint, int scale) { - double realMinX = mRenderer.getXAxisMin(scale); - double realMaxX = mRenderer.getXAxisMax(scale); - double realMinY = mRenderer.getYAxisMin(scale); - double realMaxY = mRenderer.getYAxisMax(scale); - if (!mRenderer.isMinXSet(scale) || !mRenderer.isMaxXSet(scale) || !mRenderer.isMinXSet(scale) - || !mRenderer.isMaxYSet(scale)) { - double[] calcRange = getCalcRange(scale); - realMinX = calcRange[0]; - realMaxX = calcRange[1]; - realMinY = calcRange[2]; - realMaxY = calcRange[3]; - } - return new double[] { - (realPoint[0] - realMinX) * mScreenR.width() / (realMaxX - realMinX) + mScreenR.left, - (realMaxY - realPoint[1]) * mScreenR.height() / (realMaxY - realMinY) + mScreenR.top }; - } - - public SeriesSelection getSeriesAndPointForScreenCoordinate(final Point screenPoint) { - if (clickableAreas != null) - for (int seriesIndex = clickableAreas.size() - 1; seriesIndex >= 0; seriesIndex--) { - // series 0 is drawn first. Then series 1 is drawn on top, and series 2 - // on top of that. - // we want to know what the user clicked on, so traverse them in the - // order they appear on the screen. - int pointIndex = 0; - if (clickableAreas.get(seriesIndex) != null) { - RectF rectangle; - for (ClickableArea area : clickableAreas.get(seriesIndex)) { - rectangle = area.getRect(); - if (rectangle != null && rectangle.contains(screenPoint.getX(), screenPoint.getY())) { - return new SeriesSelection(seriesIndex, pointIndex, area.getX(), area.getY()); - } - pointIndex++; - } - } - } - return super.getSeriesAndPointForScreenCoordinate(screenPoint); - } - - /** - * The graphical representation of a series. - * - * @param canvas the canvas to paint to - * @param paint the paint to be used for drawing - * @param points the array of points to be used for drawing the series - * @param seriesRenderer the series renderer - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series currently being drawn - * @param startIndex the start index of the rendering points - */ - public abstract void drawSeries(Canvas canvas, Paint paint, float[] points, - SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex); - - /** - * Returns the clickable areas for all passed points - * - * @param points the array of points - * @param values the array of values of each point - * @param yAxisValue the minimum value of the y axis - * @param seriesIndex the index of the series to which the points belong - * @return an array of rectangles with the clickable area - * @param startIndex the start index of the rendering points - */ - protected abstract ClickableArea[] clickableAreasForPoints(float[] points, double[] values, - float yAxisValue, int seriesIndex, int startIndex); - - /** - * Returns if the chart should display the null values. - * - * @return if null values should be rendered - */ - protected boolean isRenderNullValues() { - return false; - } - - /** - * Returns if the chart should display the points as a certain shape. - * - * @param renderer the series renderer - */ - public boolean isRenderPoints(SimpleSeriesRenderer renderer) { - return false; - } - - /** - * Returns the default axis minimum. - * - * @return the default axis minimum - */ - public double getDefaultMinimum() { - return MathHelper.NULL_VALUE; - } - - /** - * Returns the scatter chart to be used for drawing the data points. - * - * @return the data points scatter chart - */ - public ScatterChart getPointsChart() { - return null; - } - - /** - * Returns the chart type identifier. - * - * @return the chart type - */ - public abstract String getChartType(); - -} diff --git a/android-libraries/achartengine/src/org/achartengine/chart/package.html b/android-libraries/achartengine/src/org/achartengine/chart/package.html deleted file mode 100644 index 2c5fbec1..00000000 --- a/android-libraries/achartengine/src/org/achartengine/chart/package.html +++ /dev/null @@ -1,6 +0,0 @@ - -AChartEngine - -Provides the classes that handle the actual rendering / drawing of the charts, based on the provided model and renderer. - - \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/image/zoom-1.png b/android-libraries/achartengine/src/org/achartengine/image/zoom-1.png deleted file mode 100644 index 8265f278..00000000 Binary files a/android-libraries/achartengine/src/org/achartengine/image/zoom-1.png and /dev/null differ diff --git a/android-libraries/achartengine/src/org/achartengine/image/zoom_in.png b/android-libraries/achartengine/src/org/achartengine/image/zoom_in.png deleted file mode 100644 index 1ac4864d..00000000 Binary files a/android-libraries/achartengine/src/org/achartengine/image/zoom_in.png and /dev/null differ diff --git a/android-libraries/achartengine/src/org/achartengine/image/zoom_out.png b/android-libraries/achartengine/src/org/achartengine/image/zoom_out.png deleted file mode 100644 index d67a87de..00000000 Binary files a/android-libraries/achartengine/src/org/achartengine/image/zoom_out.png and /dev/null differ diff --git a/android-libraries/achartengine/src/org/achartengine/model/CategorySeries.java b/android-libraries/achartengine/src/org/achartengine/model/CategorySeries.java deleted file mode 100644 index ae31c7dd..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/CategorySeries.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * A series for the category charts like the pie ones. - */ -public class CategorySeries implements Serializable { - /** The series title. */ - private String mTitle; - /** The series categories. */ - private List mCategories = new ArrayList(); - /** The series values. */ - private List mValues = new ArrayList(); - - /** - * Builds a new category series. - * - * @param title the series title - */ - public CategorySeries(String title) { - mTitle = title; - } - - /** - * Returns the series title. - * - * @return the series title - */ - public String getTitle() { - return mTitle; - } - - /** - * Adds a new value to the series - * - * @param value the new value - */ - public synchronized void add(double value) { - add(mCategories.size() + "", value); - } - - /** - * Adds a new value to the series. - * - * @param category the category - * @param value the new value - */ - public synchronized void add(String category, double value) { - mCategories.add(category); - mValues.add(value); - } - - /** - * Replaces the value at the specific index in the series. - * - * @param index the index in the series - * @param category the category - * @param value the new value - */ - public synchronized void set(int index, String category, double value) { - mCategories.set(index, category); - mValues.set(index, value); - } - - /** - * Removes an existing value from the series. - * - * @param index the index in the series of the value to remove - */ - public synchronized void remove(int index) { - mCategories.remove(index); - mValues.remove(index); - } - - /** - * Removes all the existing values from the series. - */ - public synchronized void clear() { - mCategories.clear(); - mValues.clear(); - } - - /** - * Returns the value at the specified index. - * - * @param index the index - * @return the value at the index - */ - public synchronized double getValue(int index) { - return mValues.get(index); - } - - /** - * Returns the category name at the specified index. - * - * @param index the index - * @return the category name at the index - */ - public synchronized String getCategory(int index) { - return mCategories.get(index); - } - - /** - * Returns the series item count. - * - * @return the series item count - */ - public synchronized int getItemCount() { - return mCategories.size(); - } - - /** - * Transforms the category series to an XY series. - * - * @return the XY series - */ - public XYSeries toXYSeries() { - XYSeries xySeries = new XYSeries(mTitle); - int k = 0; - for (double value : mValues) { - xySeries.add(++k, value); - } - return xySeries; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/MultipleCategorySeries.java b/android-libraries/achartengine/src/org/achartengine/model/MultipleCategorySeries.java deleted file mode 100644 index 992db4c1..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/MultipleCategorySeries.java +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * A series for the multiple category charts like the doughnut. - */ -public class MultipleCategorySeries implements Serializable { - /** The series title. */ - private String mTitle; - /** The series local keys. */ - private List mCategories = new ArrayList(); - /** The series name. */ - private List mTitles = new ArrayList(); - /** The series values. */ - private List mValues = new ArrayList(); - - /** - * Builds a new category series. - * - * @param title the series title - */ - public MultipleCategorySeries(String title) { - mTitle = title; - } - - /** - * Adds a new value to the series - * - * @param titles the titles to be used as labels - * @param values the new value - */ - public void add(String[] titles, double[] values) { - add(mCategories.size() + "", titles, values); - } - - /** - * Adds a new value to the series. - * - * @param category the category name - * @param titles the titles to be used as labels - * @param values the new value - */ - public void add(String category, String[] titles, double[] values) { - mCategories.add(category); - mTitles.add(titles); - mValues.add(values); - } - - /** - * Removes an existing value from the series. - * - * @param index the index in the series of the value to remove - */ - public void remove(int index) { - mCategories.remove(index); - mTitles.remove(index); - mValues.remove(index); - } - - /** - * Removes all the existing values from the series. - */ - public void clear() { - mCategories.clear(); - mTitles.clear(); - mValues.clear(); - } - - /** - * Returns the values at the specified index. - * - * @param index the index - * @return the value at the index - */ - public double[] getValues(int index) { - return mValues.get(index); - } - - /** - * Returns the category name at the specified index. - * - * @param index the index - * @return the category name at the index - */ - public String getCategory(int index) { - return mCategories.get(index); - } - - /** - * Returns the categories count. - * - * @return the categories count - */ - public int getCategoriesCount() { - return mCategories.size(); - } - - /** - * Returns the series item count. - * - * @param index the index - * @return the series item count - */ - public int getItemCount(int index) { - return mValues.get(index).length; - } - - /** - * Returns the series titles. - * - * @param index the index - * @return the series titles - */ - public String[] getTitles(int index) { - return mTitles.get(index); - } - - /** - * Transforms the category series to an XY series. - * - * @return the XY series - */ - public XYSeries toXYSeries() { - XYSeries xySeries = new XYSeries(mTitle); - return xySeries; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/Point.java b/android-libraries/achartengine/src/org/achartengine/model/Point.java deleted file mode 100644 index 4d2767cf..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/Point.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.io.Serializable; - -/** - * A class to encapsulate the definition of a point. - */ -public final class Point implements Serializable { - /** The X axis coordinate value. */ - private float mX; - /** The Y axis coordinate value. */ - private float mY; - - public Point() { - } - - public Point(float x, float y) { - mX = x; - mY = y; - } - - public float getX() { - return mX; - } - - public float getY() { - return mY; - } - - public void setX(float x) { - mX = x; - } - - public void setY(float y) { - mY = y; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/RangeCategorySeries.java b/android-libraries/achartengine/src/org/achartengine/model/RangeCategorySeries.java deleted file mode 100644 index c004fa10..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/RangeCategorySeries.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.util.ArrayList; -import java.util.List; -/** - * A series for the range category charts like the range bar. - */ -public class RangeCategorySeries extends CategorySeries { - /** The series values. */ - private List mMaxValues = new ArrayList(); - /** - * Builds a new category series. - * - * @param title the series title - */ - public RangeCategorySeries(String title) { - super(title); - } - /** - * Adds new values to the series - * - * @param minValue the new minimum value - * @param maxValue the new maximum value - */ - public synchronized void add(double minValue, double maxValue) { - super.add(minValue); - mMaxValues.add(maxValue); - } - - /** - * Adds new values to the series. - * - * @param category the category - * @param minValue the new minimum value - * @param maxValue the new maximum value - */ - public synchronized void add(String category, double minValue, double maxValue) { - super.add(category, minValue); - mMaxValues.add(maxValue); - } - - /** - * Removes existing values from the series. - * - * @param index the index in the series of the values to remove - */ - public synchronized void remove(int index) { - super.remove(index); - mMaxValues.remove(index); - } - - /** - * Removes all the existing values from the series. - */ - public synchronized void clear() { - super.clear(); - mMaxValues.clear(); - } - - /** - * Returns the minimum value at the specified index. - * - * @param index the index - * @return the minimum value at the index - */ - public double getMinimumValue(int index) { - return getValue(index); - } - - /** - * Returns the maximum value at the specified index. - * - * @param index the index - * @return the maximum value at the index - */ - public double getMaximumValue(int index) { - return mMaxValues.get(index); - } - - /** - * Transforms the range category series to an XY series. - * - * @return the XY series - */ - public XYSeries toXYSeries() { - XYSeries xySeries = new XYSeries(getTitle()); - int length = getItemCount(); - for (int k = 0; k < length; k++) { - xySeries.add(k + 1, getMinimumValue(k)); - // the new fast XYSeries implementation doesn't allow 2 values at the same X, - // so I had to do a hack until I find a better solution - xySeries.add(k + 1.000001, getMaximumValue(k)); - } - return xySeries; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/SeriesSelection.java b/android-libraries/achartengine/src/org/achartengine/model/SeriesSelection.java deleted file mode 100644 index 4319c742..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/SeriesSelection.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -public class SeriesSelection { - private int mSeriesIndex; - - private int mPointIndex; - - private double mXValue; - - private double mValue; - - public SeriesSelection(int seriesIndex, int pointIndex, double xValue, double value) { - mSeriesIndex = seriesIndex; - mPointIndex = pointIndex; - mXValue = xValue; - mValue = value; - } - - public int getSeriesIndex() { - return mSeriesIndex; - } - - public int getPointIndex() { - return mPointIndex; - } - - public double getXValue() { - return mXValue; - } - - public double getValue() { - return mValue; - } -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/model/TimeSeries.java b/android-libraries/achartengine/src/org/achartengine/model/TimeSeries.java deleted file mode 100644 index 6b9a18e5..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/TimeSeries.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.util.Date; - -/** - * A series for the date / time charts. - */ -public class TimeSeries extends XYSeries { - - /** - * Builds a new date / time series. - * - * @param title the series title - */ - public TimeSeries(String title) { - super(title); - } - - /** - * Adds a new value to the series. - * - * @param x the date / time value for the X axis - * @param y the value for the Y axis - */ - public synchronized void add(Date x, double y) { - super.add(x.getTime(), y); - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/XYMultipleSeriesDataset.java b/android-libraries/achartengine/src/org/achartengine/model/XYMultipleSeriesDataset.java deleted file mode 100644 index 6ac6a6de..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/XYMultipleSeriesDataset.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -/** - * A series that includes 0 to many XYSeries. - */ -public class XYMultipleSeriesDataset implements Serializable { - /** The included series. */ - private List mSeries = new ArrayList(); - - /** - * Adds a new XY series to the list. - * - * @param series the XY series to ass - */ - public synchronized void addSeries(XYSeries series) { - mSeries.add(series); - } - - /** - * Adds a new XY series to the list. - * - * @param index the index in the series list - * @param series the XY series to ass - */ - public synchronized void addSeries(int index, XYSeries series) { - mSeries.add(index, series); - } - - /** - * Removes the XY series from the list. - * - * @param index the index in the series list of the series to remove - */ - public synchronized void removeSeries(int index) { - mSeries.remove(index); - } - - /** - * Removes the XY series from the list. - * - * @param series the XY series to be removed - */ - public synchronized void removeSeries(XYSeries series) { - mSeries.remove(series); - } - - /** - * Returns the XY series at the specified index. - * - * @param index the index - * @return the XY series at the index - */ - public synchronized XYSeries getSeriesAt(int index) { - return mSeries.get(index); - } - - /** - * Returns the XY series count. - * - * @return the XY series count - */ - public synchronized int getSeriesCount() { - return mSeries.size(); - } - - /** - * Returns an array of the XY series. - * - * @return the XY series array - */ - public synchronized XYSeries[] getSeries() { - return mSeries.toArray(new XYSeries[0]); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/XYSeries.java b/android-libraries/achartengine/src/org/achartengine/model/XYSeries.java deleted file mode 100644 index 56063b77..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/XYSeries.java +++ /dev/null @@ -1,255 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.SortedMap; - -import org.achartengine.util.IndexXYMap; -import org.achartengine.util.MathHelper; -import org.achartengine.util.XYEntry; - -/** - * An XY series encapsulates values for XY charts like line, time, area, - * scatter... charts. - */ -public class XYSeries implements Serializable { - /** The series title. */ - private String mTitle; - /** A map to contain values for X and Y axes and index for each bundle */ - private final IndexXYMap mXY = new IndexXYMap(); - /** The minimum value for the X axis. */ - private double mMinX = MathHelper.NULL_VALUE; - /** The maximum value for the X axis. */ - private double mMaxX = -MathHelper.NULL_VALUE; - /** The minimum value for the Y axis. */ - private double mMinY = MathHelper.NULL_VALUE; - /** The maximum value for the Y axis. */ - private double mMaxY = -MathHelper.NULL_VALUE; - /** The scale number for this series. */ - private final int mScaleNumber; - - /** - * Builds a new XY series. - * - * @param title the series title. - */ - public XYSeries(String title) { - this(title, 0); - } - - /** - * Builds a new XY series. - * - * @param title the series title. - * @param scaleNumber the series scale number - */ - public XYSeries(String title, int scaleNumber) { - mTitle = title; - mScaleNumber = scaleNumber; - initRange(); - } - - public int getScaleNumber() { - return mScaleNumber; - } - - /** - * Initializes the range for both axes. - */ - private void initRange() { - mMinX = MathHelper.NULL_VALUE; - mMaxX = -MathHelper.NULL_VALUE; - mMinY = MathHelper.NULL_VALUE; - mMaxY = -MathHelper.NULL_VALUE; - int length = getItemCount(); - for (int k = 0; k < length; k++) { - double x = getX(k); - double y = getY(k); - updateRange(x, y); - } - } - - /** - * Updates the range on both axes. - * - * @param x the new x value - * @param y the new y value - */ - private void updateRange(double x, double y) { - mMinX = Math.min(mMinX, x); - mMaxX = Math.max(mMaxX, x); - mMinY = Math.min(mMinY, y); - mMaxY = Math.max(mMaxY, y); - } - - /** - * Returns the series title. - * - * @return the series title - */ - public String getTitle() { - return mTitle; - } - - /** - * Sets the series title. - * - * @param title the series title - */ - public void setTitle(String title) { - mTitle = title; - } - - /** - * Adds a new value to the series. - * - * @param x the value for the X axis - * @param y the value for the Y axis - */ - public synchronized void add(double x, double y) { - mXY.put(x, y); - updateRange(x, y); - } - - /** - * Removes an existing value from the series. - * - * @param index the index in the series of the value to remove - */ - public synchronized void remove(int index) { - XYEntry removedEntry = mXY.removeByIndex(index); - double removedX = removedEntry.getKey(); - double removedY = removedEntry.getValue(); - if (removedX == mMinX || removedX == mMaxX || removedY == mMinY || removedY == mMaxY) { - initRange(); - } - } - - /** - * Removes all the existing values from the series. - */ - public synchronized void clear() { - mXY.clear(); - initRange(); - } - - /** - * Returns the X axis value at the specified index. - * - * @param index the index - * @return the X value - */ - public synchronized double getX(int index) { - return mXY.getXByIndex(index); - } - - /** - * Returns the Y axis value at the specified index. - * - * @param index the index - * @return the Y value - */ - public synchronized double getY(int index) { - return mXY.getYByIndex(index); - } - - /** - * Returns submap of x and y values according to the given start and end - * - * @param start start x value - * @param stop stop x value - * @return a submap of x and y values - */ - public synchronized SortedMap getRange(double start, double stop, - int beforeAfterPoints) { - // we need to add one point before the start and one point after the end (if - // there are any) - // to ensure that line doesn't end before the end of the screen - - // this would be simply: start = mXY.lowerKey(start) but NavigableMap is - // available since API 9 - SortedMap headMap = mXY.headMap(start); - if (!headMap.isEmpty()) { - start = headMap.lastKey(); - } - - // this would be simply: end = mXY.higherKey(end) but NavigableMap is - // available since API 9 - // so we have to do this hack in order to support older versions - SortedMap tailMap = mXY.tailMap(stop); - if (!tailMap.isEmpty()) { - Iterator tailIterator = tailMap.keySet().iterator(); - Double next = tailIterator.next(); - if (tailIterator.hasNext()) { - stop = tailIterator.next(); - } else { - stop += next; - } - } - return mXY.subMap(start, stop); - } - - public int getIndexForKey(double key) { - return mXY.getIndexForKey(key); - } - - /** - * Returns the series item count. - * - * @return the series item count - */ - public synchronized int getItemCount() { - return mXY.size(); - } - - /** - * Returns the minimum value on the X axis. - * - * @return the X axis minimum value - */ - public double getMinX() { - return mMinX; - } - - /** - * Returns the minimum value on the Y axis. - * - * @return the Y axis minimum value - */ - public double getMinY() { - return mMinY; - } - - /** - * Returns the maximum value on the X axis. - * - * @return the X axis maximum value - */ - public double getMaxX() { - return mMaxX; - } - - /** - * Returns the maximum value on the Y axis. - * - * @return the Y axis maximum value - */ - public double getMaxY() { - return mMaxY; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/XYValueSeries.java b/android-libraries/achartengine/src/org/achartengine/model/XYValueSeries.java deleted file mode 100644 index 81aff28b..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/XYValueSeries.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.model; - -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.util.MathHelper; - -/** - * An extension of the XY series which adds a third dimension. It is used for XY - * charts like bubble. - */ -public class XYValueSeries extends XYSeries { - /** A list to contain the series values. */ - private List mValue = new ArrayList(); - /** The minimum value. */ - private double mMinValue = MathHelper.NULL_VALUE; - /** The maximum value. */ - private double mMaxValue = -MathHelper.NULL_VALUE; - - /** - * Builds a new XY value series. - * - * @param title the series title. - */ - public XYValueSeries(String title) { - super(title); - } - - /** - * Adds a new value to the series. - * - * @param x the value for the X axis - * @param y the value for the Y axis - * @param value the value - */ - public synchronized void add(double x, double y, double value) { - super.add(x, y); - mValue.add(value); - updateRange(value); - } - - /** - * Initializes the values range. - */ - private void initRange() { - mMinValue = MathHelper.NULL_VALUE; - mMaxValue = MathHelper.NULL_VALUE; - int length = getItemCount(); - for (int k = 0; k < length; k++) { - updateRange(getValue(k)); - } - } - - /** - * Updates the values range. - * - * @param value the new value - */ - private void updateRange(double value) { - mMinValue = Math.min(mMinValue, value); - mMaxValue = Math.max(mMaxValue, value); - } - - /** - * Adds a new value to the series. - * - * @param x the value for the X axis - * @param y the value for the Y axis - */ - public synchronized void add(double x, double y) { - add(x, y, 0d); - } - - /** - * Removes an existing value from the series. - * - * @param index the index in the series of the value to remove - */ - public synchronized void remove(int index) { - super.remove(index); - double removedValue = mValue.remove(index); - if (removedValue == mMinValue || removedValue == mMaxValue) { - initRange(); - } - } - - /** - * Removes all the values from the series. - */ - public synchronized void clear() { - super.clear(); - mValue.clear(); - initRange(); - } - - /** - * Returns the value at the specified index. - * - * @param index the index - * @return the value - */ - public synchronized double getValue(int index) { - return mValue.get(index); - } - - /** - * Returns the minimum value. - * - * @return the minimum value - */ - public double getMinValue() { - return mMinValue; - } - - /** - * Returns the maximum value. - * - * @return the maximum value - */ - public double getMaxValue() { - return mMaxValue; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/model/package.html b/android-libraries/achartengine/src/org/achartengine/model/package.html deleted file mode 100644 index 6135d29c..00000000 --- a/android-libraries/achartengine/src/org/achartengine/model/package.html +++ /dev/null @@ -1,6 +0,0 @@ - -AChartEngine - -Provides the classes that handle the data values (data model) to be used by displaying the charts. - - \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/package.html b/android-libraries/achartengine/src/org/achartengine/package.html deleted file mode 100644 index b26cf259..00000000 --- a/android-libraries/achartengine/src/org/achartengine/package.html +++ /dev/null @@ -1,6 +0,0 @@ - -AChartEngine - -The main classes, including the ChartFactory, GraphicalActivity and GraphicalView. - - \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/BasicStroke.java b/android-libraries/achartengine/src/org/achartengine/renderer/BasicStroke.java deleted file mode 100644 index 3ac93d54..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/BasicStroke.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.renderer; - -import java.io.Serializable; - -import android.graphics.Paint.Cap; -import android.graphics.Paint.Join; - -/** - * A descriptor for the stroke style. - */ -public class BasicStroke implements Serializable { - /** The solid line style. */ - public static final BasicStroke SOLID = new BasicStroke(Cap.BUTT, Join.MITER, 4, null, 0); - /** The dashed line style. */ - public static final BasicStroke DASHED = new BasicStroke(Cap.ROUND, Join.BEVEL, 10, new float[] { - 10, 10 }, 1); - /** The dot line style. */ - public static final BasicStroke DOTTED = new BasicStroke(Cap.ROUND, Join.BEVEL, 5, new float[] { - 2, 10 }, 1); - /** The stroke cap. */ - private Cap mCap; - /** The stroke join. */ - private Join mJoin; - /** The stroke miter. */ - private float mMiter; - /** The path effect intervals. */ - private float[] mIntervals; - /** The path effect phase. */ - private float mPhase; - - /** - * Build a new basic stroke style. - * - * @param cap the stroke cap - * @param join the stroke join - * @param miter the stroke miter - * @param intervals the path effect intervals - * @param phase the path effect phase - */ - public BasicStroke(Cap cap, Join join, float miter, float[] intervals, float phase) { - mCap = cap; - mJoin = join; - mMiter = miter; - mIntervals = intervals; - } - - /** - * Returns the stroke cap. - * - * @return the stroke cap - */ - public Cap getCap() { - return mCap; - } - - /** - * Returns the stroke join. - * - * @return the stroke join - */ - public Join getJoin() { - return mJoin; - } - - /** - * Returns the stroke miter. - * - * @return the stroke miter - */ - public float getMiter() { - return mMiter; - } - - /** - * Returns the path effect intervals. - * - * @return the path effect intervals - */ - public float[] getIntervals() { - return mIntervals; - } - - /** - * Returns the path effect phase. - * - * @return the path effect phase - */ - public float getPhase() { - return mPhase; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/DefaultRenderer.java b/android-libraries/achartengine/src/org/achartengine/renderer/DefaultRenderer.java deleted file mode 100644 index 4dbb2549..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/DefaultRenderer.java +++ /dev/null @@ -1,750 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.renderer; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import android.graphics.Color; -import android.graphics.Typeface; - -/** - * An abstract renderer to be extended by the multiple series classes. - */ -public class DefaultRenderer implements Serializable { - /** The chart title. */ - private String mChartTitle = ""; - /** The chart title text size. */ - private float mChartTitleTextSize = 15; - /** A no color constant. */ - public static final int NO_COLOR = 0; - /** The default background color. */ - public static final int BACKGROUND_COLOR = Color.BLACK; - /** The default color for text. */ - public static final int TEXT_COLOR = Color.LTGRAY; - /** A text font for regular text, like the chart labels. */ - private static final Typeface REGULAR_TEXT_FONT = Typeface - .create(Typeface.SERIF, Typeface.NORMAL); - /** The typeface name for the texts. */ - private String mTextTypefaceName = REGULAR_TEXT_FONT.toString(); - /** The typeface style for the texts. */ - private int mTextTypefaceStyle = Typeface.NORMAL; - /** The chart background color. */ - private int mBackgroundColor; - /** If the background color is applied. */ - private boolean mApplyBackgroundColor; - /** If the axes are visible. */ - private boolean mShowAxes = true; - /** The axes color. */ - private int mAxesColor = TEXT_COLOR; - /** If the labels are visible. */ - private boolean mShowLabels = true; - /** The labels color. */ - private int mLabelsColor = TEXT_COLOR; - /** The labels text size. */ - private float mLabelsTextSize = 10; - /** If the legend is visible. */ - private boolean mShowLegend = true; - /** The legend text size. */ - private float mLegendTextSize = 12; - /** If the legend should size to fit. */ - private boolean mFitLegend = false; - /** If the X axis grid should be displayed. */ - private boolean mShowGridX = false; - /** If the Y axis grid should be displayed. */ - private boolean mShowGridY = false; - /** If the custom text grid should be displayed. */ - private boolean mShowCustomTextGrid = false; - /** The simple renderers that are included in this multiple series renderer. */ - private List mRenderers = new ArrayList(); - /** The antialiasing flag. */ - private boolean mAntialiasing = true; - /** The legend height. */ - private int mLegendHeight = 0; - /** The margins size. */ - private int[] mMargins = new int[] { 20, 30, 10, 20 }; - /** A value to be used for scaling the chart. */ - private float mScale = 1; - /** A flag for enabling the pan. */ - private boolean mPanEnabled = true; - /** A flag for enabling the zoom. */ - private boolean mZoomEnabled = true; - /** A flag for enabling the visibility of the zoom buttons. */ - private boolean mZoomButtonsVisible = false; - /** The zoom rate. */ - private float mZoomRate = 1.5f; - /** A flag for enabling the external zoom. */ - private boolean mExternalZoomEnabled = false; - /** The original chart scale. */ - private float mOriginalScale = mScale; - /** A flag for enabling the click on elements. */ - private boolean mClickEnabled = false; - /** The selectable radius around a clickable point. */ - private int selectableBuffer = 15; - /** If the chart should display the values (available for pie chart). */ - private boolean mDisplayValues; - - /** - * A flag to be set if the chart is inside a scroll and doesn't need to shrink - * when not enough space. - */ - private boolean mInScroll; - /** The start angle for circular charts such as pie, doughnut, etc. */ - private float mStartAngle = 0; - - /** - * Returns the chart title. - * - * @return the chart title - */ - public String getChartTitle() { - return mChartTitle; - } - - /** - * Sets the chart title. - * - * @param title the chart title - */ - public void setChartTitle(String title) { - mChartTitle = title; - } - - /** - * Returns the chart title text size. - * - * @return the chart title text size - */ - public float getChartTitleTextSize() { - return mChartTitleTextSize; - } - - /** - * Sets the chart title text size. - * - * @param textSize the chart title text size - */ - public void setChartTitleTextSize(float textSize) { - mChartTitleTextSize = textSize; - } - - /** - * Adds a simple renderer to the multiple renderer. - * - * @param renderer the renderer to be added - */ - public void addSeriesRenderer(SimpleSeriesRenderer renderer) { - mRenderers.add(renderer); - } - - /** - * Adds a simple renderer to the multiple renderer. - * - * @param index the index in the renderers list - * @param renderer the renderer to be added - */ - public void addSeriesRenderer(int index, SimpleSeriesRenderer renderer) { - mRenderers.add(index, renderer); - } - - /** - * Removes a simple renderer from the multiple renderer. - * - * @param renderer the renderer to be removed - */ - public void removeSeriesRenderer(SimpleSeriesRenderer renderer) { - mRenderers.remove(renderer); - } - - /** - * Removes all renderers from the multiple renderer. - */ - public void removeAllRenderers() { - mRenderers.clear(); - } - - /** - * Returns the simple renderer from the multiple renderer list. - * - * @param index the index in the simple renderers list - * @return the simple renderer at the specified index - */ - public SimpleSeriesRenderer getSeriesRendererAt(int index) { - return mRenderers.get(index); - } - - /** - * Returns the simple renderers count in the multiple renderer list. - * - * @return the simple renderers count - */ - public int getSeriesRendererCount() { - return mRenderers.size(); - } - - /** - * Returns an array of the simple renderers in the multiple renderer list. - * - * @return the simple renderers array - */ - public SimpleSeriesRenderer[] getSeriesRenderers() { - return mRenderers.toArray(new SimpleSeriesRenderer[0]); - } - - /** - * Returns the background color. - * - * @return the background color - */ - public int getBackgroundColor() { - return mBackgroundColor; - } - - /** - * Sets the background color. - * - * @param color the background color - */ - public void setBackgroundColor(int color) { - mBackgroundColor = color; - } - - /** - * Returns if the background color should be applied. - * - * @return the apply flag for the background color. - */ - public boolean isApplyBackgroundColor() { - return mApplyBackgroundColor; - } - - /** - * Sets if the background color should be applied. - * - * @param apply the apply flag for the background color - */ - public void setApplyBackgroundColor(boolean apply) { - mApplyBackgroundColor = apply; - } - - /** - * Returns the axes color. - * - * @return the axes color - */ - public int getAxesColor() { - return mAxesColor; - } - - /** - * Sets the axes color. - * - * @param color the axes color - */ - public void setAxesColor(int color) { - mAxesColor = color; - } - - /** - * Returns the labels color. - * - * @return the labels color - */ - public int getLabelsColor() { - return mLabelsColor; - } - - /** - * Sets the labels color. - * - * @param color the labels color - */ - public void setLabelsColor(int color) { - mLabelsColor = color; - } - - /** - * Returns the labels text size. - * - * @return the labels text size - */ - public float getLabelsTextSize() { - return mLabelsTextSize; - } - - /** - * Sets the labels text size. - * - * @param textSize the labels text size - */ - public void setLabelsTextSize(float textSize) { - mLabelsTextSize = textSize; - } - - /** - * Returns if the axes should be visible. - * - * @return the visibility flag for the axes - */ - public boolean isShowAxes() { - return mShowAxes; - } - - /** - * Sets if the axes should be visible. - * - * @param showAxes the visibility flag for the axes - */ - public void setShowAxes(boolean showAxes) { - mShowAxes = showAxes; - } - - /** - * Returns if the labels should be visible. - * - * @return the visibility flag for the labels - */ - public boolean isShowLabels() { - return mShowLabels; - } - - /** - * Sets if the labels should be visible. - * - * @param showLabels the visibility flag for the labels - */ - public void setShowLabels(boolean showLabels) { - mShowLabels = showLabels; - } - - /** - * Returns if the X axis grid should be visible. - * - * @return the visibility flag for the X axis grid - */ - public boolean isShowGridX() { - return mShowGridX; - } - - /** - * Returns if the Y axis grid should be visible. - * - * @return the visibility flag for the Y axis grid - */ - public boolean isShowGridY() { - return mShowGridY; - } - - /** - * Sets if the X axis grid should be visible. - * - * @param showGrid the visibility flag for the X axis grid - */ - public void setShowGridX(boolean showGrid) { - mShowGridX = showGrid; - } - - /** - * Sets if the Y axis grid should be visible. - * - * @param showGrid the visibility flag for the Y axis grid - */ - public void setShowGridY(boolean showGrid) { - mShowGridY = showGrid; - } - - /** - * Sets if the grid should be visible. - * - * @param showGrid the visibility flag for the grid - */ - public void setShowGrid(boolean showGrid) { - setShowGridX(showGrid); - setShowGridY(showGrid); - } - - /** - * Returns if the grid should be visible for custom X or Y labels. - * - * @return the visibility flag for the custom text grid - */ - public boolean isShowCustomTextGrid() { - return mShowCustomTextGrid; - } - - /** - * Sets if the grid for custom X or Y labels should be visible. - * - * @param showGrid the visibility flag for the custom text grid - */ - public void setShowCustomTextGrid(boolean showGrid) { - mShowCustomTextGrid = showGrid; - } - - /** - * Returns if the legend should be visible. - * - * @return the visibility flag for the legend - */ - public boolean isShowLegend() { - return mShowLegend; - } - - /** - * Sets if the legend should be visible. - * - * @param showLegend the visibility flag for the legend - */ - public void setShowLegend(boolean showLegend) { - mShowLegend = showLegend; - } - - /** - * Returns if the legend should size to fit. - * - * @return the fit behavior - */ - public boolean isFitLegend() { - return mFitLegend; - } - - /** - * Sets if the legend should size to fit. - * - * @param fit the fit behavior - */ - public void setFitLegend(boolean fit) { - mFitLegend = fit; - } - - /** - * Returns the text typeface name. - * - * @return the text typeface name - */ - public String getTextTypefaceName() { - return mTextTypefaceName; - } - - /** - * Returns the text typeface style. - * - * @return the text typeface style - */ - public int getTextTypefaceStyle() { - return mTextTypefaceStyle; - } - - /** - * Returns the legend text size. - * - * @return the legend text size - */ - public float getLegendTextSize() { - return mLegendTextSize; - } - - /** - * Sets the legend text size. - * - * @param textSize the legend text size - */ - public void setLegendTextSize(float textSize) { - mLegendTextSize = textSize; - } - - /** - * Sets the text typeface name and style. - * - * @param typefaceName the text typeface name - * @param style the text typeface style - */ - public void setTextTypeface(String typefaceName, int style) { - mTextTypefaceName = typefaceName; - mTextTypefaceStyle = style; - } - - /** - * Returns the antialiasing flag value. - * - * @return the antialiasing value - */ - public boolean isAntialiasing() { - return mAntialiasing; - } - - /** - * Sets the antialiasing value. - * - * @param antialiasing the antialiasing - */ - public void setAntialiasing(boolean antialiasing) { - mAntialiasing = antialiasing; - } - - /** - * Returns the value to be used for scaling the chart. - * - * @return the scale value - */ - public float getScale() { - return mScale; - } - - /** - * Returns the original value to be used for scaling the chart. - * - * @return the original scale value - */ - public float getOriginalScale() { - return mOriginalScale; - } - - /** - * Sets the value to be used for scaling the chart. It works on some charts - * like pie, doughnut, dial. - * - * @param scale the scale value - */ - public void setScale(float scale) { - mScale = scale; - } - - /** - * Returns the enabled state of the zoom. - * - * @return if zoom is enabled - */ - public boolean isZoomEnabled() { - return mZoomEnabled; - } - - /** - * Sets the enabled state of the zoom. - * - * @param enabled zoom enabled - */ - public void setZoomEnabled(boolean enabled) { - mZoomEnabled = enabled; - } - - /** - * Returns the visible state of the zoom buttons. - * - * @return if zoom buttons are visible - */ - public boolean isZoomButtonsVisible() { - return mZoomButtonsVisible; - } - - /** - * Sets the visible state of the zoom buttons. - * - * @param visible if the zoom buttons are visible - */ - public void setZoomButtonsVisible(boolean visible) { - mZoomButtonsVisible = visible; - } - - /** - * Returns the enabled state of the external (application implemented) zoom. - * - * @return if external zoom is enabled - */ - public boolean isExternalZoomEnabled() { - return mExternalZoomEnabled; - } - - /** - * Sets the enabled state of the external (application implemented) zoom. - * - * @param enabled external zoom enabled - */ - public void setExternalZoomEnabled(boolean enabled) { - mExternalZoomEnabled = enabled; - } - - /** - * Returns the zoom rate. - * - * @return the zoom rate - */ - public float getZoomRate() { - return mZoomRate; - } - - /** - * Returns the enabled state of the pan. - * - * @return if pan is enabled - */ - public boolean isPanEnabled() { - return mPanEnabled; - } - - /** - * Sets the enabled state of the pan. - * - * @param enabled pan enabled - */ - public void setPanEnabled(boolean enabled) { - mPanEnabled = enabled; - } - - /** - * Sets the zoom rate. - * - * @param rate the zoom rate - */ - public void setZoomRate(float rate) { - mZoomRate = rate; - } - - /** - * Returns the enabled state of the click. - * - * @return if click is enabled - */ - public boolean isClickEnabled() { - return mClickEnabled; - } - - /** - * Sets the enabled state of the click. - * - * @param enabled click enabled - */ - public void setClickEnabled(boolean enabled) { - mClickEnabled = enabled; - } - - /** - * Returns the selectable radius value around clickable points. - * - * @return the selectable radius - */ - public int getSelectableBuffer() { - return selectableBuffer; - } - - /** - * Sets the selectable radius value around clickable points. - * - * @param buffer the selectable radius - */ - public void setSelectableBuffer(int buffer) { - selectableBuffer = buffer; - } - - /** - * Returns the legend height. - * - * @return the legend height - */ - public int getLegendHeight() { - return mLegendHeight; - } - - /** - * Sets the legend height, in pixels. - * - * @param height the legend height - */ - public void setLegendHeight(int height) { - mLegendHeight = height; - } - - /** - * Returns the margin sizes. An array containing the margins in this order: - * top, left, bottom, right - * - * @return the margin sizes - */ - public int[] getMargins() { - return mMargins; - } - - /** - * Sets the margins, in pixels. - * - * @param margins an array containing the margin size values, in this order: - * top, left, bottom, right - */ - public void setMargins(int[] margins) { - mMargins = margins; - } - - /** - * Returns if the chart is inside a scroll view and doesn't need to shrink. - * - * @return if it is inside a scroll view - */ - public boolean isInScroll() { - return mInScroll; - } - - /** - * To be set if the chart is inside a scroll view and doesn't need to shrink - * when not enough space. - * - * @param inScroll if it is inside a scroll view - */ - public void setInScroll(boolean inScroll) { - mInScroll = inScroll; - } - - /** - * Returns the start angle for circular charts such as pie, doughnut. An angle - * of 0 degrees correspond to the geometric angle of 0 degrees (3 o'clock on a - * watch.) - * - * @return the start angle in degrees - */ - public float getStartAngle() { - return mStartAngle; - } - - /** - * Sets the start angle for circular charts such as pie, doughnut, etc. An - * angle of 0 degrees correspond to the geometric angle of 0 degrees (3 - * o'clock on a watch.) - * - * @param startAngle the start angle in degrees - */ - public void setStartAngle(float startAngle) { - mStartAngle = startAngle; - } - - /** - * Returns if the values should be displayed as text. - * - * @return if the values should be displayed as text - */ - public boolean isDisplayValues() { - return mDisplayValues; - } - - /** - * Sets if the values should be displayed as text (supported by pie chart). - * - * @param display if the values should be displayed as text - */ - public void setDisplayValues(boolean display) { - mDisplayValues = display; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/DialRenderer.java b/android-libraries/achartengine/src/org/achartengine/renderer/DialRenderer.java deleted file mode 100644 index 1ed84619..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/DialRenderer.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.renderer; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.achartengine.util.MathHelper; - -/** - * Dial chart renderer. - */ -public class DialRenderer extends DefaultRenderer { - /** The start angle in the dial range. */ - private double mAngleMin = 330; - /** The end angle in the dial range. */ - private double mAngleMax = 30; - /** The start value in dial range. */ - private double mMinValue = MathHelper.NULL_VALUE; - /** The end value in dial range. */ - private double mMaxValue = -MathHelper.NULL_VALUE; - /** The spacing for the minor ticks. */ - private double mMinorTickSpacing = MathHelper.NULL_VALUE; - /** The spacing for the major ticks. */ - private double mMajorTickSpacing = MathHelper.NULL_VALUE; - /** An array of the renderers types (default is NEEDLE). */ - private List mVisualTypes = new ArrayList(); - - public enum Type { - NEEDLE, ARROW; - } - - /** - * Returns the start angle value of the dial. - * - * @return the angle start value - */ - public double getAngleMin() { - return mAngleMin; - } - - /** - * Sets the start angle value of the dial. - * - * @param min the dial angle start value - */ - public void setAngleMin(double min) { - mAngleMin = min; - } - - /** - * Returns the end angle value of the dial. - * - * @return the angle end value - */ - public double getAngleMax() { - return mAngleMax; - } - - /** - * Sets the end angle value of the dial. - * - * @param max the dial angle end value - */ - public void setAngleMax(double max) { - mAngleMax = max; - } - - /** - * Returns the start value to be rendered on the dial. - * - * @return the start value on dial - */ - public double getMinValue() { - return mMinValue; - } - - /** - * Sets the start value to be rendered on the dial. - * - * @param min the start value on the dial - */ - public void setMinValue(double min) { - mMinValue = min; - } - - /** - * Returns if the minimum dial value was set. - * - * @return the minimum dial value was set or not - */ - public boolean isMinValueSet() { - return mMinValue != MathHelper.NULL_VALUE; - } - - /** - * Returns the end value to be rendered on the dial. - * - * @return the end value on the dial - */ - public double getMaxValue() { - return mMaxValue; - } - - /** - * Sets the end value to be rendered on the dial. - * - * @param max the end value on the dial - */ - public void setMaxValue(double max) { - mMaxValue = max; - } - - /** - * Returns if the maximum dial value was set. - * - * @return the maximum dial was set or not - */ - public boolean isMaxValueSet() { - return mMaxValue != -MathHelper.NULL_VALUE; - } - - /** - * Returns the minor ticks spacing. - * - * @return the minor ticks spacing - */ - public double getMinorTicksSpacing() { - return mMinorTickSpacing; - } - - /** - * Sets the minor ticks spacing. - * - * @param spacing the minor ticks spacing - */ - public void setMinorTicksSpacing(double spacing) { - mMinorTickSpacing = spacing; - } - - /** - * Returns the major ticks spacing. - * - * @return the major ticks spacing - */ - public double getMajorTicksSpacing() { - return mMajorTickSpacing; - } - - /** - * Sets the major ticks spacing. - * - * @param spacing the major ticks spacing - */ - public void setMajorTicksSpacing(double spacing) { - mMajorTickSpacing = spacing; - } - - /** - * Returns the visual type at the specified index. - * - * @param index the index - * @return the visual type - */ - public Type getVisualTypeForIndex(int index) { - if (index < mVisualTypes.size()) { - return mVisualTypes.get(index); - } - return Type.NEEDLE; - } - - /** - * Sets the visual types. - * - * @param types the visual types - */ - public void setVisualTypes(Type[] types) { - mVisualTypes.clear(); - mVisualTypes.addAll(Arrays.asList(types)); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/SimpleSeriesRenderer.java b/android-libraries/achartengine/src/org/achartengine/renderer/SimpleSeriesRenderer.java deleted file mode 100644 index 0763fc58..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/SimpleSeriesRenderer.java +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.renderer; - -import java.io.Serializable; - -import android.graphics.Color; -import android.graphics.Paint.Align; - -/** - * A simple series renderer. - */ -public class SimpleSeriesRenderer implements Serializable { - /** The series color. */ - private int mColor = Color.BLUE; - /** If the values should be displayed above the chart points. */ - private boolean mDisplayChartValues; - /** The chart values text size. */ - private float mChartValuesTextSize = 10; - /** The chart values text alignment. */ - private Align mChartValuesTextAlign = Align.CENTER; - /** The chart values spacing from the data point. */ - private float mChartValuesSpacing = 5f; - /** The stroke style. */ - private BasicStroke mStroke; - /** If gradient is enabled. */ - private boolean mGradientEnabled = false; - /** The gradient start value. */ - private double mGradientStartValue; - /** The gradient start color. */ - private int mGradientStartColor; - /** The gradient stop value. */ - private double mGradientStopValue; - /** The gradient stop color. */ - private int mGradientStopColor; - - /** - * Returns the series color. - * - * @return the series color - */ - public int getColor() { - return mColor; - } - - /** - * Sets the series color. - * - * @param color the series color - */ - public void setColor(int color) { - mColor = color; - } - - /** - * Returns if the chart point values should be displayed as text. - * - * @return if the chart point values should be displayed as text - */ - public boolean isDisplayChartValues() { - return mDisplayChartValues; - } - - /** - * Sets if the chart point values should be displayed as text. - * - * @param display if the chart point values should be displayed as text - */ - public void setDisplayChartValues(boolean display) { - mDisplayChartValues = display; - } - - /** - * Returns the chart values text size. - * - * @return the chart values text size - */ - public float getChartValuesTextSize() { - return mChartValuesTextSize; - } - - /** - * Sets the chart values text size. - * - * @param textSize the chart values text size - */ - public void setChartValuesTextSize(float textSize) { - mChartValuesTextSize = textSize; - } - - /** - * Returns the chart values text align. - * - * @return the chart values text align - */ - public Align getChartValuesTextAlign() { - return mChartValuesTextAlign; - } - - /** - * Sets the chart values text align. - * - * @param align the chart values text align - */ - public void setChartValuesTextAlign(Align align) { - mChartValuesTextAlign = align; - } - - /** - * Returns the chart values spacing from the data point. - * - * @return the chart values spacing - */ - public float getChartValuesSpacing() { - return mChartValuesSpacing; - } - - /** - * Sets the chart values spacing from the data point. - * - * @param spacing the chart values spacing (in pixels) from the chart data - * point - */ - public void setChartValuesSpacing(float spacing) { - mChartValuesSpacing = spacing; - } - - /** - * Returns the stroke style. - * - * @return the stroke style - */ - public BasicStroke getStroke() { - return mStroke; - } - - /** - * Sets the stroke style. - * - * @param stroke the stroke style - */ - public void setStroke(BasicStroke stroke) { - mStroke = stroke; - } - - /** - * Returns the gradient is enabled value. - * - * @return the gradient enabled - */ - public boolean isGradientEnabled() { - return mGradientEnabled; - } - - /** - * Sets the gradient enabled value. - * - * @param enabled the gradient enabled - */ - public void setGradientEnabled(boolean enabled) { - mGradientEnabled = enabled; - } - - /** - * Returns the gradient start value. - * - * @return the gradient start value - */ - public double getGradientStartValue() { - return mGradientStartValue; - } - - /** - * Returns the gradient start color. - * - * @return the gradient start color - */ - public int getGradientStartColor() { - return mGradientStartColor; - } - - /** - * Sets the gradient start value and color. - * - * @param start the gradient start value - * @param color the gradient start color - */ - public void setGradientStart(double start, int color) { - mGradientStartValue = start; - mGradientStartColor = color; - } - - /** - * Returns the gradient stop value. - * - * @return the gradient stop value - */ - public double getGradientStopValue() { - return mGradientStopValue; - } - - /** - * Returns the gradient stop color. - * - * @return the gradient stop color - */ - public int getGradientStopColor() { - return mGradientStopColor; - } - - /** - * Sets the gradient stop value and color. - * - * @param start the gradient stop value - * @param color the gradient stop color - */ - public void setGradientStop(double start, int color) { - mGradientStopValue = start; - mGradientStopColor = color; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/XYMultipleSeriesRenderer.java b/android-libraries/achartengine/src/org/achartengine/renderer/XYMultipleSeriesRenderer.java deleted file mode 100644 index 64b34211..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/XYMultipleSeriesRenderer.java +++ /dev/null @@ -1,1101 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.renderer; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.achartengine.util.MathHelper; - -import android.graphics.Color; -import android.graphics.Paint.Align; - -/** - * Multiple XY series renderer. - */ -public class XYMultipleSeriesRenderer extends DefaultRenderer { - /** The X axis title. */ - private String mXTitle = ""; - /** The Y axis title. */ - private String[] mYTitle; - /** The axis title text size. */ - private float mAxisTitleTextSize = 12; - /** The start value in the X axis range. */ - private double[] mMinX; - /** The end value in the X axis range. */ - private double[] mMaxX; - /** The start value in the Y axis range. */ - private double[] mMinY; - /** The end value in the Y axis range. */ - private double[] mMaxY; - /** The approximative number of labels on the x axis. */ - private int mXLabels = 5; - /** The approximative number of labels on the y axis. */ - private int mYLabels = 5; - /** The current orientation of the chart. */ - private Orientation mOrientation = Orientation.HORIZONTAL; - /** The X axis text labels. */ - private Map mXTextLabels = new HashMap(); - /** The Y axis text labels. */ - private Map> mYTextLabels = new LinkedHashMap>(); - /** A flag for enabling or not the pan on the X axis. */ - private boolean mPanXEnabled = true; - /** A flag for enabling or not the pan on the Y axis. */ - private boolean mPanYEnabled = true; - /** A flag for enabling or not the zoom on the X axis. */ - private boolean mZoomXEnabled = true; - /** A flag for enabling or not the zoom on the Y axis . */ - private boolean mZoomYEnabled = true; - /** The spacing between bars, in bar charts. */ - private double mBarSpacing = 0; - /** The margins colors. */ - private int mMarginsColor = NO_COLOR; - /** The pan limits. */ - private double[] mPanLimits; - /** The zoom limits. */ - private double[] mZoomLimits; - /** The X axis labels rotation angle. */ - private float mXLabelsAngle; - /** The Y axis labels rotation angle. */ - private float mYLabelsAngle; - /** The initial axis range. */ - private Map initialRange = new LinkedHashMap(); - /** The point size for charts displaying points. */ - private float mPointSize = 3; - /** The grid color. */ - private int mGridColor = Color.argb(75, 200, 200, 200); - /** The number of scales. */ - private int scalesCount; - /** The X axis labels alignment. */ - private Align xLabelsAlign = Align.CENTER; - /** The Y axis labels alignment. */ - private Align[] yLabelsAlign; - /** The Y axis alignment. */ - private Align[] yAxisAlign; - /** The X axis labels color. */ - private int mXLabelsColor = TEXT_COLOR; - /** The Y axis labels color. */ - private int[] mYLabelsColor = new int[] { TEXT_COLOR }; - /** - * If X axis value selection algorithm to be used. Only used by the time - * charts. - */ - private boolean mXRoundedLabels = true; - - /** - * An enum for the XY chart orientation of the X axis. - */ - public enum Orientation { - HORIZONTAL(0), VERTICAL(90); - /** The rotate angle. */ - private int mAngle = 0; - - private Orientation(int angle) { - mAngle = angle; - } - - /** - * Return the orientation rotate angle. - * - * @return the orientaion rotate angle - */ - public int getAngle() { - return mAngle; - } - } - - public XYMultipleSeriesRenderer() { - this(1); - } - - public XYMultipleSeriesRenderer(int scaleNumber) { - scalesCount = scaleNumber; - initAxesRange(scaleNumber); - } - - public void initAxesRange(int scales) { - mYTitle = new String[scales]; - yLabelsAlign = new Align[scales]; - yAxisAlign = new Align[scales]; - mYLabelsColor = new int[scales]; - mMinX = new double[scales]; - mMaxX = new double[scales]; - mMinY = new double[scales]; - mMaxY = new double[scales]; - for (int i = 0; i < scales; i++) { - mYLabelsColor[i] = TEXT_COLOR; - initAxesRangeForScale(i); - } - } - - public void initAxesRangeForScale(int i) { - mMinX[i] = MathHelper.NULL_VALUE; - mMaxX[i] = -MathHelper.NULL_VALUE; - mMinY[i] = MathHelper.NULL_VALUE; - mMaxY[i] = -MathHelper.NULL_VALUE; - double[] range = new double[] { mMinX[i], mMaxX[i], mMinY[i], mMaxY[i] }; - initialRange.put(i, range); - mYTitle[i] = ""; - mYTextLabels.put(i, new HashMap()); - yLabelsAlign[i] = Align.CENTER; - yAxisAlign[i] = Align.LEFT; - } - - /** - * Returns the current orientation of the chart X axis. - * - * @return the chart orientation - */ - public Orientation getOrientation() { - return mOrientation; - } - - /** - * Sets the current orientation of the chart X axis. - * - * @param orientation the chart orientation - */ - public void setOrientation(Orientation orientation) { - mOrientation = orientation; - } - - /** - * Returns the title for the X axis. - * - * @return the X axis title - */ - public String getXTitle() { - return mXTitle; - } - - /** - * Sets the title for the X axis. - * - * @param title the X axis title - */ - public void setXTitle(String title) { - mXTitle = title; - } - - /** - * Returns the title for the Y axis. - * - * @return the Y axis title - */ - public String getYTitle() { - return getYTitle(0); - } - - /** - * Returns the title for the Y axis. - * - * @param scale the renderer scale - * @return the Y axis title - */ - public String getYTitle(int scale) { - return mYTitle[scale]; - } - - /** - * Sets the title for the Y axis. - * - * @param title the Y axis title - */ - public void setYTitle(String title) { - setYTitle(title, 0); - } - - /** - * Sets the title for the Y axis. - * - * @param title the Y axis title - * @param scale the renderer scale - */ - public void setYTitle(String title, int scale) { - mYTitle[scale] = title; - } - - /** - * Returns the axis title text size. - * - * @return the axis title text size - */ - public float getAxisTitleTextSize() { - return mAxisTitleTextSize; - } - - /** - * Sets the axis title text size. - * - * @param textSize the chart axis text size - */ - public void setAxisTitleTextSize(float textSize) { - mAxisTitleTextSize = textSize; - } - - /** - * Returns the start value of the X axis range. - * - * @return the X axis range start value - */ - public double getXAxisMin() { - return getXAxisMin(0); - } - - /** - * Sets the start value of the X axis range. - * - * @param min the X axis range start value - */ - public void setXAxisMin(double min) { - setXAxisMin(min, 0); - } - - /** - * Returns if the minimum X value was set. - * - * @return the minX was set or not - */ - public boolean isMinXSet() { - return isMinXSet(0); - } - - /** - * Returns the end value of the X axis range. - * - * @return the X axis range end value - */ - public double getXAxisMax() { - return getXAxisMax(0); - } - - /** - * Sets the end value of the X axis range. - * - * @param max the X axis range end value - */ - public void setXAxisMax(double max) { - setXAxisMax(max, 0); - } - - /** - * Returns if the maximum X value was set. - * - * @return the maxX was set or not - */ - public boolean isMaxXSet() { - return isMaxXSet(0); - } - - /** - * Returns the start value of the Y axis range. - * - * @return the Y axis range end value - */ - public double getYAxisMin() { - return getYAxisMin(0); - } - - /** - * Sets the start value of the Y axis range. - * - * @param min the Y axis range start value - */ - public void setYAxisMin(double min) { - setYAxisMin(min, 0); - } - - /** - * Returns if the minimum Y value was set. - * - * @return the minY was set or not - */ - public boolean isMinYSet() { - return isMinYSet(0); - } - - /** - * Returns the end value of the Y axis range. - * - * @return the Y axis range end value - */ - public double getYAxisMax() { - return getYAxisMax(0); - } - - /** - * Sets the end value of the Y axis range. - * - * @param max the Y axis range end value - */ - public void setYAxisMax(double max) { - setYAxisMax(max, 0); - } - - /** - * Returns if the maximum Y value was set. - * - * @return the maxY was set or not - */ - public boolean isMaxYSet() { - return isMaxYSet(0); - } - - /** - * Returns the start value of the X axis range. - * - * @param scale the renderer scale - * @return the X axis range start value - */ - public double getXAxisMin(int scale) { - return mMinX[scale]; - } - - /** - * Sets the start value of the X axis range. - * - * @param min the X axis range start value - * @param scale the renderer scale - */ - public void setXAxisMin(double min, int scale) { - if (!isMinXSet(scale)) { - initialRange.get(scale)[0] = min; - } - mMinX[scale] = min; - } - - /** - * Returns if the minimum X value was set. - * - * @param scale the renderer scale - * @return the minX was set or not - */ - public boolean isMinXSet(int scale) { - return mMinX[scale] != MathHelper.NULL_VALUE; - } - - /** - * Returns the end value of the X axis range. - * - * @param scale the renderer scale - * @return the X axis range end value - */ - public double getXAxisMax(int scale) { - return mMaxX[scale]; - } - - /** - * Sets the end value of the X axis range. - * - * @param max the X axis range end value - * @param scale the renderer scale - */ - public void setXAxisMax(double max, int scale) { - if (!isMaxXSet(scale)) { - initialRange.get(scale)[1] = max; - } - mMaxX[scale] = max; - } - - /** - * Returns if the maximum X value was set. - * - * @param scale the renderer scale - * @return the maxX was set or not - */ - public boolean isMaxXSet(int scale) { - return mMaxX[scale] != -MathHelper.NULL_VALUE; - } - - /** - * Returns the start value of the Y axis range. - * - * @param scale the renderer scale - * @return the Y axis range end value - */ - public double getYAxisMin(int scale) { - return mMinY[scale]; - } - - /** - * Sets the start value of the Y axis range. - * - * @param min the Y axis range start value - * @param scale the renderer scale - */ - public void setYAxisMin(double min, int scale) { - if (!isMinYSet(scale)) { - initialRange.get(scale)[2] = min; - } - mMinY[scale] = min; - } - - /** - * Returns if the minimum Y value was set. - * - * @param scale the renderer scale - * @return the minY was set or not - */ - public boolean isMinYSet(int scale) { - return mMinY[scale] != MathHelper.NULL_VALUE; - } - - /** - * Returns the end value of the Y axis range. - * - * @param scale the renderer scale - * @return the Y axis range end value - */ - public double getYAxisMax(int scale) { - return mMaxY[scale]; - } - - /** - * Sets the end value of the Y axis range. - * - * @param max the Y axis range end value - * @param scale the renderer scale - */ - public void setYAxisMax(double max, int scale) { - if (!isMaxYSet(scale)) { - initialRange.get(scale)[3] = max; - } - mMaxY[scale] = max; - } - - /** - * Returns if the maximum Y value was set. - * - * @param scale the renderer scale - * @return the maxY was set or not - */ - public boolean isMaxYSet(int scale) { - return mMaxY[scale] != -MathHelper.NULL_VALUE; - } - - /** - * Returns the approximate number of labels for the X axis. - * - * @return the approximate number of labels for the X axis - */ - public int getXLabels() { - return mXLabels; - } - - /** - * Sets the approximate number of labels for the X axis. - * - * @param xLabels the approximate number of labels for the X axis - */ - public void setXLabels(int xLabels) { - mXLabels = xLabels; - } - - /** - * Adds a new text label for the specified X axis value. - * - * @param x the X axis value - * @param text the text label - * @deprecated use addXTextLabel instead - */ - public void addTextLabel(double x, String text) { - addXTextLabel(x, text); - } - - /** - * Adds a new text label for the specified X axis value. - * - * @param x the X axis value - * @param text the text label - */ - public void addXTextLabel(double x, String text) { - mXTextLabels.put(x, text); - } - - /** - * Returns the X axis text label at the specified X axis value. - * - * @param x the X axis value - * @return the X axis text label - */ - public String getXTextLabel(Double x) { - return mXTextLabels.get(x); - } - - /** - * Returns the X text label locations. - * - * @return the X text label locations - */ - public Double[] getXTextLabelLocations() { - return mXTextLabels.keySet().toArray(new Double[0]); - } - - /** - * Clears the existing text labels. - * - * @deprecated use clearXTextLabels instead - */ - public void clearTextLabels() { - clearXTextLabels(); - } - - /** - * Clears the existing text labels on the X axis. - */ - public void clearXTextLabels() { - mXTextLabels.clear(); - } - - /** - * If X axis labels should be rounded. - * - * @return if rounded time values to be used - */ - public boolean isXRoundedLabels() { - return mXRoundedLabels; - } - - /** - * Sets if X axis rounded time values to be used. - * - * @param rounded rounded values to be used - */ - public void setXRoundedLabels(boolean rounded) { - mXRoundedLabels = rounded; - } - - /** - * Adds a new text label for the specified Y axis value. - * - * @param y the Y axis value - * @param text the text label - */ - public void addYTextLabel(double y, String text) { - addYTextLabel(y, text, 0); - } - - /** - * Adds a new text label for the specified Y axis value. - * - * @param y the Y axis value - * @param text the text label - * @param scale the renderer scale - */ - public void addYTextLabel(double y, String text, int scale) { - mYTextLabels.get(scale).put(y, text); - } - - /** - * Returns the Y axis text label at the specified Y axis value. - * - * @param y the Y axis value - * @return the Y axis text label - */ - public String getYTextLabel(Double y) { - return getYTextLabel(y, 0); - } - - /** - * Returns the Y axis text label at the specified Y axis value. - * - * @param y the Y axis value - * @param scale the renderer scale - * @return the Y axis text label - */ - public String getYTextLabel(Double y, int scale) { - return mYTextLabels.get(scale).get(y); - } - - /** - * Returns the Y text label locations. - * - * @return the Y text label locations - */ - public Double[] getYTextLabelLocations() { - return getYTextLabelLocations(0); - } - - /** - * Returns the Y text label locations. - * - * @param scale the renderer scale - * @return the Y text label locations - */ - public Double[] getYTextLabelLocations(int scale) { - return mYTextLabels.get(scale).keySet().toArray(new Double[0]); - } - - /** - * Clears the existing text labels on the Y axis. - */ - public void clearYTextLabels() { - clearYTextLabels(0); - } - - /** - * Clears the existing text labels on the Y axis. - * - * @param scale the renderer scale - */ - public void clearYTextLabels(int scale) { - mYTextLabels.get(scale).clear(); - } - - /** - * Returns the approximate number of labels for the Y axis. - * - * @return the approximate number of labels for the Y axis - */ - public int getYLabels() { - return mYLabels; - } - - /** - * Sets the approximate number of labels for the Y axis. - * - * @param yLabels the approximate number of labels for the Y axis - */ - public void setYLabels(int yLabels) { - mYLabels = yLabels; - } - - /** - * Sets if the chart point values should be displayed as text. - * - * @param display if the chart point values should be displayed as text - * @deprecated use SimpleSeriesRenderer.setDisplayChartValues() instead - */ - public void setDisplayChartValues(boolean display) { - SimpleSeriesRenderer[] renderers = getSeriesRenderers(); - for (SimpleSeriesRenderer renderer : renderers) { - renderer.setDisplayChartValues(display); - } - } - - /** - * Sets the chart values text size. - * - * @param textSize the chart values text size - * @deprecated use SimpleSeriesRenderer.setChartValuesTextSize() instead - */ - public void setChartValuesTextSize(float textSize) { - SimpleSeriesRenderer[] renderers = getSeriesRenderers(); - for (SimpleSeriesRenderer renderer : renderers) { - renderer.setChartValuesTextSize(textSize); - } - } - - /** - * Returns the enabled state of the pan on at least one axis. - * - * @return if pan is enabled - */ - public boolean isPanEnabled() { - return isPanXEnabled() || isPanYEnabled(); - } - - /** - * Returns the enabled state of the pan on X axis. - * - * @return if pan is enabled on X axis - */ - public boolean isPanXEnabled() { - return mPanXEnabled; - } - - /** - * Returns the enabled state of the pan on Y axis. - * - * @return if pan is enabled on Y axis - */ - public boolean isPanYEnabled() { - return mPanYEnabled; - } - - /** - * Sets the enabled state of the pan. - * - * @param enabledX pan enabled on X axis - * @param enabledY pan enabled on Y axis - */ - public void setPanEnabled(boolean enabledX, boolean enabledY) { - mPanXEnabled = enabledX; - mPanYEnabled = enabledY; - } - - /** - * Returns the enabled state of the zoom on at least one axis. - * - * @return if zoom is enabled - */ - public boolean isZoomEnabled() { - return isZoomXEnabled() || isZoomYEnabled(); - } - - /** - * Returns the enabled state of the zoom on X axis. - * - * @return if zoom is enabled on X axis - */ - public boolean isZoomXEnabled() { - return mZoomXEnabled; - } - - /** - * Returns the enabled state of the zoom on Y axis. - * - * @return if zoom is enabled on Y axis - */ - public boolean isZoomYEnabled() { - return mZoomYEnabled; - } - - /** - * Sets the enabled state of the zoom. - * - * @param enabledX zoom enabled on X axis - * @param enabledY zoom enabled on Y axis - */ - public void setZoomEnabled(boolean enabledX, boolean enabledY) { - mZoomXEnabled = enabledX; - mZoomYEnabled = enabledY; - } - - /** - * Returns the spacing between bars, in bar charts. - * - * @return the spacing between bars - * @deprecated use getBarSpacing instead - */ - public double getBarsSpacing() { - return getBarSpacing(); - } - - /** - * Returns the spacing between bars, in bar charts. - * - * @return the spacing between bars - */ - public double getBarSpacing() { - return mBarSpacing; - } - - /** - * Sets the spacing between bars, in bar charts. Only available for bar - * charts. This is a coefficient of the bar width. For instance, if you want - * the spacing to be a half of the bar width, set this value to 0.5. - * - * @param spacing the spacing between bars coefficient - */ - public void setBarSpacing(double spacing) { - mBarSpacing = spacing; - } - - /** - * Returns the margins color. - * - * @return the margins color - */ - public int getMarginsColor() { - return mMarginsColor; - } - - /** - * Sets the color of the margins. - * - * @param color the margins color - */ - public void setMarginsColor(int color) { - mMarginsColor = color; - } - - /** - * Returns the grid color. - * - * @return the grid color - */ - public int getGridColor() { - return mGridColor; - } - - /** - * Sets the color of the grid. - * - * @param color the grid color - */ - public void setGridColor(int color) { - mGridColor = color; - } - - /** - * Returns the pan limits. - * - * @return the pan limits - */ - public double[] getPanLimits() { - return mPanLimits; - } - - /** - * Sets the pan limits as an array of 4 values. Setting it to null or a - * different size array will disable the panning limitation. Values: - * [panMinimumX, panMaximumX, panMinimumY, panMaximumY] - * - * @param panLimits the pan limits - */ - public void setPanLimits(double[] panLimits) { - mPanLimits = panLimits; - } - - /** - * Returns the zoom limits. - * - * @return the zoom limits - */ - public double[] getZoomLimits() { - return mZoomLimits; - } - - /** - * Sets the zoom limits as an array of 4 values. Setting it to null or a - * different size array will disable the zooming limitation. Values: - * [zoomMinimumX, zoomMaximumX, zoomMinimumY, zoomMaximumY] - * - * @param zoomLimits the zoom limits - */ - public void setZoomLimits(double[] zoomLimits) { - mZoomLimits = zoomLimits; - } - - /** - * Returns the rotation angle of labels for the X axis. - * - * @return the rotation angle of labels for the X axis - */ - public float getXLabelsAngle() { - return mXLabelsAngle; - } - - /** - * Sets the rotation angle (in degrees) of labels for the X axis. - * - * @param angle the rotation angle of labels for the X axis - */ - public void setXLabelsAngle(float angle) { - mXLabelsAngle = angle; - } - - /** - * Returns the rotation angle of labels for the Y axis. - * - * @return the approximate number of labels for the Y axis - */ - public float getYLabelsAngle() { - return mYLabelsAngle; - } - - /** - * Sets the rotation angle (in degrees) of labels for the Y axis. - * - * @param angle the rotation angle of labels for the Y axis - */ - public void setYLabelsAngle(float angle) { - mYLabelsAngle = angle; - } - - /** - * Returns the size of the points, for charts displaying points. - * - * @return the point size - */ - public float getPointSize() { - return mPointSize; - } - - /** - * Sets the size of the points, for charts displaying points. - * - * @param size the point size - */ - public void setPointSize(float size) { - mPointSize = size; - } - - public void setRange(double[] range) { - setRange(range, 0); - } - - /** - * Sets the axes range values. - * - * @param range an array having the values in this order: minX, maxX, minY, - * maxY - * @param scale the renderer scale - */ - public void setRange(double[] range, int scale) { - setXAxisMin(range[0], scale); - setXAxisMax(range[1], scale); - setYAxisMin(range[2], scale); - setYAxisMax(range[3], scale); - } - - public boolean isInitialRangeSet() { - return isInitialRangeSet(0); - } - - /** - * Returns if the initial range is set. - * - * @param scale the renderer scale - * @return the initial range was set or not - */ - public boolean isInitialRangeSet(int scale) { - return initialRange.get(scale) != null; - } - - /** - * Returns the initial range. - * - * @return the initial range - */ - public double[] getInitialRange() { - return getInitialRange(0); - } - - /** - * Returns the initial range. - * - * @param scale the renderer scale - * @return the initial range - */ - public double[] getInitialRange(int scale) { - return initialRange.get(scale); - } - - /** - * Sets the axes initial range values. This will be used in the zoom fit tool. - * - * @param range an array having the values in this order: minX, maxX, minY, - * maxY - */ - public void setInitialRange(double[] range) { - setInitialRange(range, 0); - } - - /** - * Sets the axes initial range values. This will be used in the zoom fit tool. - * - * @param range an array having the values in this order: minX, maxX, minY, - * maxY - * @param scale the renderer scale - */ - public void setInitialRange(double[] range, int scale) { - initialRange.put(scale, range); - } - - /** - * Returns the X axis labels color. - * - * @return the X axis labels color - */ - public int getXLabelsColor() { - return mXLabelsColor; - } - - /** - * Returns the Y axis labels color. - * - * @return the Y axis labels color - */ - public int getYLabelsColor(int scale) { - return mYLabelsColor[scale]; - } - - /** - * Sets the X axis labels color. - * - * @param color the X axis labels color - */ - public void setXLabelsColor(int color) { - mXLabelsColor = color; - } - - /** - * Sets the Y axis labels color. - * - * @param scale the renderer scale - * @param color the Y axis labels color - */ - public void setYLabelsColor(int scale, int color) { - mYLabelsColor[scale] = color; - } - - /** - * Returns the X axis labels alignment. - * - * @return X labels alignment - */ - public Align getXLabelsAlign() { - return xLabelsAlign; - } - - /** - * Sets the X axis labels alignment. - * - * @param align the X labels alignment - */ - public void setXLabelsAlign(Align align) { - xLabelsAlign = align; - } - - /** - * Returns the Y axis labels alignment. - * - * @param scale the renderer scale - * @return Y labels alignment - */ - public Align getYLabelsAlign(int scale) { - return yLabelsAlign[scale]; - } - - public void setYLabelsAlign(Align align) { - setYLabelsAlign(align, 0); - } - - public Align getYAxisAlign(int scale) { - return yAxisAlign[scale]; - } - - public void setYAxisAlign(Align align, int scale) { - yAxisAlign[scale] = align; - } - - /** - * Sets the Y axis labels alignment. - * - * @param align the Y labels alignment - */ - public void setYLabelsAlign(Align align, int scale) { - yLabelsAlign[scale] = align; - } - - public int getScalesCount() { - return scalesCount; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/XYSeriesRenderer.java b/android-libraries/achartengine/src/org/achartengine/renderer/XYSeriesRenderer.java deleted file mode 100644 index 42e4808e..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/XYSeriesRenderer.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.renderer; - -import org.achartengine.chart.PointStyle; - -import android.graphics.Color; - -/** - * A renderer for the XY type series. - */ -public class XYSeriesRenderer extends SimpleSeriesRenderer { - /** If the chart points should be filled. */ - private boolean mFillPoints = false; - /** If the chart should be filled below its line. */ - private boolean mFillBelowLine = false; - /** The fill below the chart line color. */ - private int mFillColor = Color.argb(125, 0, 0, 200); - /** The point style. */ - private PointStyle mPointStyle = PointStyle.POINT; - /** The chart line width. */ - private float mLineWidth = 1; - - /** - * Returns if the chart should be filled below the line. - * - * @return the fill below line status - */ - public boolean isFillBelowLine() { - return mFillBelowLine; - } - - /** - * Sets if the line chart should be filled below its line. Filling below the - * line transforms a line chart into an area chart. - * - * @param fill the fill below line flag value - */ - public void setFillBelowLine(boolean fill) { - mFillBelowLine = fill; - } - - /** - * Returns if the chart points should be filled. - * - * @return the points fill status - */ - public boolean isFillPoints() { - return mFillPoints; - } - - /** - * Sets if the chart points should be filled. - * - * @param fill the points fill flag value - */ - public void setFillPoints(boolean fill) { - mFillPoints = fill; - } - - /** - * Returns the fill below line color. - * - * @return the fill below line color - */ - public int getFillBelowLineColor() { - return mFillColor; - } - - /** - * Sets the fill below the line color. - * - * @param color the fill below line color - */ - public void setFillBelowLineColor(int color) { - mFillColor = color; - } - - /** - * Returns the point style. - * - * @return the point style - */ - public PointStyle getPointStyle() { - return mPointStyle; - } - - /** - * Sets the point style. - * - * @param style the point style - */ - public void setPointStyle(PointStyle style) { - mPointStyle = style; - } - - /** - * Returns the chart line width. - * - * @return the line width - */ - public float getLineWidth() { - return mLineWidth; - } - - /** - * Sets the chart line width. - * - * @param lineWidth the line width - */ - public void setLineWidth(float lineWidth) { - mLineWidth = lineWidth; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/renderer/package.html b/android-libraries/achartengine/src/org/achartengine/renderer/package.html deleted file mode 100644 index c9db0a45..00000000 --- a/android-libraries/achartengine/src/org/achartengine/renderer/package.html +++ /dev/null @@ -1,6 +0,0 @@ - -AChartEngine - -Provides renderer classes that keep the chart rendering / drawing styles. - - \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/tools/AbstractTool.java b/android-libraries/achartengine/src/org/achartengine/tools/AbstractTool.java deleted file mode 100644 index 99841ed7..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/AbstractTool.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.XYChart; -import org.achartengine.renderer.XYMultipleSeriesRenderer; - -/** - * Abstract class for being extended by graphical view tools. - */ -public abstract class AbstractTool { - /** The chart. */ - protected AbstractChart mChart; - /** The renderer. */ - protected XYMultipleSeriesRenderer mRenderer; - - /** - * Abstract tool constructor. - * - * @param chart the chart - */ - public AbstractTool(AbstractChart chart) { - mChart = chart; - if (chart instanceof XYChart) { - mRenderer = ((XYChart) chart).getRenderer(); - } - } - - /** - * Returns the current chart range. - * - * @param scale the scale - * @return the chart range - */ - public double[] getRange(int scale) { - double minX = mRenderer.getXAxisMin(scale); - double maxX = mRenderer.getXAxisMax(scale); - double minY = mRenderer.getYAxisMin(scale); - double maxY = mRenderer.getYAxisMax(scale); - return new double[] { minX, maxX, minY, maxY }; - } - - /** - * Sets the range to the calculated one, if not already set. - * - * @param range the range - * @param scale the scale - */ - public void checkRange(double[] range, int scale) { - if (mChart instanceof XYChart) { - double[] calcRange = ((XYChart) mChart).getCalcRange(scale); - if (calcRange != null) { - if (!mRenderer.isMinXSet(scale)) { - range[0] = calcRange[0]; - mRenderer.setXAxisMin(range[0], scale); - } - if (!mRenderer.isMaxXSet(scale)) { - range[1] = calcRange[1]; - mRenderer.setXAxisMax(range[1], scale); - } - if (!mRenderer.isMinYSet(scale)) { - range[2] = calcRange[2]; - mRenderer.setYAxisMin(range[2], scale); - } - if (!mRenderer.isMaxYSet(scale)) { - range[3] = calcRange[3]; - mRenderer.setYAxisMax(range[3], scale); - } - } - } - } - - /** - * Sets a new range on the X axis. - * - * @param min the minimum value - * @param max the maximum value - * @param scale the scale - */ - protected void setXRange(double min, double max, int scale) { - mRenderer.setXAxisMin(min, scale); - mRenderer.setXAxisMax(max, scale); - } - - /** - * Sets a new range on the Y axis. - * - * @param min the minimum value - * @param max the maximum value - * @param scale the scale - */ - protected void setYRange(double min, double max, int scale) { - mRenderer.setYAxisMin(min, scale); - mRenderer.setYAxisMax(max, scale); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/tools/FitZoom.java b/android-libraries/achartengine/src/org/achartengine/tools/FitZoom.java deleted file mode 100644 index 92f67b84..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/FitZoom.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.RoundChart; -import org.achartengine.chart.XYChart; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.DefaultRenderer; -import org.achartengine.util.MathHelper; - -public class FitZoom extends AbstractTool { - /** - * Builds an instance of the fit zoom tool. - * - * @param chart the XY chart - */ - public FitZoom(AbstractChart chart) { - super(chart); - } - - /** - * Apply the tool. - */ - public void apply() { - if (mChart instanceof XYChart) { - if (((XYChart) mChart).getDataset() == null) { - return; - } - int scales = mRenderer.getScalesCount(); - if (mRenderer.isInitialRangeSet()) { - for (int i = 0; i < scales; i++) { - if (mRenderer.isInitialRangeSet(i)) { - mRenderer.setRange(mRenderer.getInitialRange(i), i); - } - } - } else { - XYSeries[] series = ((XYChart) mChart).getDataset().getSeries(); - double[] range = null; - int length = series.length; - if (length > 0) { - for (int i = 0; i < scales; i++) { - range = new double[] { MathHelper.NULL_VALUE, -MathHelper.NULL_VALUE, - MathHelper.NULL_VALUE, -MathHelper.NULL_VALUE }; - for (int j = 0; j < length; j++) { - if (i == series[j].getScaleNumber()) { - range[0] = Math.min(range[0], series[j].getMinX()); - range[1] = Math.max(range[1], series[j].getMaxX()); - range[2] = Math.min(range[2], series[j].getMinY()); - range[3] = Math.max(range[3], series[j].getMaxY()); - } - } - double marginX = Math.abs(range[1] - range[0]) / 40; - double marginY = Math.abs(range[3] - range[2]) / 40; - mRenderer.setRange(new double[] { range[0] - marginX, range[1] + marginX, - range[2] - marginY, range[3] + marginY }, i); - } - } - } - } else { - DefaultRenderer renderer = ((RoundChart) mChart).getRenderer(); - renderer.setScale(renderer.getOriginalScale()); - } - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/tools/Pan.java b/android-libraries/achartengine/src/org/achartengine/tools/Pan.java deleted file mode 100644 index 2d4ea28e..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/Pan.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.RoundChart; -import org.achartengine.chart.XYChart; - -/** - * The pan tool. - */ -public class Pan extends AbstractTool { - /** The pan listeners. */ - private List mPanListeners = new ArrayList(); - /** Pan limits reached on the X axis. */ - private boolean limitsReachedX = false; - /** Pan limits reached on the X axis. */ - private boolean limitsReachedY = false; - - /** - * Builds and instance of the pan tool. - * - * @param chart the XY chart - */ - public Pan(AbstractChart chart) { - super(chart); - } - - /** - * Apply the tool. - * - * @param oldX the previous location on X axis - * @param oldY the previous location on Y axis - * @param newX the current location on X axis - * @param newY the current location on the Y axis - */ - public void apply(float oldX, float oldY, float newX, float newY) { - boolean notLimitedUp = true; - boolean notLimitedBottom = true; - boolean notLimitedLeft = true; - boolean notLimitedRight = true; - if (mChart instanceof XYChart) { - int scales = mRenderer.getScalesCount(); - double[] limits = mRenderer.getPanLimits(); - boolean limited = limits != null && limits.length == 4; - XYChart chart = (XYChart) mChart; - for (int i = 0; i < scales; i++) { - double[] range = getRange(i); - double[] calcRange = chart.getCalcRange(i); - if (limitsReachedX - && limitsReachedY - && (range[0] == range[1] && calcRange[0] == calcRange[1] || range[2] == range[3] - && calcRange[2] == calcRange[3])) { - return; - } - checkRange(range, i); - - double[] realPoint = chart.toRealPoint(oldX, oldY, i); - double[] realPoint2 = chart.toRealPoint(newX, newY, i); - double deltaX = realPoint[0] - realPoint2[0]; - double deltaY = realPoint[1] - realPoint2[1]; - double ratio = getAxisRatio(range); - if (chart.isVertical(mRenderer)) { - double newDeltaX = -deltaY * ratio; - double newDeltaY = deltaX / ratio; - deltaX = newDeltaX; - deltaY = newDeltaY; - } - if (mRenderer.isPanXEnabled()) { - if (limits != null) { - if (notLimitedLeft) { - notLimitedLeft = limits[0] <= range[0] + deltaX; - } - if (notLimitedRight) { - notLimitedRight = limits[1] >= range[1] + deltaX; - } - } - if (!limited || (notLimitedLeft && notLimitedRight)) { - setXRange(range[0] + deltaX, range[1] + deltaX, i); - limitsReachedX = false; - } else { - limitsReachedX = true; - } - } - if (mRenderer.isPanYEnabled()) { - if (limits != null) { - if (notLimitedBottom) { - notLimitedBottom = limits[2] <= range[2] + deltaY; - } - if (notLimitedUp) { - notLimitedUp = limits[3] >= range[3] + deltaY; - } - } - if (!limited || (notLimitedBottom && notLimitedUp)) { - setYRange(range[2] + deltaY, range[3] + deltaY, i); - limitsReachedY = false; - } else { - limitsReachedY = true; - } - } - } - } else { - RoundChart chart = (RoundChart) mChart; - chart.setCenterX(chart.getCenterX() + (int) (newX - oldX)); - chart.setCenterY(chart.getCenterY() + (int) (newY - oldY)); - } - notifyPanListeners(); - } - - /** - * Return the X / Y axis range ratio. - * - * @param range the axis range - * @return the ratio - */ - private double getAxisRatio(double[] range) { - return Math.abs(range[1] - range[0]) / Math.abs(range[3] - range[2]); - } - - /** - * Notify the pan listeners about a pan. - */ - private synchronized void notifyPanListeners() { - for (PanListener listener : mPanListeners) { - listener.panApplied(); - } - } - - /** - * Adds a new pan listener. - * - * @param listener pan listener - */ - public synchronized void addPanListener(PanListener listener) { - mPanListeners.add(listener); - } - - /** - * Removes a pan listener. - * - * @param listener pan listener - */ - public synchronized void removePanListener(PanListener listener) { - mPanListeners.add(listener); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/tools/PanListener.java b/android-libraries/achartengine/src/org/achartengine/tools/PanListener.java deleted file mode 100644 index d3d136c0..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/PanListener.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - -/** - * A pan listener. - */ -public interface PanListener { - - /** - * Called when a pan change is triggered. - */ - void panApplied(); - -} diff --git a/android-libraries/achartengine/src/org/achartengine/tools/Zoom.java b/android-libraries/achartengine/src/org/achartengine/tools/Zoom.java deleted file mode 100644 index 0abee92c..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/Zoom.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - -import java.util.ArrayList; -import java.util.List; - -import org.achartengine.chart.AbstractChart; -import org.achartengine.chart.RoundChart; -import org.achartengine.chart.XYChart; -import org.achartengine.renderer.DefaultRenderer; - -/** - * The zoom tool. - */ -public class Zoom extends AbstractTool { - /** A flag to be used to know if this is a zoom in or out. */ - private boolean mZoomIn; - /** The zoom rate. */ - private float mZoomRate; - /** The zoom listeners. */ - private List mZoomListeners = new ArrayList(); - /** Zoom limits reached on the X axis. */ - private boolean limitsReachedX = false; - /** Zoom limits reached on the Y axis. */ - private boolean limitsReachedY = false; - - /** Zoom on X axis and Y axis */ - public static final int ZOOM_AXIS_XY = 0; - /** Zoom on X axis independently */ - public static final int ZOOM_AXIS_X = 1; - /** Zoom on Y axis independently */ - public static final int ZOOM_AXIS_Y = 2; - - - /** - * Builds the zoom tool. - * - * @param chart the chart - * @param in zoom in or out - * @param rate the zoom rate - */ - public Zoom(AbstractChart chart, boolean in, float rate) { - super(chart); - mZoomIn = in; - setZoomRate(rate); - } - - /** - * Sets the zoom rate. - * - * @param rate - */ - public void setZoomRate(float rate) { - mZoomRate = rate; - } - - /** - * Apply the zoom. - */ - public void apply(int zoom_axis) { - if (mChart instanceof XYChart) { - int scales = mRenderer.getScalesCount(); - for (int i = 0; i < scales; i++) { - double[] range = getRange(i); - checkRange(range, i); - double[] limits = mRenderer.getZoomLimits(); - - double centerX = (range[0] + range[1]) / 2; - double centerY = (range[2] + range[3]) / 2; - double newWidth = range[1] - range[0]; - double newHeight = range[3] - range[2]; - double newXMin = centerX - newWidth / 2; - double newXMax = centerX + newWidth / 2; - double newYMin = centerY - newHeight / 2; - double newYMax = centerY + newHeight / 2; - - // if already reached last zoom, then it will always set to reached - if (i == 0) { - limitsReachedX = limits != null && (newXMin <= limits[0] || newXMax >= limits[1]); - limitsReachedY = limits != null && (newYMin <= limits[2] || newYMax >= limits[3]); - } - - if (mZoomIn) { - if (mRenderer.isZoomXEnabled() && // zoom in on X axis - (zoom_axis == ZOOM_AXIS_X || zoom_axis == ZOOM_AXIS_XY)) { - if (limitsReachedX && mZoomRate < 1) { - // ignore pinch zoom out once reached X limit - } else { - newWidth /= mZoomRate; - } - } - - if (mRenderer.isZoomYEnabled() && // zoom in on Y axis - (zoom_axis == ZOOM_AXIS_Y || zoom_axis == ZOOM_AXIS_XY)) { - if (limitsReachedY && mZoomRate < 1) { - } else { - newHeight /= mZoomRate; - } - } - } else { - if (mRenderer.isZoomXEnabled() && !limitsReachedX && // zoom out on X axis - (zoom_axis == ZOOM_AXIS_X || zoom_axis == ZOOM_AXIS_XY)) { - newWidth *= mZoomRate; - } - - if (mRenderer.isZoomYEnabled() && !limitsReachedY && // zoom out on Y axis - (zoom_axis == ZOOM_AXIS_Y || zoom_axis == ZOOM_AXIS_XY)) { - newHeight *= mZoomRate; - } - } - - if (mRenderer.isZoomXEnabled() && - (zoom_axis == ZOOM_AXIS_X || zoom_axis == ZOOM_AXIS_XY)) { - newXMin = centerX - newWidth / 2; - newXMax = centerX + newWidth / 2; - setXRange(newXMin, newXMax, i); - } - if (mRenderer.isZoomYEnabled() && - (zoom_axis == ZOOM_AXIS_Y || zoom_axis == ZOOM_AXIS_XY)) { - newYMin = centerY - newHeight / 2; - newYMax = centerY + newHeight / 2; - setYRange(newYMin, newYMax, i); - } - } - } else { - DefaultRenderer renderer = ((RoundChart) mChart).getRenderer(); - if (mZoomIn) { - renderer.setScale(renderer.getScale() * mZoomRate); - } else { - renderer.setScale(renderer.getScale() / mZoomRate); - } - } - notifyZoomListeners(new ZoomEvent(mZoomIn, mZoomRate)); - } - - - /** - * Notify the zoom listeners about a zoom change. - * - * @param e the zoom event - */ - private synchronized void notifyZoomListeners(ZoomEvent e) { - for (ZoomListener listener : mZoomListeners) { - listener.zoomApplied(e); - } - } - - /** - * Notify the zoom listeners about a zoom reset. - */ - public synchronized void notifyZoomResetListeners() { - for (ZoomListener listener : mZoomListeners) { - listener.zoomReset(); - } - } - - /** - * Adds a new zoom listener. - * - * @param listener zoom listener - */ - public synchronized void addZoomListener(ZoomListener listener) { - mZoomListeners.add(listener); - } - - /** - * Removes a zoom listener. - * - * @param listener zoom listener - */ - public synchronized void removeZoomListener(ZoomListener listener) { - mZoomListeners.add(listener); - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/tools/ZoomEvent.java b/android-libraries/achartengine/src/org/achartengine/tools/ZoomEvent.java deleted file mode 100644 index bd8fb686..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/ZoomEvent.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - - -/** - * A zoom event. - */ -public class ZoomEvent { - /** A flag to be used to know if this is a zoom in or out. */ - private boolean mZoomIn; - /** The zoom rate. */ - private float mZoomRate; - - /** - * Builds the zoom tool. - * - * @param in zoom in or out - * @param rate the zoom rate - */ - public ZoomEvent(boolean in, float rate) { - mZoomIn = in; - mZoomRate = rate; - } - - /** - * Returns the zoom type. - * - * @return true if zoom in, false otherwise - */ - public boolean isZoomIn() { - return mZoomIn; - } - - /** - * Returns the zoom rate. - * - * @return the zoom rate - */ - public float getZoomRate() { - return mZoomRate; - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/tools/ZoomListener.java b/android-libraries/achartengine/src/org/achartengine/tools/ZoomListener.java deleted file mode 100644 index 4827483e..00000000 --- a/android-libraries/achartengine/src/org/achartengine/tools/ZoomListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.tools; - -/** - * A zoom listener. - */ -public interface ZoomListener { - - /** - * Called when a zoom change is triggered. - * @param e the zoom event - */ - void zoomApplied(ZoomEvent e); - - /** - * Called when a zoom reset is done. - */ - void zoomReset(); -} diff --git a/android-libraries/achartengine/src/org/achartengine/util/IndexXYMap.java b/android-libraries/achartengine/src/org/achartengine/util/IndexXYMap.java deleted file mode 100644 index f9572622..00000000 --- a/android-libraries/achartengine/src/org/achartengine/util/IndexXYMap.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.TreeMap; - -/** - * This class requires sorted x values - */ -public class IndexXYMap extends TreeMap { - private final List indexList = new ArrayList(); - - private double maxXDifference = 0; - - public IndexXYMap() { - super(); - } - - public V put(K key, V value) { - indexList.add(key); - updateMaxXDifference(); - return super.put(key, value); - } - - private void updateMaxXDifference() { - if (indexList.size() < 2) { - maxXDifference = 0; - return; - } - - if (Math.abs((Double) indexList.get(indexList.size() - 1) - - (Double) indexList.get(indexList.size() - 2)) > maxXDifference) - maxXDifference = Math.abs((Double) indexList.get(indexList.size() - 1) - - (Double) indexList.get(indexList.size() - 2)); - } - - public double getMaxXDifference() { - return maxXDifference; - } - - public void clear() { - updateMaxXDifference(); - super.clear(); - indexList.clear(); - } - - /** - * Returns X-value according to the given index - * - * @param index - * @return the X value - */ - public K getXByIndex(int index) { - return indexList.get(index); - } - - /** - * Returns Y-value according to the given index - * - * @param index - * @return the Y value - */ - public V getYByIndex(int index) { - K key = indexList.get(index); - return this.get(key); - } - - /** - * Returns XY-entry according to the given index - * - * @param index - * @return the X and Y values - */ - public XYEntry getByIndex(int index) { - K key = indexList.get(index); - return new XYEntry(key, this.get(key)); - } - - /** - * Removes entry from map by index - * - * @param index - */ - public XYEntry removeByIndex(int index) { - K key = indexList.remove(index); - return new XYEntry(key, this.remove(key)); - } - - public int getIndexForKey(K key) { - return Collections.binarySearch(indexList, key, null); - } -} diff --git a/android-libraries/achartengine/src/org/achartengine/util/MathHelper.java b/android-libraries/achartengine/src/org/achartengine/util/MathHelper.java deleted file mode 100644 index f5b893bf..00000000 --- a/android-libraries/achartengine/src/org/achartengine/util/MathHelper.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.util; - -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; - -/** - * Utility class for math operations. - */ -public class MathHelper { - /** A value that is used a null value. */ - public static final double NULL_VALUE = Double.MAX_VALUE; - /** - * A number formatter to be used to make sure we have a maximum number of - * fraction digits in the labels. - */ - private static final NumberFormat FORMAT = NumberFormat.getNumberInstance(); - - private MathHelper() { - // empty constructor - } - - /** - * Calculate the minimum and maximum values out of a list of doubles. - * - * @param values the input values - * @return an array with the minimum and maximum values - */ - public static double[] minmax(List values) { - if (values.size() == 0) { - return new double[2]; - } - double min = values.get(0); - double max = min; - int length = values.size(); - for (int i = 1; i < length; i++) { - double value = values.get(i); - min = Math.min(min, value); - max = Math.max(max, value); - } - return new double[] { min, max }; - } - - /** - * Computes a reasonable set of labels for a data interval and number of - * labels. - * - * @param start start value - * @param end final value - * @param approxNumLabels desired number of labels - * @return collection containing {start value, end value, increment} - */ - public static List getLabels(final double start, final double end, - final int approxNumLabels) { - FORMAT.setMaximumFractionDigits(5); - List labels = new ArrayList(); - double[] labelParams = computeLabels(start, end, approxNumLabels); - // when the start > end the inc will be negative so it will still work - int numLabels = 1 + (int) ((labelParams[1] - labelParams[0]) / labelParams[2]); - // we want the range to be inclusive but we don't want to blow up when - // looping for the case where the min and max are the same. So we loop - // on - // numLabels not on the values. - for (int i = 0; i < numLabels; i++) { - double z = labelParams[0] + i * labelParams[2]; - try { - // this way, we avoid a label value like 0.4000000000000000001 instead - // of 0.4 - z = FORMAT.parse(FORMAT.format(z)).doubleValue(); - } catch (ParseException e) { - // do nothing here - } - labels.add(z); - } - return labels; - } - - /** - * Computes a reasonable number of labels for a data range. - * - * @param start start value - * @param end final value - * @param approxNumLabels desired number of labels - * @return double[] array containing {start value, end value, increment} - */ - private static double[] computeLabels(final double start, final double end, - final int approxNumLabels) { - if (Math.abs(start - end) < 0.0000001f) { - return new double[] { start, start, 0 }; - } - double s = start; - double e = end; - boolean switched = false; - if (s > e) { - switched = true; - double tmp = s; - s = e; - e = tmp; - } - double xStep = roundUp(Math.abs(s - e) / approxNumLabels); - // Compute x starting point so it is a multiple of xStep. - double xStart = xStep * Math.ceil(s / xStep); - double xEnd = xStep * Math.floor(e / xStep); - if (switched) { - return new double[] { xEnd, xStart, -1.0 * xStep }; - } - return new double[] { xStart, xEnd, xStep }; - } - - /** - * Given a number, round up to the nearest power of ten times 1, 2, or 5. The - * argument must be strictly positive. - */ - private static double roundUp(final double val) { - int exponent = (int) Math.floor(Math.log10(val)); - double rval = val * Math.pow(10, -exponent); - if (rval > 5.0) { - rval = 10.0; - } else if (rval > 2.0) { - rval = 5.0; - } else if (rval > 1.0) { - rval = 2.0; - } - rval *= Math.pow(10, exponent); - return rval; - } - - /** - * Transforms a list of Float values into an array of float. - * - * @param values the list of Float - * @return the array of floats - */ - public static float[] getFloats(List values) { - int length = values.size(); - float[] result = new float[length]; - for (int i = 0; i < length; i++) { - result[i] = values.get(i).floatValue(); - } - return result; - } - - /** - * Transforms a list of Double values into an array of double. - * - * @param values the list of Double - * @return the array of doubles - */ - public static double[] getDoubles(List values) { - int length = values.size(); - double[] result = new double[length]; - for (int i = 0; i < length; i++) { - result[i] = values.get(i).doubleValue(); - } - return result; - } - -} diff --git a/android-libraries/achartengine/src/org/achartengine/util/XYEntry.java b/android-libraries/achartengine/src/org/achartengine/util/XYEntry.java deleted file mode 100644 index 53761a4d..00000000 --- a/android-libraries/achartengine/src/org/achartengine/util/XYEntry.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (C) 2009 - 2012 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 org.achartengine.util; - -import java.util.Map.Entry; - -/** - * A map entry value encapsulating an XY point. - */ -public class XYEntry implements Entry { - private final K key; - - private V value; - - public XYEntry(K key, V value) { - this.key = key; - this.value = value; - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - public V setValue(V object) { - this.value = object; - return this.value; - } -} \ No newline at end of file diff --git a/android-libraries/achartengine/src/org/achartengine/util/package.html b/android-libraries/achartengine/src/org/achartengine/util/package.html deleted file mode 100644 index da92e913..00000000 --- a/android-libraries/achartengine/src/org/achartengine/util/package.html +++ /dev/null @@ -1,6 +0,0 @@ - -AChartEngine - -Utility classes that provide helper methods used by most of the other packages. - - \ No newline at end of file diff --git a/android/.classpath b/android/.classpath deleted file mode 100644 index 07677d89..00000000 --- a/android/.classpath +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/android/.project b/android/.project deleted file mode 100644 index 94894b51..00000000 --- a/android/.project +++ /dev/null @@ -1,45 +0,0 @@ - - - OpenRocket-android - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - - - - core - 2 - WORKSPACE_LOC/OpenRocket/src - - - core-resources - 2 - WORKSPACE_LOC/OpenRocket/resources - - - diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml deleted file mode 100644 index 473dfeb2..00000000 --- a/android/AndroidManifest.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/android/lint.xml b/android/lint.xml deleted file mode 100644 index ee0eead5..00000000 --- a/android/lint.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/android/proguard.cfg b/android/proguard.cfg deleted file mode 100644 index b1cdf17b..00000000 --- a/android/proguard.cfg +++ /dev/null @@ -1,40 +0,0 @@ --optimizationpasses 5 --dontusemixedcaseclassnames --dontskipnonpubliclibraryclasses --dontpreverify --verbose --optimizations !code/simplification/arithmetic,!field/*,!class/merging/* - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference --keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native ; -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet); -} - --keepclasseswithmembers class * { - public (android.content.Context, android.util.AttributeSet, int); -} - --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} diff --git a/android/project.properties b/android/project.properties deleted file mode 100644 index 8202ea55..00000000 --- a/android/project.properties +++ /dev/null @@ -1,14 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-15 -android.library.reference.1=../ActionBarSherlock -android.library.reference.2=../TreeViewList -android.library.reference.3=../achartengine diff --git a/android/res/drawable-hdpi/arrow_down_float.png b/android/res/drawable-hdpi/arrow_down_float.png deleted file mode 100644 index 2466c8f6..00000000 Binary files a/android/res/drawable-hdpi/arrow_down_float.png and /dev/null differ diff --git a/android/res/drawable-hdpi/arrow_up_float.png b/android/res/drawable-hdpi/arrow_up_float.png deleted file mode 100644 index d1301c3b..00000000 Binary files a/android/res/drawable-hdpi/arrow_up_float.png and /dev/null differ diff --git a/android/res/drawable-hdpi/ic_menu_add.png b/android/res/drawable-hdpi/ic_menu_add.png deleted file mode 100644 index 444e8a5e..00000000 Binary files a/android/res/drawable-hdpi/ic_menu_add.png and /dev/null differ diff --git a/android/res/drawable-hdpi/ic_menu_archive.png b/android/res/drawable-hdpi/ic_menu_archive.png deleted file mode 100644 index e2d9bc1a..00000000 Binary files a/android/res/drawable-hdpi/ic_menu_archive.png and /dev/null differ diff --git a/android/res/drawable-hdpi/ic_menu_info_details.png b/android/res/drawable-hdpi/ic_menu_info_details.png deleted file mode 100644 index 6a7a1e94..00000000 Binary files a/android/res/drawable-hdpi/ic_menu_info_details.png and /dev/null differ diff --git a/android/res/drawable-hdpi/ic_menu_preferences.png b/android/res/drawable-hdpi/ic_menu_preferences.png deleted file mode 100644 index 5321f828..00000000 Binary files a/android/res/drawable-hdpi/ic_menu_preferences.png and /dev/null differ diff --git a/android/res/drawable-hdpi/ic_menu_save.png b/android/res/drawable-hdpi/ic_menu_save.png deleted file mode 100644 index 36fc7f4d..00000000 Binary files a/android/res/drawable-hdpi/ic_menu_save.png and /dev/null differ diff --git a/android/res/drawable-hdpi/ic_menu_search.png b/android/res/drawable-hdpi/ic_menu_search.png deleted file mode 100644 index a7f9bbee..00000000 Binary files a/android/res/drawable-hdpi/ic_menu_search.png and /dev/null differ diff --git a/android/res/drawable-hdpi/or_launcher.png b/android/res/drawable-hdpi/or_launcher.png deleted file mode 100644 index 22c526f3..00000000 Binary files a/android/res/drawable-hdpi/or_launcher.png and /dev/null differ diff --git a/android/res/drawable-ldpi/arrow_down_float.png b/android/res/drawable-ldpi/arrow_down_float.png deleted file mode 100644 index c41340da..00000000 Binary files a/android/res/drawable-ldpi/arrow_down_float.png and /dev/null differ diff --git a/android/res/drawable-ldpi/arrow_up_float.png b/android/res/drawable-ldpi/arrow_up_float.png deleted file mode 100644 index 8b60f121..00000000 Binary files a/android/res/drawable-ldpi/arrow_up_float.png and /dev/null differ diff --git a/android/res/drawable-ldpi/ic_menu_add.png b/android/res/drawable-ldpi/ic_menu_add.png deleted file mode 100644 index 89620af8..00000000 Binary files a/android/res/drawable-ldpi/ic_menu_add.png and /dev/null differ diff --git a/android/res/drawable-ldpi/ic_menu_archive.png b/android/res/drawable-ldpi/ic_menu_archive.png deleted file mode 100644 index 719ecd85..00000000 Binary files a/android/res/drawable-ldpi/ic_menu_archive.png and /dev/null differ diff --git a/android/res/drawable-ldpi/ic_menu_info_details.png b/android/res/drawable-ldpi/ic_menu_info_details.png deleted file mode 100644 index 55c57d5c..00000000 Binary files a/android/res/drawable-ldpi/ic_menu_info_details.png and /dev/null differ diff --git a/android/res/drawable-ldpi/ic_menu_preferences.png b/android/res/drawable-ldpi/ic_menu_preferences.png deleted file mode 100644 index efc2f3e4..00000000 Binary files a/android/res/drawable-ldpi/ic_menu_preferences.png and /dev/null differ diff --git a/android/res/drawable-ldpi/ic_menu_save.png b/android/res/drawable-ldpi/ic_menu_save.png deleted file mode 100644 index ac053b41..00000000 Binary files a/android/res/drawable-ldpi/ic_menu_save.png and /dev/null differ diff --git a/android/res/drawable-ldpi/ic_menu_search.png b/android/res/drawable-ldpi/ic_menu_search.png deleted file mode 100644 index 1d95408c..00000000 Binary files a/android/res/drawable-ldpi/ic_menu_search.png and /dev/null differ diff --git a/android/res/drawable-ldpi/or_launcher.png b/android/res/drawable-ldpi/or_launcher.png deleted file mode 100644 index 5f7a0b2a..00000000 Binary files a/android/res/drawable-ldpi/or_launcher.png and /dev/null differ diff --git a/android/res/drawable-mdpi/arrow_down_float.png b/android/res/drawable-mdpi/arrow_down_float.png deleted file mode 100644 index dd825234..00000000 Binary files a/android/res/drawable-mdpi/arrow_down_float.png and /dev/null differ diff --git a/android/res/drawable-mdpi/arrow_up_float.png b/android/res/drawable-mdpi/arrow_up_float.png deleted file mode 100644 index 9bc3d1c2..00000000 Binary files a/android/res/drawable-mdpi/arrow_up_float.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_directory.png b/android/res/drawable-mdpi/ic_directory.png deleted file mode 100644 index a4599e37..00000000 Binary files a/android/res/drawable-mdpi/ic_directory.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_menu_add.png b/android/res/drawable-mdpi/ic_menu_add.png deleted file mode 100644 index 361c7c46..00000000 Binary files a/android/res/drawable-mdpi/ic_menu_add.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_menu_archive.png b/android/res/drawable-mdpi/ic_menu_archive.png deleted file mode 100644 index 49ac569d..00000000 Binary files a/android/res/drawable-mdpi/ic_menu_archive.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_menu_info_details.png b/android/res/drawable-mdpi/ic_menu_info_details.png deleted file mode 100644 index 18b15b5a..00000000 Binary files a/android/res/drawable-mdpi/ic_menu_info_details.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_menu_preferences.png b/android/res/drawable-mdpi/ic_menu_preferences.png deleted file mode 100644 index ccc50e66..00000000 Binary files a/android/res/drawable-mdpi/ic_menu_preferences.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_menu_save.png b/android/res/drawable-mdpi/ic_menu_save.png deleted file mode 100644 index 5f668644..00000000 Binary files a/android/res/drawable-mdpi/ic_menu_save.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_menu_search.png b/android/res/drawable-mdpi/ic_menu_search.png deleted file mode 100644 index 5d3155e0..00000000 Binary files a/android/res/drawable-mdpi/ic_menu_search.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_motorbrowser.png b/android/res/drawable-mdpi/ic_motorbrowser.png deleted file mode 100644 index c7dcd536..00000000 Binary files a/android/res/drawable-mdpi/ic_motorbrowser.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_star_select.png b/android/res/drawable-mdpi/ic_star_select.png deleted file mode 100644 index 4c479314..00000000 Binary files a/android/res/drawable-mdpi/ic_star_select.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_star_unselected.png b/android/res/drawable-mdpi/ic_star_unselected.png deleted file mode 100644 index 98203a73..00000000 Binary files a/android/res/drawable-mdpi/ic_star_unselected.png and /dev/null differ diff --git a/android/res/drawable-mdpi/or_launcher.png b/android/res/drawable-mdpi/or_launcher.png deleted file mode 100644 index 36a91549..00000000 Binary files a/android/res/drawable-mdpi/or_launcher.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/ic_menu_add.png b/android/res/drawable-xhdpi/ic_menu_add.png deleted file mode 100644 index 7d498a96..00000000 Binary files a/android/res/drawable-xhdpi/ic_menu_add.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/ic_menu_archive.png b/android/res/drawable-xhdpi/ic_menu_archive.png deleted file mode 100644 index b1be9d5b..00000000 Binary files a/android/res/drawable-xhdpi/ic_menu_archive.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/ic_menu_info_details.png b/android/res/drawable-xhdpi/ic_menu_info_details.png deleted file mode 100644 index 24ea5437..00000000 Binary files a/android/res/drawable-xhdpi/ic_menu_info_details.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/ic_menu_preferences.png b/android/res/drawable-xhdpi/ic_menu_preferences.png deleted file mode 100644 index 02cfbad0..00000000 Binary files a/android/res/drawable-xhdpi/ic_menu_preferences.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/ic_menu_save.png b/android/res/drawable-xhdpi/ic_menu_save.png deleted file mode 100644 index 62a66d87..00000000 Binary files a/android/res/drawable-xhdpi/ic_menu_save.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/ic_menu_search.png b/android/res/drawable-xhdpi/ic_menu_search.png deleted file mode 100644 index 5c18f9e8..00000000 Binary files a/android/res/drawable-xhdpi/ic_menu_search.png and /dev/null differ diff --git a/android/res/drawable-xhdpi/or_launcher.png b/android/res/drawable-xhdpi/or_launcher.png deleted file mode 100644 index f13148d2..00000000 Binary files a/android/res/drawable-xhdpi/or_launcher.png and /dev/null differ diff --git a/android/res/drawable/filebrowser_home.xml b/android/res/drawable/filebrowser_home.xml deleted file mode 100644 index 1ca0fef6..00000000 --- a/android/res/drawable/filebrowser_home.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/android/res/drawable/openrocket.png b/android/res/drawable/openrocket.png deleted file mode 100644 index ca28bf5b..00000000 Binary files a/android/res/drawable/openrocket.png and /dev/null differ diff --git a/android/res/drawable/rocketglobe.png b/android/res/drawable/rocketglobe.png deleted file mode 100644 index 6deb572b..00000000 Binary files a/android/res/drawable/rocketglobe.png and /dev/null differ diff --git a/android/res/drawable/sf_donate.png b/android/res/drawable/sf_donate.png deleted file mode 100644 index 7f5a52c5..00000000 Binary files a/android/res/drawable/sf_donate.png and /dev/null differ diff --git a/android/res/drawable/simulation_state.xml b/android/res/drawable/simulation_state.xml deleted file mode 100644 index 28e59234..00000000 --- a/android/res/drawable/simulation_state.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/android/res/drawable/simulation_state_green.xml b/android/res/drawable/simulation_state_green.xml deleted file mode 100644 index 4ccef189..00000000 --- a/android/res/drawable/simulation_state_green.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/android/res/drawable/simulation_state_red.xml b/android/res/drawable/simulation_state_red.xml deleted file mode 100644 index 37c5b523..00000000 --- a/android/res/drawable/simulation_state_red.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/android/res/drawable/simulation_state_yellow.xml b/android/res/drawable/simulation_state_yellow.xml deleted file mode 100644 index 1d258478..00000000 --- a/android/res/drawable/simulation_state_yellow.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/android/res/drawable/starfield.png b/android/res/drawable/starfield.png deleted file mode 100644 index 6ce43c53..00000000 Binary files a/android/res/drawable/starfield.png and /dev/null differ diff --git a/android/res/layout-land/main.xml b/android/res/layout-land/main.xml deleted file mode 100644 index 693bf737..00000000 --- a/android/res/layout-land/main.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - -
- * - * @author fas@congrace.de - * - */ -public class CommandlineInterpreter { - private static void calculateExpression(String string) { - try { - final PostfixExpression pe = PostfixExpression.fromInfix(string); - System.out.println(pe.calculate()); - } catch (UnparsableExpressionException e) { - e.printStackTrace(); - } catch (UnknownFunctionException e) { - e.printStackTrace(); - } - } - - public static void main(String[] args) { - if (args.length != 1) { - printUsage(); - } else { - calculateExpression(args[0]); - } - } - - private static void printUsage() { - final StringBuilder usage = new StringBuilder(); - usage.append("Commandline Expression Parser\n\n").append("Example: ").append("\n").append("java -jar exp4j.jar \"2.12 * log(23) * (12 - 4)\"\n\n") - .append("written by fas@congrace.de"); - System.err.println(usage.toString()); - } -} diff --git a/core/src/de/congrace/exp4j/CustomFunction.java b/core/src/de/congrace/exp4j/CustomFunction.java deleted file mode 100644 index f49f9481..00000000 --- a/core/src/de/congrace/exp4j/CustomFunction.java +++ /dev/null @@ -1,90 +0,0 @@ -package de.congrace.exp4j; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import de.congrace.exp4j.FunctionToken.Function; - -/** - * this classed is used to create custom functions for exp4j
- *
- * Example
- *
{@code 
- * CustomFunction fooFunc = new CustomFunction("foo") {
- * 		public double applyFunction(double value) {
- * 			return value*Math.E;
- * 		}
- * };
- * double varX=12d;
- * Calculable calc = new ExpressionBuilder("foo(x)").withCustomFunction(fooFunc).withVariable("x",varX).build();
- * assertTrue(calc.calculate() == Math.E * varX);
- * }
- * - * @author ruckus - * - */ -public abstract class CustomFunction extends CalculationToken { - private int argc=1; - - /** - * create a new single value input CustomFunction with a set name - * - * @param value - * the name of the function (e.g. foo) - */ - protected CustomFunction(String value) throws InvalidCustomFunctionException{ - super(value); - for (Function f:Function.values()) { - if (value.equalsIgnoreCase(f.toString())){ - throw new InvalidCustomFunctionException(value + " is already reserved as a function name"); - } - } - } - - /** - * create a new single value input CustomFunction with a set name - * - * @param value - * the name of the function (e.g. foo) - */ - protected CustomFunction(String value,int argumentCount) throws InvalidCustomFunctionException{ - super(value); - this.argc=argumentCount; - for (Function f:Function.values()) { - if (value.equalsIgnoreCase(f.toString())){ - throw new InvalidCustomFunctionException(value + " is already reserved as a function name"); - } - } - } - - /** - * apply the function to a value - * - * @param values - * the values to which the function should be applied. - * @return the function value - */ - public abstract Variable applyFunction(List vars); - - @Override - void mutateStackForCalculation(Stack stack, VariableSet variables) { - List args = new ArrayList(argc); - for (int i=0; i < argc; i++) { - args.add(i, stack.pop() ); - } - Collections.reverse(args); // Put elements in logical order - - stack.push(this.applyFunction(args)); - } - - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - operatorStack.push(this); - } - public int getArgumentCount() { - return argc; - } -} diff --git a/core/src/de/congrace/exp4j/Example.java b/core/src/de/congrace/exp4j/Example.java deleted file mode 100644 index 0d70b0b0..00000000 --- a/core/src/de/congrace/exp4j/Example.java +++ /dev/null @@ -1,77 +0,0 @@ -package de.congrace.exp4j; - -import java.util.List; - -public class Example { - - public static void main(String[] args) throws UnknownFunctionException, UnparsableExpressionException, InvalidCustomFunctionException { - - // Test 1 - // ====== - - Calculable calc1 = new ExpressionBuilder("x * y - 2").withVariableNames("x", "y").build(); - calc1.setVariable(new Variable("x", 1.2)); - calc1.setVariable(new Variable("y", 2.2)); - - System.out.println(calc1.calculate().toString()); - //double result = calc1.calculate().getDoubleValue(); - //System.out.println(result); - - // Test 2 - // ====== - - // A function which calculates the mean of an array and scales it - CustomFunction meanFn = new CustomFunction("mean",2) { - public Variable applyFunction(List vars) { - - double[] vals; - double scale; - - try{ - vals = vars.get(0).getArrayValue(); - scale = vars.get(1).getDoubleValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - - double subtotal = 0; - for (int i = 0; i < vals.length; i++ ){ - subtotal += vals[i]; - } - - subtotal = scale * subtotal / vals.length; - return new Variable("double MEAN result, ", subtotal); - - } - }; - - ExpressionBuilder b = new ExpressionBuilder("mean(x,y)"); - b.withCustomFunction(meanFn); - b.withVariable(new Variable("x", new double[] {1.1,2,10,3,2.4,10.2})); - b.withVariable(new Variable("y", 2)); - Calculable calc2 = b.build(); - - System.out.println( calc2.calculate().toString() ); - - // Test 3 - // ====== - - Calculable calc3 = new ExpressionBuilder("x * y - 2").withVariableNames("x", "y").build(); - calc3.setVariable(new Variable("x", new double[]{1.2, 10, 20, 15})); - calc3.setVariable(new Variable("y", new double[]{2.2, 5.2, 12, 9 })); - - //double result3 = calc3.calculate().getDoubleValue(); - System.out.println(calc3.calculate().toString()); - - - // Test 4 - // ====== - - Calculable calc4 = new ExpressionBuilder("log10(sqrt(x) * abs(y))").withVariableNames("x", "y").build(); - calc4.setVariable(new Variable("x", new double[]{1.2, 10, 10, 15})); - calc4.setVariable(new Variable("y", new double[]{2.2, -5.2, 5.2, 9 })); - - //double result3 = calc3.calculate().getDoubleValue(); - System.out.println(calc4.calculate().toString()); - } -} diff --git a/core/src/de/congrace/exp4j/ExpressionBuilder.java b/core/src/de/congrace/exp4j/ExpressionBuilder.java deleted file mode 100644 index 8ecf1b5c..00000000 --- a/core/src/de/congrace/exp4j/ExpressionBuilder.java +++ /dev/null @@ -1,135 +0,0 @@ -package de.congrace.exp4j; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * This is Builder implementation for the exp4j API used to create a Calculable - * instance for the user - * - * @author ruckus - * - */ -public class ExpressionBuilder { - private VariableSet variables = new VariableSet(); - private final Set customFunctions = new HashSet(); - - private String expression; - - /** - * Create a new ExpressionBuilder - * - * @param expression - * the expression to evaluate - */ - public ExpressionBuilder(String expression) { - this.expression = expression; - } - - /** - * build a new {@link Calculable} from the expression using the supplied - * variables - * - * @return the {@link Calculable} which can be used to evaluate the - * expression - * @throws UnknownFunctionException - * when an unrecognized function name is used in the expression - * @throws UnparsableExpressionException - * if the expression could not be parsed - */ - public Calculable build() throws UnknownFunctionException, UnparsableExpressionException { - if (expression.indexOf('=') == -1 && !variables.isEmpty()) { - - // User supplied an expression without leading "f(...)=" - // so we just append the user function to a proper "f()=" - // for PostfixExpression.fromInfix() - StringBuilder function = new StringBuilder("f("); - for (String name : variables.getVariableNames()) { - function.append(name).append(','); - } - expression = function.deleteCharAt(function.length() - 1).toString() + ")=" + expression; - } - // create the PostfixExpression and return it as a Calculable - PostfixExpression delegate = PostfixExpression.fromInfix(expression, customFunctions); - for (Variable var : variables ) { - delegate.setVariable(var); - for (CustomFunction fn:customFunctions){ - if (fn.getValue().equalsIgnoreCase(var.getName())){ - throw new UnparsableExpressionException("variable '" + var + "' cannot have the same name as a custom function " + fn.getValue()); - } - } - } - return delegate; - } - - /** - * add a custom function instance for the evaluator to recognize - * - * @param function - * the {@link CustomFunction} to add - * @return the {@link ExpressionBuilder} instance - */ - public ExpressionBuilder withCustomFunction(CustomFunction function) { - customFunctions.add(function); - return this; - } - - public ExpressionBuilder withCustomFunctions(Collection functions) { - customFunctions.addAll(functions); - return this; - } - - /** - * set the value for a variable - * - * @param variableName - * the variable name e.g. "x" - * @param value - * the value e.g. 2.32d - * @return the {@link ExpressionBuilder} instance - */ - public ExpressionBuilder withVariable(Variable value) { - variables.add(value); - return this; - } - - /* - * Provided for backwards compatibility - */ - @Deprecated - public ExpressionBuilder withVariable(String variableName, double value) { - variables.add(new Variable(variableName, value)); - return this; - } - - /** - * set the variables names used in the expression without setting their - * values. Usefull for building an expression before you know the variable values. - * - * @param variableNames - * vararg {@link String} of the variable names used in the - * expression - * @return the ExpressionBuilder instance - */ - - public ExpressionBuilder withVariableNames(String... variableNames) { - for (String name : variableNames) { - variables.add( new Variable(name, Double.NaN) ); - } - return this; - } - - - /** - * set the values for variables - * - * @param variableMap - * a map of variable names to variable values - * @return the {@link ExpressionBuilder} instance - */ - public ExpressionBuilder withVariables(VariableSet variables) { - this.variables = variables; - return this; - } -} diff --git a/core/src/de/congrace/exp4j/FunctionSeparatorToken.java b/core/src/de/congrace/exp4j/FunctionSeparatorToken.java deleted file mode 100644 index 24b1109d..00000000 --- a/core/src/de/congrace/exp4j/FunctionSeparatorToken.java +++ /dev/null @@ -1,17 +0,0 @@ -package de.congrace.exp4j; - -import java.util.Stack; - -public class FunctionSeparatorToken extends Token{ - public FunctionSeparatorToken() { - super(","); - } - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - Token token; - while (!((token=operatorStack.peek()) instanceof ParenthesisToken) && !token.getValue().equals("(")){ - output.append(operatorStack.pop().getValue()).append(" "); - } - } - -} diff --git a/core/src/de/congrace/exp4j/FunctionToken.java b/core/src/de/congrace/exp4j/FunctionToken.java deleted file mode 100644 index 6bc620ce..00000000 --- a/core/src/de/congrace/exp4j/FunctionToken.java +++ /dev/null @@ -1,161 +0,0 @@ -/* -Copyright 2011 frank asseg - -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 de.congrace.exp4j; - -import java.util.Stack; - -/** - * A {@link Token} for functions - * - * @author fas@congrace.de - * - */ -class FunctionToken extends CalculationToken { - /** - * the functionNames that can be used in an expression - * - * @author ruckus - * - */ - enum Function { - ABS, ACOS, ASIN, ATAN, CBRT, CEIL, COS, COSH, EXP, EXPM1, FLOOR, ROUND, RANDOM, LOG, SIN, SINH, SQRT, TAN, TANH, LOG10 - } - - private Function function; - - /** - * construct a new {@link FunctionToken} - * - * @param value - * the name of the function - * @throws UnknownFunctionException - * if an unknown function name is encountered - */ - FunctionToken(String value) throws UnknownFunctionException { - super(value); - try { - function = Function.valueOf(value.toUpperCase()); - } catch (IllegalArgumentException e) { - throw new UnknownFunctionException(value); - } - if (function == null) { - throw new UnknownFunctionException(value); - } - } - - /** - * apply a function to a variable - * - * @param x - * the value the function should be applied to - * @return the result of the function - */ - public Variable applyFunction(Variable var) { - - // The names here are strictly unused, but are useful for debugging - String name = function.name() + " result (#"+var.hashCode()+"), "; - - switch (var.getPrimary()) { - case DOUBLE: - name = "double "+name; - double x = var.getDoubleValue(); - return new Variable(name, applyFunction(x) ); - - case ARRAY: - name = "array "+name; - double[] input = var.getArrayValue(); - double[] result = new double[input.length]; - for (int i = 0; i < input.length; i++){ - result[i] = applyFunction(input[i]); - } - return new Variable(name, result); - - default: - return new Variable("Invalid"); - } - } - - /* - * The actual function application on a double - */ - private double applyFunction(double x){ - switch (function) { - case ABS: - return Math.abs(x); - case ACOS: - return Math.acos(x); - case ASIN: - return Math.asin(x); - case ATAN: - return Math.atan(x); - case CBRT: - return Math.cbrt(x); - case CEIL: - return Math.ceil(x); - case COS: - return Math.cos(x); - case COSH: - return Math.cosh(x); - case EXP: - return Math.exp(x); - case EXPM1: - return Math.expm1(x); - case FLOOR: - return Math.floor(x); - case ROUND: - return Math.round(x); - case RANDOM: - return Math.random()*x; - case LOG: - return Math.log(x); - case LOG10: - return Math.log10(x); - case SIN: - return Math.sin(x); - case SINH: - return Math.sinh(x); - case SQRT: - return Math.sqrt(x); - case TAN: - return Math.tan(x); - case TANH: - return Math.tanh(x); - default: - return Double.NaN; // should not happen ;) - } - } - - /** - * - * get the {@link Function} - * - * @return the correspoding {@link Function} - */ - Function getFunction() { - return function; - } - - @Override - void mutateStackForCalculation(Stack stack, VariableSet variableValues) { - stack.push(this.applyFunction(stack.pop())); - } - - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - operatorStack.push(this); - } -} diff --git a/core/src/de/congrace/exp4j/InfixTranslator.java b/core/src/de/congrace/exp4j/InfixTranslator.java deleted file mode 100644 index 9712bce3..00000000 --- a/core/src/de/congrace/exp4j/InfixTranslator.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Set; -import java.util.Stack; - -/** - * Translate a mathematical expression in human readable infix notation to a - * Reverse Polish Notation (postfix) expression for easier parsing. by - * implementing the shunting yard algorithm by dijkstra - * - * @author fas@congrace.de - */ -class InfixTranslator { - - private static String substituteUnaryOperators(String expr) { - final StringBuilder exprBuilder = new StringBuilder(expr.length()); - final char[] data = expr.toCharArray(); - char lastChar = ' '; - for (int i = 0; i < expr.length(); i++) { - if (exprBuilder.length() > 0) { - lastChar = exprBuilder.charAt(exprBuilder.length() - 1); - } - final char c = data[i]; - switch (c) { - case '+': - if (i > 0 && lastChar != '(' && !(OperatorToken.isOperator(lastChar))) { - exprBuilder.append(c); - } - break; - case '-': - if (i > 0 && lastChar != '(' && !(OperatorToken.isOperator(lastChar))) { - exprBuilder.append(c); - } else { - exprBuilder.append('#'); - } - break; - default: - if (!Character.isWhitespace(c)) { - exprBuilder.append(c); - } - } - } - return exprBuilder.toString(); - } - - /** - * Delegation method for simple expression without variables or custom - * functions - * - * @param infixExpression - * the infix expression to be translated - * @return translated RNP postfix expression - * @throws UnparsableExpressionException - * when the expression is invalid - * @throws UnknownFunctionException - * when an unknown function has been used in the input. - */ - static String toPostfixExpression(String infixExpression) throws UnparsableExpressionException, UnknownFunctionException { - return toPostfixExpression(infixExpression, null, null); - } - - /** - * implement the shunting yard algorithm - * - * @param infixExpression - * the human readable expression which should be translated to - * RPN - * @param variableNames - * the variable names used in the expression - * @param customFunctions - * the CustomFunction implementations used - * @return the expression in postfix format - * @throws UnparsableExpressionException - * if the expression could not be translated to RPN - * @throws UnknownFunctionException - * if an unknown function was encountered - */ - static String toPostfixExpression(String infixExpression, String[] variableStrings, Set customFunctions) - throws UnparsableExpressionException, UnknownFunctionException { - infixExpression = substituteUnaryOperators(infixExpression); - final Token[] tokens = new Tokenizer(variableStrings, customFunctions).tokenize(infixExpression); - final StringBuilder output = new StringBuilder(tokens.length); - final Stack operatorStack = new Stack(); - for (final Token token : tokens) { - token.mutateStackForInfixTranslation(operatorStack, output); - } - // all tokens read, put the rest of the operations on the output; - while (operatorStack.size() > 0) { - output.append(operatorStack.pop().getValue()).append(" "); - } - return output.toString().trim(); - } -} diff --git a/core/src/de/congrace/exp4j/InvalidCustomFunctionException.java b/core/src/de/congrace/exp4j/InvalidCustomFunctionException.java deleted file mode 100644 index e3810db0..00000000 --- a/core/src/de/congrace/exp4j/InvalidCustomFunctionException.java +++ /dev/null @@ -1,9 +0,0 @@ -package de.congrace.exp4j; - -public class InvalidCustomFunctionException extends Exception{ - private static final long serialVersionUID = 1L; - - public InvalidCustomFunctionException(String message) { - super(message); - } -} diff --git a/core/src/de/congrace/exp4j/NumberToken.java b/core/src/de/congrace/exp4j/NumberToken.java deleted file mode 100644 index b765d451..00000000 --- a/core/src/de/congrace/exp4j/NumberToken.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Map; -import java.util.Stack; - -/** - * A {@link Token} for Numbers - * - * @author fas@congrace.de - * - */ -class NumberToken extends CalculationToken { - - private final double doubleValue; - - /** - * construct a new {@link NumberToken} - * - * @param value - * the value of the number as a {@link String} - */ - NumberToken(String value) { - super(value); - this.doubleValue = Double.parseDouble(value); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof NumberToken) { - final NumberToken t = (NumberToken) obj; - return t.getValue().equals(this.getValue()); - } - return false; - } - - @Override - public int hashCode() { - return getValue().hashCode(); - } - - @Override - void mutateStackForCalculation(Stack stack, VariableSet variables) { - stack.push(new Variable("From number "+getValue()+" : "+hashCode(), this.doubleValue)); - } - - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - output.append(this.getValue()).append(' '); - } -} diff --git a/core/src/de/congrace/exp4j/OperatorToken.java b/core/src/de/congrace/exp4j/OperatorToken.java deleted file mode 100644 index 765f4508..00000000 --- a/core/src/de/congrace/exp4j/OperatorToken.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Stack; - -/** - * {@link Token} for Operations like +,-,*,/,% and ^ - * - * @author fas@congrace.de - */ -class OperatorToken extends CalculationToken { - - /** - * the valid {@link Operation}s for the {@link OperatorToken} - * - * @author fas@congrace.de - */ - enum Operation { - ADDITION(1, true), SUBTRACTION(1, true), MULTIPLICATION(2, true), DIVISION(2, true), MODULO(2, true), EXPONENTIATION(3, false), UNARY_MINUS(4, false), UNARY_PLUS( - 4, false); - private final int precedence; - private final boolean leftAssociative; - - private Operation(int precedence, boolean leftAssociative) { - this.precedence = precedence; - this.leftAssociative = leftAssociative; - } - } - - /** - * return a corresponding {@link Operation} for a symbol - * - * @param c - * the symbol of the operation - * @return the corresponding {@link Operation} - */ - static Operation getOperation(char c) { - switch (c) { - case '+': - return Operation.ADDITION; - case '-': - return Operation.SUBTRACTION; - case '*': - return Operation.MULTIPLICATION; - case '/': - return Operation.DIVISION; - case '^': - return Operation.EXPONENTIATION; - case '#': - return Operation.UNARY_MINUS; - case '%': - return Operation.MODULO; - default: - return null; - } - } - - static boolean isOperator(char c) { - return getOperation(c) != null; - } - - private final Operation operation; - - /** - * construct a new {@link OperatorToken} - * - * @param value - * the symbol (e.g.: '+') - * @param operation - * the {@link Operation} of this {@link Token} - */ - OperatorToken(String value, Operation operation) { - super(value); - this.operation = operation; - } - - /** - * apply the {@link Operation} - * - * @param values - * the doubles to operate on - * @return the result of the {@link Operation} - * @throws UnparsableExpressionException - */ - public Variable applyOperation(Variable... values) { - - values = expandVariables(values); - - double[] inputs = new double[values.length]; - switch (values[0].getPrimary()){ - - case DOUBLE: - for (int i = 0; i stack, VariableSet variables) { - if (this.getOperandCount() == 2) { - final Variable n2 = stack.pop(); - final Variable n1 = stack.pop(); - stack.push(this.applyOperation(n1, n2)); - } else if (this.getOperandCount() == 1) { - final Variable n1 = stack.pop(); - stack.push(this.applyOperation(n1)); - } - } - - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - Token before; - while (!operatorStack.isEmpty() && (before = operatorStack.peek()) != null && (before instanceof OperatorToken || before instanceof FunctionToken)) { - if (before instanceof FunctionToken) { - operatorStack.pop(); - output.append(before.getValue()).append(" "); - } else { - final OperatorToken stackOperator = (OperatorToken) before; - if (this.isLeftAssociative() && this.getPrecedence() <= stackOperator.getPrecedence()) { - output.append(operatorStack.pop().getValue()).append(" "); - } else if (!this.isLeftAssociative() && this.getPrecedence() < stackOperator.getPrecedence()) { - output.append(operatorStack.pop().getValue()).append(" "); - } else { - break; - } - } - } - operatorStack.push(this); - } -} diff --git a/core/src/de/congrace/exp4j/ParenthesisToken.java b/core/src/de/congrace/exp4j/ParenthesisToken.java deleted file mode 100644 index ad8ab0f6..00000000 --- a/core/src/de/congrace/exp4j/ParenthesisToken.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Stack; - -/** - * Token for parenthesis - * - * @author fas@congrace.de - */ -class ParenthesisToken extends Token { - - ParenthesisToken(String value) { - super(value); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof ParenthesisToken) { - final ParenthesisToken t = (ParenthesisToken) obj; - return t.getValue().equals(this.getValue()); - } - return false; - } - - @Override - public int hashCode() { - return getValue().hashCode(); - } - - /** - * check the direction of the parenthesis - * - * @return true if it's a left parenthesis (open) false if it is a right - * parenthesis (closed) - */ - boolean isOpen() { - return getValue().equals("(") || getValue().equals("[") || getValue().equals("{"); - } - - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - if (this.isOpen()) { - operatorStack.push(this); - } else { - Token next; - while ((next = operatorStack.peek()) instanceof OperatorToken || next instanceof FunctionToken || next instanceof CustomFunction - || (next instanceof ParenthesisToken && !((ParenthesisToken) next).isOpen())) { - output.append(operatorStack.pop().getValue()).append(" "); - } - operatorStack.pop(); - } - } -} diff --git a/core/src/de/congrace/exp4j/PostfixExpression.java b/core/src/de/congrace/exp4j/PostfixExpression.java deleted file mode 100644 index 0bbcc142..00000000 --- a/core/src/de/congrace/exp4j/PostfixExpression.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Set; -import java.util.Stack; - -/** - * Class for calculating values from a RPN postfix expression.
- * The default way to create a new instance of {@link PostfixExpression} is by - * using the static factory method fromInfix() - * - * @author fas@congrace.de - */ -public final class PostfixExpression extends AbstractExpression implements Calculable { - - private VariableSet variables = new VariableSet(); - - /** - * Factory method for creating {@link PostfixExpression}s from human - * readable infix expressions - * - * @param expression - * the infix expression to be used - * @return an equivalent {@link PostfixExpression} - * @throws UnparsableExpressionException - * if the expression was invalid - * @throws UnknownFunctionException - * if an unknown function has been used - * @deprecated please use {@link ExpressionBuilder} API - */ - @Deprecated - public static PostfixExpression fromInfix(String expression) throws UnparsableExpressionException, UnknownFunctionException { - return fromInfix(expression, null); - } - - /** - * Factory method for creating {@link PostfixExpression}s from human - * readable infix expressions - * - * @param expression - * the infix expression to be used - * @param customFunctions - * the CustomFunction implementations used - * @return an equivalent {@link PostfixExpression} - * @throws UnparsableExpressionException - * if the expression was invalid - * @throws UnknownFunctionException - * if an unknown function has been used - * @deprecated please use {@link ExpressionBuilder} - */ - @Deprecated - public static PostfixExpression fromInfix(String expression, Set customFunctions) throws UnparsableExpressionException, - UnknownFunctionException { - String[] variableStrings = null; - int posStart, posEnd; - if ((posStart = expression.indexOf('=')) > 0) { - String functionDef = expression.substring(0, posStart); - expression = expression.substring(posStart + 1); - if ((posStart = functionDef.indexOf('(')) > 0 && (posEnd = functionDef.indexOf(')')) > 0) { - variableStrings = functionDef.substring(posStart + 1, posEnd).split(","); - } - } - return new PostfixExpression(InfixTranslator.toPostfixExpression(expression, variableStrings, customFunctions), variableStrings, customFunctions); - } - - /** - * Construct a new simple {@link PostfixExpression} - * - * @param expression - * the postfix expression to be calculated - * @param variableNames - * the variable names in the expression - * @param customFunctions - * the CustomFunction implementations used - * @throws UnparsableExpressionException - * when expression is invalid - * @throws UnknownFunctionException - * when an unknown function has been used - */ - private PostfixExpression(String expression, String[] variableStrings, Set customFunctions) throws UnparsableExpressionException, - UnknownFunctionException { - super(expression, new Tokenizer(variableStrings, customFunctions).tokenize(expression), variableStrings); - } - - /** - * delegate the calculation of a simple expression - */ - public Variable calculate() throws IllegalArgumentException { - - final Stack stack = new Stack(); - for (final Token t : getTokens()) { - ((CalculationToken) t).mutateStackForCalculation(stack, variables); - } - return stack.pop(); - - } - - public void setVariable(Variable value) { - variables.add(value); - } -} diff --git a/core/src/de/congrace/exp4j/Token.java b/core/src/de/congrace/exp4j/Token.java deleted file mode 100644 index 2ce4030a..00000000 --- a/core/src/de/congrace/exp4j/Token.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Stack; - -/** - * Superclass for tokenized Strings - * - * @author fas@congrace.de - */ -abstract class Token { - private final String value; - - /** - * construct a new {@link Token} - * - * @param value - * the value of the {@link Token} - */ - Token(String value) { - super(); - this.value = value; - } - - /** - * get the value (String representation) of the token - * - * @return the value - */ - String getValue() { - return value; - } - - abstract void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output); -} diff --git a/core/src/de/congrace/exp4j/Tokenizer.java b/core/src/de/congrace/exp4j/Tokenizer.java deleted file mode 100644 index c2c99d97..00000000 --- a/core/src/de/congrace/exp4j/Tokenizer.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import de.congrace.exp4j.FunctionToken.Function; - -/** - * Class for tokenizing mathematical expressions by breaking an expression up - * into multiple different {@link Token}s - * - * @author fas@congrace.de - */ -class Tokenizer { - private String[] variableNames; - private final Set functionNames = new HashSet(); - private final Set customFunctions; - - { - functionNames.add("abs"); - functionNames.add("acos"); - functionNames.add("asin"); - functionNames.add("atan"); - functionNames.add("cbrt"); - functionNames.add("ceil"); - functionNames.add("cos"); - functionNames.add("cosh"); - functionNames.add("exp"); - functionNames.add("expm1"); - functionNames.add("floor"); - functionNames.add("log"); - functionNames.add("sin"); - functionNames.add("sinh"); - functionNames.add("sqrt"); - functionNames.add("tan"); - functionNames.add("tanh"); - } - - Tokenizer() { - super(); - customFunctions = null; - } - - /** - * construct a new Tokenizer that recognizes variable names - * - * @param variableNames - * the variable names in the expression - * @throws IllegalArgumentException - * if a variable has the name as a function - * @param customFunctions - * the CustomFunction implementations used if the variableNames - * are not valid - */ - Tokenizer(String[] variableNames, Set customFunctions) throws IllegalArgumentException { - super(); - this.variableNames = variableNames; - - if (variableNames != null) { - for (String varName : variableNames) { - if (functionNames.contains(varName.toLowerCase())) { - throw new IllegalArgumentException("Variable '" + varName + "' can not have the same name as a function"); - } - } - } - this.customFunctions = customFunctions; - } - - private Token getCustomFunctionToken(String name) throws UnknownFunctionException { - for (CustomFunction func : customFunctions) { - if (func.getValue().equals(name)) { - return func; - } - } - throw new UnknownFunctionException(name); - } - - private boolean isCustomFunction(String name) { - if (customFunctions == null) { - return false; - } - for (CustomFunction func : customFunctions) { - if (func.getValue().equals(name)) { - return true; - } - } - return false; - } - - /** - * check if a char is part of a number - * - * @param c - * the char to be checked - * @return true if the char is part of a number - */ - private boolean isDigit(char c) { - return Character.isDigit(c) || c == '.'; - } - - private boolean isFunction(String name) { - for (Function fn : Function.values()) { - if (fn.name().equals(name.toUpperCase())) { - return true; - } - } - return false; - } - - /** - * check if a String is a variable name - * - * @param name - * the variable name which is checked to be valid the char to be - * checked - * @return true if the char is a variable name (e.g. x) - */ - private boolean isVariable(String name) { - //String[] variableNames = variables.getVariableNames(); - - if (variableNames != null) { - for (String var : variableNames) { - if (name.equals(var)) { - return true; - } - } - } - return false; - } - - /** - * tokenize an infix expression by breaking it up into different - * {@link Token} that can represent operations,functions,numbers, - * parenthesis or variables - * - * @param infix - * the infix expression to be tokenized - * @return the {@link Token}s representing the expression - * @throws UnparsableExpressionException - * when the expression is invalid - * @throws UnknownFunctionException - * when an unknown function name has been used. - */ - Token[] tokenize(String infix) throws UnparsableExpressionException, UnknownFunctionException { - final List tokens = new ArrayList(); - final char[] chars = infix.toCharArray(); - // iterate over the chars and fork on different types of input - Token lastToken; - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; - - if (c == ' ') - continue; - if (isDigit(c)) { - final StringBuilder valueBuilder = new StringBuilder(1); - // handle the numbers of the expression - valueBuilder.append(c); - int numberLen = 1; - while (chars.length > i + numberLen && isDigit(chars[i + numberLen])) { - valueBuilder.append(chars[i + numberLen]); - numberLen++; - } - i += numberLen - 1; - lastToken = new NumberToken(valueBuilder.toString()); - } else if (Character.isLetter(c) || c == '_' || c == '$') { - // can be a variable or function - final StringBuilder nameBuilder = new StringBuilder(); - nameBuilder.append(c); - int offset = 1; - while (chars.length > i + offset && (Character.isLetter(chars[i + offset]) || Character.isDigit(chars[i + offset]) || chars[i + offset] == '_' || chars[i + offset] == '$')) { - nameBuilder.append(chars[i + offset++]); - } - String name = nameBuilder.toString(); - if (this.isVariable(name)) { - // a variable - i += offset - 1; - lastToken = new VariableToken(name); - } else if (this.isFunction(name)) { - // might be a function - i += offset - 1; - lastToken = new FunctionToken(name); - } else if (this.isCustomFunction(name)) { - // a custom function - i += offset - 1; - lastToken = getCustomFunctionToken(name); - } else { - // an unknown symbol was encountered - throw new UnparsableExpressionException(c, i); - } - }else if (c == ',') { - // a function separator, hopefully - lastToken=new FunctionSeparatorToken(); - } else if (OperatorToken.isOperator(c)) { - lastToken = new OperatorToken(String.valueOf(c), OperatorToken.getOperation(c)); - } else if (c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}') { - lastToken = new ParenthesisToken(String.valueOf(c)); - } else { - // an unknown symbol was encountered - throw new UnparsableExpressionException(c, i); - } - tokens.add(lastToken); - } - return tokens.toArray(new Token[tokens.size()]); - } -} diff --git a/core/src/de/congrace/exp4j/UnknownFunctionException.java b/core/src/de/congrace/exp4j/UnknownFunctionException.java deleted file mode 100644 index ae350932..00000000 --- a/core/src/de/congrace/exp4j/UnknownFunctionException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -/** - * Exception for handling unknown Functions. - * - * @see FunctionToken - * @author fas@congrace.de - */ -public class UnknownFunctionException extends Exception { - private static final long serialVersionUID = 1L; - - /** - * construct a new {@link UnknownFunctionException} - * - * @param functionName - * the function name which could not be found - */ - public UnknownFunctionException(String functionName) { - super("Unknown function: " + functionName); - } -} diff --git a/core/src/de/congrace/exp4j/UnparsableExpressionException.java b/core/src/de/congrace/exp4j/UnparsableExpressionException.java deleted file mode 100644 index fcbf7da2..00000000 --- a/core/src/de/congrace/exp4j/UnparsableExpressionException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -/** - * Exception for invalid expressions - * - * @author fas@congrace.de - */ -public class UnparsableExpressionException extends Exception { - private static final long serialVersionUID = 1L; - - /** - * construct a new {@link UnparsableExpressionException} - * - * @param c - * the character which could not be parsed - * @param pos - * the position of the character in the expression - */ - public UnparsableExpressionException(char c, int pos) { - super("Unable to parse character at position " + pos + ": '" + String.valueOf(c) + "'"); - } - /** - * construct a new {@link UnparsableExpressionException} - * - * @param msg - * the error message - */ - public UnparsableExpressionException(String msg) { - super(msg); - } -} diff --git a/core/src/de/congrace/exp4j/Variable.java b/core/src/de/congrace/exp4j/Variable.java deleted file mode 100644 index 0030e70b..00000000 --- a/core/src/de/congrace/exp4j/Variable.java +++ /dev/null @@ -1,107 +0,0 @@ -package de.congrace.exp4j; - -/* - * Represents a generic variable which can have double or array values. - * Optionally the start and step values corresponding to each array index can be specified for array values - * Tries to do something sensible if you try and apply a regular function / operator to an array - * and vice-versa. - */ -public class Variable { - - // The primary or preferred representation - public enum Primary {DOUBLE, ARRAY, PLACEHOLDER}; - private final Primary primary; - - private final String name; - - private final double doubleValue; - private final double[] arrayValue; - - private final double start, step; - - /* - * Initialize a new variable with a name only. This can be used as a place holder - */ - public Variable(String name){ - this.name = name; - this.primary = Primary.PLACEHOLDER; - this.doubleValue = Double.NaN; - this.arrayValue = new double[] {Double.NaN}; - this.start = Double.NaN; - this.step = Double.NaN; - } - - /* - * Initialize a new double variable - */ - public Variable(String name, double d){ - this.doubleValue = d; - this.arrayValue = new double[] {d}; - this.name = name; - this.primary = Primary.DOUBLE; - this.start = Double.NaN; - this.step = Double.NaN; - } - - /* - * Initialize a new array variable - */ - public Variable(String name, double[] d){ - this.arrayValue = d; - this.doubleValue = d[0]; - this.name = name; - this.primary = Primary.ARRAY; - this.start = Double.NaN; - this.step = Double.NaN; - } - - /* - * Initialize a new array variable, specifying the start and step values - */ - public Variable(String name, double[] d, double start, double step){ - this.arrayValue = d; - this.doubleValue = d[0]; - this.name = name; - this.primary = Primary.ARRAY; - this.start = start; - this.step = step; - } - - public String getName(){ - return name; - } - - public Primary getPrimary(){ - return this.primary; - } - - public double getDoubleValue(){ - return doubleValue; - } - - public double[] getArrayValue(){ - return arrayValue; - } - - public double getStep(){ - return step; - } - - public double getStart(){ - return start; - } - - public String toString(){ - if ( arrayValue.length > 1 ){ - String out = name + " is Array (length " + new Integer(arrayValue.length).toString() + ") : {"; - for (double x : arrayValue){ - out = out + x + ","; - } - out = out.substring(0, out.length()-1); - return out + "}"; - } - else{ - return name + " is double : {" + new Double(doubleValue).toString() + "}"; - } - } -} \ No newline at end of file diff --git a/core/src/de/congrace/exp4j/VariableSet.java b/core/src/de/congrace/exp4j/VariableSet.java deleted file mode 100644 index f567006f..00000000 --- a/core/src/de/congrace/exp4j/VariableSet.java +++ /dev/null @@ -1,42 +0,0 @@ -package de.congrace.exp4j; - -import java.util.HashSet; - -public class VariableSet extends HashSet { - - /** - * - */ - private static final long serialVersionUID = -4212803364398351279L; - - public boolean add(Variable v){ - Variable previous = getVariableNamed(v.getName()); - if ( previous != null ){ - this.remove( previous ); - } - - return super.add(v); - } - - public Variable getVariableNamed(String name){ - for (Variable var : this){ - if (var.getName().equals(name) ){ - return var; - } - } - return null; - } - - public String[] getVariableNames(){ - if (this.size() == 0){ - return null; - } - String names[] = new String[this.size()]; - int i = 0; - for (Variable var : this){ - names[i] = var.getName(); - i++; - } - return names; - } -} diff --git a/core/src/de/congrace/exp4j/VariableToken.java b/core/src/de/congrace/exp4j/VariableToken.java deleted file mode 100644 index 716ef2ee..00000000 --- a/core/src/de/congrace/exp4j/VariableToken.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2011 frank asseg - - 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 de.congrace.exp4j; - -import java.util.Stack; - -/** - * A {@link Token} for representing variables - * - * @author fas - */ -class VariableToken extends CalculationToken { - /** - * construct a new {@link VariableToken} - * - * @param value - * the value of the token - */ - VariableToken(String value) { - super(value); - } - - @Override - void mutateStackForCalculation(Stack stack, VariableSet variableValues) { - Variable value = variableValues.getVariableNamed(this.getValue()); - stack.push(value); - } - - @Override - void mutateStackForInfixTranslation(Stack operatorStack, StringBuilder output) { - output.append(this.getValue()).append(" "); - } -} diff --git a/core/src/net/sf/openrocket/aerodynamics/AbstractAerodynamicCalculator.java b/core/src/net/sf/openrocket/aerodynamics/AbstractAerodynamicCalculator.java deleted file mode 100644 index a92d0ab4..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/AbstractAerodynamicCalculator.java +++ /dev/null @@ -1,116 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import java.util.Map; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; - - -/** - * An abstract aerodynamic calculator implementation, that offers basic implementation - * of some methods and methods for cache validation and purging. - * - * @author Sampo Niskanen - */ - -public abstract class AbstractAerodynamicCalculator implements AerodynamicCalculator { - private static final LogHelper log = Application.getLogger(); - - /** Number of divisions used when calculating worst CP. */ - public static final int DIVISIONS = 360; - - /** - * A WarningSet that can be used if null is passed - * to a calculation method. - */ - protected WarningSet ignoreWarningSet = new WarningSet(); - - /** The aerodynamic modification ID of the latest rocket */ - private int rocketAeroModID = -1; - private int rocketTreeModID = -1; - - - - - //////////////// Aerodynamic calculators //////////////// - - @Override - public abstract Coordinate getCP(Configuration configuration, FlightConditions conditions, - WarningSet warnings); - - @Override - public abstract Map getForceAnalysis(Configuration configuration, FlightConditions conditions, - WarningSet warnings); - - @Override - public abstract AerodynamicForces getAerodynamicForces(Configuration configuration, - FlightConditions conditions, WarningSet warnings); - - - - /* - * The worst theta angle is stored in conditions. - */ - @Override - public Coordinate getWorstCP(Configuration configuration, FlightConditions conditions, - WarningSet warnings) { - FlightConditions cond = conditions.clone(); - Coordinate worst = new Coordinate(Double.MAX_VALUE); - Coordinate cp; - double theta = 0; - - for (int i = 0; i < DIVISIONS; i++) { - cond.setTheta(2 * Math.PI * i / DIVISIONS); - cp = getCP(configuration, cond, warnings); - if (cp.x < worst.x) { - worst = cp; - theta = cond.getTheta(); - } - } - - conditions.setTheta(theta); - - return worst; - } - - - - /** - * Check the current cache consistency. This method must be called by all - * methods that may use any cached data before any other operations are - * performed. If the rocket has changed since the previous call to - * checkCache(), then {@link #voidAerodynamicCache()} is called. - *

- * This method performs the checking based on the rocket's modification IDs, - * so that these method may be called from listeners of the rocket itself. - * - * @param configuration the configuration of the current call - */ - protected final void checkCache(Configuration configuration) { - if (rocketAeroModID != configuration.getRocket().getAerodynamicModID() || - rocketTreeModID != configuration.getRocket().getTreeModID()) { - rocketAeroModID = configuration.getRocket().getAerodynamicModID(); - rocketTreeModID = configuration.getRocket().getTreeModID(); - log.debug("Voiding the aerodynamic cache"); - voidAerodynamicCache(); - } - } - - - - /** - * Void cached aerodynamic data. This method is called whenever a change occurs in - * the rocket structure that affects the aerodynamics of the rocket and when a new - * Rocket is set. This method must be overridden to void any cached data - * necessary. The method must call super.voidAerodynamicCache() during - * its execution. - */ - protected void voidAerodynamicCache() { - // No-op - } - - -} diff --git a/core/src/net/sf/openrocket/aerodynamics/AerodynamicCalculator.java b/core/src/net/sf/openrocket/aerodynamics/AerodynamicCalculator.java deleted file mode 100644 index 0ce3efc5..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/AerodynamicCalculator.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import java.util.Map; - -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Monitorable; - -/** - * An interface for performing aerodynamic calculations on rockets. - * - * @author Sampo Niskanen - */ -public interface AerodynamicCalculator extends Monitorable { - - /** - * Calculate the CP of the specified configuration. - * - * @param configuration the rocket configuration - * @param conditions the flight conditions - * @param warnings the set in which to place warnings, or null - * @return the CP position in absolute coordinates - */ - public Coordinate getCP(Configuration configuration, FlightConditions conditions, WarningSet warnings); - - /** - * Calculate the aerodynamic forces acting upon the rocket. - * - * @param configuration the rocket configuration. - * @param conditions the flight conditions. - * @param warnings the set in which to place warnings, or null. - * @return the aerodynamic forces acting upon the rocket. - */ - public AerodynamicForces getAerodynamicForces(Configuration configuration, - FlightConditions conditions, WarningSet warnings); - - /** - * Calculate the aerodynamic forces acting upon the rocket with a component analysis. - * - * @param configuration the rocket configuration. - * @param conditions the flight conditions. - * @param warnings the set in which to place warnings, or null. - * @return a map from the rocket components to the aerodynamic force portions that component - * exerts. The map contains an value for the base rocket, which is the total - * aerodynamic forces. - */ - public Map getForceAnalysis(Configuration configuration, - FlightConditions conditions, WarningSet warnings); - - /** - * Calculate the worst CP occurring for any lateral wind angle. The worst CP is returned and the theta angle - * that produces the worst CP is stored in the flight conditions. - * - * @param configuration the rocket configuration. - * @param conditions the flight conditions. - * @param warnings the set in which to place warnings, or null. - * @return the worst (foremost) CP position for any lateral wind angle. - */ - public Coordinate getWorstCP(Configuration configuration, FlightConditions conditions, - WarningSet warnings); - - /** - * Return a new instance of this aerodynamic calculator type. - * - * @return a new, independent instance of this aerodynamic calculator type - */ - public AerodynamicCalculator newInstance(); - -} diff --git a/core/src/net/sf/openrocket/aerodynamics/AerodynamicForces.java b/core/src/net/sf/openrocket/aerodynamics/AerodynamicForces.java deleted file mode 100644 index 2bb6d75b..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/AerodynamicForces.java +++ /dev/null @@ -1,355 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Monitorable; - -public class AerodynamicForces implements Cloneable, Monitorable { - - /** - * The component this data is referring to. Used in analysis methods. - * A total value is indicated by the component being the Rocket component. - */ - private RocketComponent component = null; - - - /** CP and CNa. */ - private Coordinate cp = null; - - - /** - * Normal force coefficient derivative. At values close to zero angle of attack - * this value may be poorly defined or NaN if the calculation method does not - * compute CNa directly. - */ - private double CNa = Double.NaN; - - - /** Normal force coefficient. */ - private double CN = Double.NaN; - - /** Pitching moment coefficient, relative to the coordinate origin. */ - private double Cm = Double.NaN; - - /** Side force coefficient, Cy */ - private double Cside = Double.NaN; - - /** Yaw moment coefficient, Cn, relative to the coordinate origin. */ - private double Cyaw = Double.NaN; - - /** Roll moment coefficient, Cl, relative to the coordinate origin. */ - private double Croll = Double.NaN; - - /** Roll moment damping coefficient */ - private double CrollDamp = Double.NaN; - - /** Roll moment forcing coefficient */ - private double CrollForce = Double.NaN; - - - - /** Axial drag coefficient, CA */ - private double Caxial = Double.NaN; - - /** Total drag force coefficient, parallel to the airflow. */ - private double CD = Double.NaN; - - /** Drag coefficient due to fore pressure drag. */ - private double pressureCD = Double.NaN; - - /** Drag coefficient due to base drag. */ - private double baseCD = Double.NaN; - - /** Drag coefficient due to friction drag. */ - private double frictionCD = Double.NaN; - - - private double pitchDampingMoment = Double.NaN; - private double yawDampingMoment = Double.NaN; - - private int modID = 0; - - - public void setComponent(RocketComponent component) { - this.component = component; - modID++; - } - - public RocketComponent getComponent() { - return component; - } - - public void setCP(Coordinate cp) { - this.cp = cp; - modID++; - } - - public Coordinate getCP() { - return cp; - } - - public void setCNa(double cNa) { - CNa = cNa; - modID++; - } - - public double getCNa() { - return CNa; - } - - public void setCN(double cN) { - CN = cN; - modID++; - } - - public double getCN() { - return CN; - } - - public void setCm(double cm) { - Cm = cm; - modID++; - } - - public double getCm() { - return Cm; - } - - public void setCside(double cside) { - Cside = cside; - modID++; - } - - public double getCside() { - return Cside; - } - - public void setCyaw(double cyaw) { - Cyaw = cyaw; - modID++; - } - - public double getCyaw() { - return Cyaw; - } - - public void setCroll(double croll) { - Croll = croll; - modID++; - } - - public double getCroll() { - return Croll; - } - - public void setCrollDamp(double crollDamp) { - CrollDamp = crollDamp; - modID++; - } - - public double getCrollDamp() { - return CrollDamp; - } - - public void setCrollForce(double crollForce) { - CrollForce = crollForce; - modID++; - } - - public double getCrollForce() { - return CrollForce; - } - - public void setCaxial(double caxial) { - Caxial = caxial; - modID++; - } - - public double getCaxial() { - return Caxial; - } - - public void setCD(double cD) { - CD = cD; - modID++; - } - - public double getCD() { - return CD; - } - - public void setPressureCD(double pressureCD) { - this.pressureCD = pressureCD; - modID++; - } - - public double getPressureCD() { - return pressureCD; - } - - public void setBaseCD(double baseCD) { - this.baseCD = baseCD; - modID++; - } - - public double getBaseCD() { - return baseCD; - } - - public void setFrictionCD(double frictionCD) { - this.frictionCD = frictionCD; - modID++; - } - - public double getFrictionCD() { - return frictionCD; - } - - public void setPitchDampingMoment(double pitchDampingMoment) { - this.pitchDampingMoment = pitchDampingMoment; - modID++; - } - - public double getPitchDampingMoment() { - return pitchDampingMoment; - } - - public void setYawDampingMoment(double yawDampingMoment) { - this.yawDampingMoment = yawDampingMoment; - modID++; - } - - public double getYawDampingMoment() { - return yawDampingMoment; - } - - - - /** - * Reset all values to null/NaN. - */ - public void reset() { - setComponent(null); - - setCP(null); - setCNa(Double.NaN); - setCN(Double.NaN); - setCm(Double.NaN); - setCside(Double.NaN); - setCyaw(Double.NaN); - setCroll(Double.NaN); - setCrollDamp(Double.NaN); - setCrollForce(Double.NaN); - setCaxial(Double.NaN); - setCD(Double.NaN); - setPitchDampingMoment(Double.NaN); - setYawDampingMoment(Double.NaN); - } - - /** - * Zero all values to 0 / Coordinate.NUL. Component is left as it was. - */ - public void zero() { - // component untouched - - setCP(Coordinate.NUL); - setCNa(0); - setCN(0); - setCm(0); - setCside(0); - setCyaw(0); - setCroll(0); - setCrollDamp(0); - setCrollForce(0); - setCaxial(0); - setCD(0); - setPitchDampingMoment(0); - setYawDampingMoment(0); - } - - - @Override - public AerodynamicForces clone() { - try { - return (AerodynamicForces)super.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException?!?"); - } - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof AerodynamicForces)) - return false; - AerodynamicForces other = (AerodynamicForces) obj; - - return (MathUtil.equals(this.getCNa(), other.getCNa()) && - MathUtil.equals(this.getCN(), other.getCN()) && - MathUtil.equals(this.getCm(), other.getCm()) && - MathUtil.equals(this.getCside(), other.getCside()) && - MathUtil.equals(this.getCyaw(), other.getCyaw()) && - MathUtil.equals(this.getCroll(), other.getCroll()) && - MathUtil.equals(this.getCrollDamp(), other.getCrollDamp()) && - MathUtil.equals(this.getCrollForce(), other.getCrollForce()) && - MathUtil.equals(this.getCaxial(), other.getCaxial()) && - MathUtil.equals(this.getCD(), other.getCD()) && - MathUtil.equals(this.getPressureCD(), other.getPressureCD()) && - MathUtil.equals(this.getBaseCD(), other.getBaseCD()) && - MathUtil.equals(this.getFrictionCD(), other.getFrictionCD()) && - MathUtil.equals(this.getPitchDampingMoment(), other.getPitchDampingMoment()) && - MathUtil.equals(this.getYawDampingMoment(), other.getYawDampingMoment()) && - this.getCP().equals(other.getCP())); - } - - @Override - public int hashCode() { - return (int) (1000*(this.getCD()+this.getCaxial()+this.getCNa())) + this.getCP().hashCode(); - } - - - @Override - public String toString() { - String text="AerodynamicForces["; - - if (getComponent() != null) - text += "component:" + getComponent() + ","; - if (getCP() != null) - text += "cp:" + getCP() + ","; - - if (!Double.isNaN(getCNa())) - text += "CNa:" + getCNa() + ","; - if (!Double.isNaN(getCN())) - text += "CN:" + getCN() + ","; - if (!Double.isNaN(getCm())) - text += "Cm:" + getCm() + ","; - - if (!Double.isNaN(getCside())) - text += "Cside:" + getCside() + ","; - if (!Double.isNaN(getCyaw())) - text += "Cyaw:" + getCyaw() + ","; - - if (!Double.isNaN(getCroll())) - text += "Croll:" + getCroll() + ","; - if (!Double.isNaN(getCaxial())) - text += "Caxial:" + getCaxial() + ","; - - if (!Double.isNaN(getCD())) - text += "CD:" + getCD() + ","; - - if (text.charAt(text.length()-1) == ',') - text = text.substring(0, text.length()-1); - - text += "]"; - return text; - } - - @Override - public int getModID() { - return modID; - } -} diff --git a/core/src/net/sf/openrocket/aerodynamics/BarrowmanCalculator.java b/core/src/net/sf/openrocket/aerodynamics/BarrowmanCalculator.java deleted file mode 100644 index be139e14..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/BarrowmanCalculator.java +++ /dev/null @@ -1,715 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import static net.sf.openrocket.util.MathUtil.pow2; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; - -import net.sf.openrocket.aerodynamics.barrowman.FinSetCalc; -import net.sf.openrocket.aerodynamics.barrowman.RocketComponentCalc; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.PolyInterpolator; -import net.sf.openrocket.util.Reflection; - -/** - * An aerodynamic calculator that uses the extended Barrowman method to - * calculate the CP of a rocket. - * - * @author Sampo Niskanen - */ -public class BarrowmanCalculator extends AbstractAerodynamicCalculator { - - private static final String BARROWMAN_PACKAGE = "net.sf.openrocket.aerodynamics.barrowman"; - private static final String BARROWMAN_SUFFIX = "Calc"; - - - private Map calcMap = null; - - private double cacheDiameter = -1; - private double cacheLength = -1; - - - - public BarrowmanCalculator() { - - } - - - @Override - public BarrowmanCalculator newInstance() { - return new BarrowmanCalculator(); - } - - - /** - * Calculate the CP according to the extended Barrowman method. - */ - @Override - public Coordinate getCP(Configuration configuration, FlightConditions conditions, - WarningSet warnings) { - checkCache(configuration); - AerodynamicForces forces = calculateNonAxialForces(configuration, conditions, null, warnings); - return forces.getCP(); - } - - - - @Override - public Map getForceAnalysis(Configuration configuration, - FlightConditions conditions, WarningSet warnings) { - checkCache(configuration); - - AerodynamicForces f; - Map map = - new LinkedHashMap(); - - // Add all components to the map - for (RocketComponent c : configuration) { - f = new AerodynamicForces(); - f.setComponent(c); - - map.put(c, f); - } - - - // Calculate non-axial force data - AerodynamicForces total = calculateNonAxialForces(configuration, conditions, map, warnings); - - - // Calculate friction data - total.setFrictionCD(calculateFrictionDrag(configuration, conditions, map, warnings)); - total.setPressureCD(calculatePressureDrag(configuration, conditions, map, warnings)); - total.setBaseCD(calculateBaseDrag(configuration, conditions, map, warnings)); - - total.setComponent(configuration.getRocket()); - map.put(total.getComponent(), total); - - - for (RocketComponent c : map.keySet()) { - f = map.get(c); - if (Double.isNaN(f.getBaseCD()) && Double.isNaN(f.getPressureCD()) && - Double.isNaN(f.getFrictionCD())) - continue; - if (Double.isNaN(f.getBaseCD())) - f.setBaseCD(0); - if (Double.isNaN(f.getPressureCD())) - f.setPressureCD(0); - if (Double.isNaN(f.getFrictionCD())) - f.setFrictionCD(0); - f.setCD(f.getBaseCD() + f.getPressureCD() + f.getFrictionCD()); - f.setCaxial(calculateAxialDrag(conditions, f.getCD())); - } - - return map; - } - - - - @Override - public AerodynamicForces getAerodynamicForces(Configuration configuration, - FlightConditions conditions, WarningSet warnings) { - checkCache(configuration); - - if (warnings == null) - warnings = ignoreWarningSet; - - // Calculate non-axial force data - AerodynamicForces total = calculateNonAxialForces(configuration, conditions, null, warnings); - - // Calculate friction data - total.setFrictionCD(calculateFrictionDrag(configuration, conditions, null, warnings)); - total.setPressureCD(calculatePressureDrag(configuration, conditions, null, warnings)); - total.setBaseCD(calculateBaseDrag(configuration, conditions, null, warnings)); - - total.setCD(total.getFrictionCD() + total.getPressureCD() + total.getBaseCD()); - - total.setCaxial(calculateAxialDrag(conditions, total.getCD())); - - // Calculate pitch and yaw damping moments - calculateDampingMoments(configuration, conditions, total); - total.setCm(total.getCm() - total.getPitchDampingMoment()); - total.setCyaw(total.getCyaw() - total.getYawDampingMoment()); - - - return total; - } - - - - - /* - * Perform the actual CP calculation. - */ - private AerodynamicForces calculateNonAxialForces(Configuration configuration, FlightConditions conditions, - Map map, WarningSet warnings) { - - checkCache(configuration); - - AerodynamicForces total = new AerodynamicForces(); - total.zero(); - - double radius = 0; // aft radius of previous component - double componentX = 0; // aft coordinate of previous component - AerodynamicForces forces = new AerodynamicForces(); - - if (warnings == null) - warnings = ignoreWarningSet; - - if (conditions.getAOA() > 17.5 * Math.PI / 180) - warnings.add(new Warning.LargeAOA(conditions.getAOA())); - - - if (calcMap == null) - buildCalcMap(configuration); - - for (RocketComponent component : configuration) { - - // Skip non-aerodynamic components - if (!component.isAerodynamic()) - continue; - - // Check for discontinuities - if (component instanceof SymmetricComponent) { - SymmetricComponent sym = (SymmetricComponent) component; - // TODO:LOW: Ignores other cluster components (not clusterable) - double x = component.toAbsolute(Coordinate.NUL)[0].x; - - // Check for lengthwise discontinuity - if (x > componentX + 0.0001) { - if (!MathUtil.equals(radius, 0)) { - warnings.add(Warning.DISCONTINUITY); - radius = 0; - } - } - componentX = component.toAbsolute(new Coordinate(component.getLength()))[0].x; - - // Check for radius discontinuity - if (!MathUtil.equals(sym.getForeRadius(), radius)) { - warnings.add(Warning.DISCONTINUITY); - // TODO: MEDIUM: Apply correction to values to cp and to map - } - radius = sym.getAftRadius(); - } - - // Call calculation method - forces.zero(); - calcMap.get(component).calculateNonaxialForces(conditions, forces, warnings); - forces.setCP(component.toAbsolute(forces.getCP())[0]); - forces.setCm(forces.getCN() * forces.getCP().x / conditions.getRefLength()); - - if (map != null) { - AerodynamicForces f = map.get(component); - - f.setCP(forces.getCP()); - f.setCNa(forces.getCNa()); - f.setCN(forces.getCN()); - f.setCm(forces.getCm()); - f.setCside(forces.getCside()); - f.setCyaw(forces.getCyaw()); - f.setCroll(forces.getCroll()); - f.setCrollDamp(forces.getCrollDamp()); - f.setCrollForce(forces.getCrollForce()); - } - - total.setCP(total.getCP().average(forces.getCP())); - total.setCNa(total.getCNa() + forces.getCNa()); - total.setCN(total.getCN() + forces.getCN()); - total.setCm(total.getCm() + forces.getCm()); - total.setCside(total.getCside() + forces.getCside()); - total.setCyaw(total.getCyaw() + forces.getCyaw()); - total.setCroll(total.getCroll() + forces.getCroll()); - total.setCrollDamp(total.getCrollDamp() + forces.getCrollDamp()); - total.setCrollForce(total.getCrollForce() + forces.getCrollForce()); - } - - return total; - } - - - - - //////////////// DRAG CALCULATIONS //////////////// - - - private double calculateFrictionDrag(Configuration configuration, FlightConditions conditions, - Map map, WarningSet set) { - double c1 = 1.0, c2 = 1.0; - - double mach = conditions.getMach(); - double Re; - double Cf; - - if (calcMap == null) - buildCalcMap(configuration); - - Re = conditions.getVelocity() * configuration.getLength() / - conditions.getAtmosphericConditions().getKinematicViscosity(); - - // Calculate the skin friction coefficient (assume non-roughness limited) - if (configuration.getRocket().isPerfectFinish()) { - - // Assume partial laminar layer. Roughness-limitation is checked later. - if (Re < 1e4) { - // Too low, constant - Cf = 1.33e-2; - } else if (Re < 5.39e5) { - // Fully laminar - Cf = 1.328 / MathUtil.safeSqrt(Re); - } else { - // Transitional - Cf = 1.0 / pow2(1.50 * Math.log(Re) - 5.6) - 1700 / Re; - } - - // Compressibility correction - - if (mach < 1.1) { - // Below Re=1e6 no correction - if (Re > 1e6) { - if (Re < 3e6) { - c1 = 1 - 0.1 * pow2(mach) * (Re - 1e6) / 2e6; // transition to turbulent - } else { - c1 = 1 - 0.1 * pow2(mach); - } - } - } - if (mach > 0.9) { - if (Re > 1e6) { - if (Re < 3e6) { - c2 = 1 + (1.0 / Math.pow(1 + 0.045 * pow2(mach), 0.25) - 1) * (Re - 1e6) / 2e6; - } else { - c2 = 1.0 / Math.pow(1 + 0.045 * pow2(mach), 0.25); - } - } - } - - // Applying continuously around Mach 1 - if (mach < 0.9) { - Cf *= c1; - } else if (mach < 1.1) { - Cf *= (c2 * (mach - 0.9) / 0.2 + c1 * (1.1 - mach) / 0.2); - } else { - Cf *= c2; - } - - - } else { - - // Assume fully turbulent. Roughness-limitation is checked later. - if (Re < 1e4) { - // Too low, constant - Cf = 1.48e-2; - } else { - // Turbulent - Cf = 1.0 / pow2(1.50 * Math.log(Re) - 5.6); - } - - // Compressibility correction - - if (mach < 1.1) { - c1 = 1 - 0.1 * pow2(mach); - } - if (mach > 0.9) { - c2 = 1 / Math.pow(1 + 0.15 * pow2(mach), 0.58); - } - // Applying continuously around Mach 1 - if (mach < 0.9) { - Cf *= c1; - } else if (mach < 1.1) { - Cf *= c2 * (mach - 0.9) / 0.2 + c1 * (1.1 - mach) / 0.2; - } else { - Cf *= c2; - } - - } - - // Roughness-limited value correction term - double roughnessCorrection; - if (mach < 0.9) { - roughnessCorrection = 1 - 0.1 * pow2(mach); - } else if (mach > 1.1) { - roughnessCorrection = 1 / (1 + 0.18 * pow2(mach)); - } else { - c1 = 1 - 0.1 * pow2(0.9); - c2 = 1.0 / (1 + 0.18 * pow2(1.1)); - roughnessCorrection = c2 * (mach - 0.9) / 0.2 + c1 * (1.1 - mach) / 0.2; - } - - - - /* - * Calculate the friction drag coefficient. - * - * The body wetted area is summed up and finally corrected with the rocket - * fineness ratio (calculated in the same iteration). The fins are corrected - * for thickness as we go on. - */ - - double finFriction = 0; - double bodyFriction = 0; - double maxR = 0, len = 0; - - double[] roughnessLimited = new double[Finish.values().length]; - Arrays.fill(roughnessLimited, Double.NaN); - - for (RocketComponent c : configuration) { - - // Consider only SymmetricComponents and FinSets: - if (!(c instanceof SymmetricComponent) && - !(c instanceof FinSet)) - continue; - - // Calculate the roughness-limited friction coefficient - Finish finish = ((ExternalComponent) c).getFinish(); - if (Double.isNaN(roughnessLimited[finish.ordinal()])) { - roughnessLimited[finish.ordinal()] = - 0.032 * Math.pow(finish.getRoughnessSize() / configuration.getLength(), 0.2) * - roughnessCorrection; - } - - /* - * Actual Cf is maximum of Cf and the roughness-limited value. - * For perfect finish require additionally that Re > 1e6 - */ - double componentCf; - if (configuration.getRocket().isPerfectFinish()) { - - // For perfect finish require Re > 1e6 - if ((Re > 1.0e6) && (roughnessLimited[finish.ordinal()] > Cf)) { - componentCf = roughnessLimited[finish.ordinal()]; - } else { - componentCf = Cf; - } - - } else { - - // For fully turbulent use simple max - componentCf = Math.max(Cf, roughnessLimited[finish.ordinal()]); - - } - - - - // Calculate the friction drag: - if (c instanceof SymmetricComponent) { - - SymmetricComponent s = (SymmetricComponent) c; - - bodyFriction += componentCf * s.getComponentWetArea(); - - if (map != null) { - // Corrected later - map.get(c).setFrictionCD(componentCf * s.getComponentWetArea() - / conditions.getRefArea()); - } - - double r = Math.max(s.getForeRadius(), s.getAftRadius()); - if (r > maxR) - maxR = r; - len += c.getLength(); - - } else if (c instanceof FinSet) { - - FinSet f = (FinSet) c; - double mac = ((FinSetCalc) calcMap.get(c)).getMACLength(); - double cd = componentCf * (1 + 2 * f.getThickness() / mac) * - 2 * f.getFinCount() * f.getFinArea(); - finFriction += cd; - - if (map != null) { - map.get(c).setFrictionCD(cd / conditions.getRefArea()); - } - - } - - } - // fB may be POSITIVE_INFINITY, but that's ok for us - double fB = (len + 0.0001) / maxR; - double correction = (1 + 1.0 / (2 * fB)); - - // Correct body data in map - if (map != null) { - for (RocketComponent c : map.keySet()) { - if (c instanceof SymmetricComponent) { - map.get(c).setFrictionCD(map.get(c).getFrictionCD() * correction); - } - } - } - - return (finFriction + correction * bodyFriction) / conditions.getRefArea(); - } - - - - private double calculatePressureDrag(Configuration configuration, FlightConditions conditions, - Map map, WarningSet warnings) { - - double stagnation, base, total; - double radius = 0; - - if (calcMap == null) - buildCalcMap(configuration); - - stagnation = calculateStagnationCD(conditions.getMach()); - base = calculateBaseCD(conditions.getMach()); - - total = 0; - for (RocketComponent c : configuration) { - if (!c.isAerodynamic()) - continue; - - // Pressure fore drag - double cd = calcMap.get(c).calculatePressureDragForce(conditions, stagnation, base, - warnings); - total += cd; - - if (map != null) { - map.get(c).setPressureCD(cd); - } - - - // Stagnation drag - if (c instanceof SymmetricComponent) { - SymmetricComponent s = (SymmetricComponent) c; - - if (radius < s.getForeRadius()) { - double area = Math.PI * (pow2(s.getForeRadius()) - pow2(radius)); - cd = stagnation * area / conditions.getRefArea(); - total += cd; - if (map != null) { - map.get(c).setPressureCD(map.get(c).getPressureCD() + cd); - } - } - - radius = s.getAftRadius(); - } - } - - return total; - } - - - private double calculateBaseDrag(Configuration configuration, FlightConditions conditions, - Map map, WarningSet warnings) { - - double base, total; - double radius = 0; - RocketComponent prevComponent = null; - - if (calcMap == null) - buildCalcMap(configuration); - - base = calculateBaseCD(conditions.getMach()); - total = 0; - - for (RocketComponent c : configuration) { - if (!(c instanceof SymmetricComponent)) - continue; - - SymmetricComponent s = (SymmetricComponent) c; - - if (radius > s.getForeRadius()) { - double area = Math.PI * (pow2(radius) - pow2(s.getForeRadius())); - double cd = base * area / conditions.getRefArea(); - total += cd; - if (map != null) { - map.get(prevComponent).setBaseCD(cd); - } - } - - radius = s.getAftRadius(); - prevComponent = c; - } - - if (radius > 0) { - double area = Math.PI * pow2(radius); - double cd = base * area / conditions.getRefArea(); - total += cd; - if (map != null) { - map.get(prevComponent).setBaseCD(cd); - } - } - - return total; - } - - - - public static double calculateStagnationCD(double m) { - double pressure; - if (m <= 1) { - pressure = 1 + pow2(m) / 4 + pow2(pow2(m)) / 40; - } else { - pressure = 1.84 - 0.76 / pow2(m) + 0.166 / pow2(pow2(m)) + 0.035 / pow2(m * m * m); - } - return 0.85 * pressure; - } - - - public static double calculateBaseCD(double m) { - if (m <= 1) { - return 0.12 + 0.13 * m * m; - } else { - return 0.25 / m; - } - } - - - - private static final double[] axialDragPoly1, axialDragPoly2; - static { - PolyInterpolator interpolator; - interpolator = new PolyInterpolator( - new double[] { 0, 17 * Math.PI / 180 }, - new double[] { 0, 17 * Math.PI / 180 } - ); - axialDragPoly1 = interpolator.interpolator(1, 1.3, 0, 0); - - interpolator = new PolyInterpolator( - new double[] { 17 * Math.PI / 180, Math.PI / 2 }, - new double[] { 17 * Math.PI / 180, Math.PI / 2 }, - new double[] { Math.PI / 2 } - ); - axialDragPoly2 = interpolator.interpolator(1.3, 0, 0, 0, 0); - } - - - /** - * Calculate the axial drag from the total drag coefficient. - * - * @param conditions - * @param cd - * @return - */ - private double calculateAxialDrag(FlightConditions conditions, double cd) { - double aoa = MathUtil.clamp(conditions.getAOA(), 0, Math.PI); - double mul; - - // double sinaoa = conditions.getSinAOA(); - // return cd * (1 + Math.min(sinaoa, 0.25)); - - - if (aoa > Math.PI / 2) - aoa = Math.PI - aoa; - if (aoa < 17 * Math.PI / 180) - mul = PolyInterpolator.eval(aoa, axialDragPoly1); - else - mul = PolyInterpolator.eval(aoa, axialDragPoly2); - - if (conditions.getAOA() < Math.PI / 2) - return mul * cd; - else - return -mul * cd; - } - - - private void calculateDampingMoments(Configuration configuration, FlightConditions conditions, - AerodynamicForces total) { - - // Calculate pitch and yaw damping moments - double mul = getDampingMultiplier(configuration, conditions, - conditions.getPitchCenter().x); - double pitch = conditions.getPitchRate(); - double yaw = conditions.getYawRate(); - double vel = conditions.getVelocity(); - - vel = MathUtil.max(vel, 1); - - mul *= 3; // TODO: Higher damping yields much more realistic apogee turn - - total.setPitchDampingMoment(mul * MathUtil.sign(pitch) * pow2(pitch / vel)); - total.setYawDampingMoment(mul * MathUtil.sign(yaw) * pow2(yaw / vel)); - } - - // TODO: MEDIUM: Are the rotation etc. being added correctly? sin/cos theta? - - - private double getDampingMultiplier(Configuration configuration, FlightConditions conditions, - double cgx) { - if (cacheDiameter < 0) { - double area = 0; - cacheLength = 0; - cacheDiameter = 0; - - for (RocketComponent c : configuration) { - if (c instanceof SymmetricComponent) { - SymmetricComponent s = (SymmetricComponent) c; - area += s.getComponentPlanformArea(); - cacheLength += s.getLength(); - } - } - if (cacheLength > 0) - cacheDiameter = area / cacheLength; - } - - double mul; - - // Body - mul = 0.275 * cacheDiameter / (conditions.getRefArea() * conditions.getRefLength()); - mul *= (MathUtil.pow4(cgx) + MathUtil.pow4(cacheLength - cgx)); - - // Fins - // TODO: LOW: This could be optimized a lot... - for (RocketComponent c : configuration) { - if (c instanceof FinSet) { - FinSet f = (FinSet) c; - mul += 0.6 * Math.min(f.getFinCount(), 4) * f.getFinArea() * - MathUtil.pow3(Math.abs(f.toAbsolute(new Coordinate( - ((FinSetCalc) calcMap.get(f)).getMidchordPos()))[0].x - - cgx)) / - (conditions.getRefArea() * conditions.getRefLength()); - } - } - - return mul; - } - - - - //////// The calculator map - - @Override - protected void voidAerodynamicCache() { - super.voidAerodynamicCache(); - - calcMap = null; - cacheDiameter = -1; - cacheLength = -1; - } - - - private void buildCalcMap(Configuration configuration) { - Iterator iterator; - - calcMap = new HashMap(); - - iterator = configuration.getRocket().iterator(); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - - if (!c.isAerodynamic()) - continue; - - calcMap.put(c, (RocketComponentCalc) Reflection.construct(BARROWMAN_PACKAGE, - c, BARROWMAN_SUFFIX, c)); - } - } - - - @Override - public int getModID() { - // Only cached data is stored, return constant mod ID - return 0; - } - - -} diff --git a/core/src/net/sf/openrocket/aerodynamics/FlightConditions.java b/core/src/net/sf/openrocket/aerodynamics/FlightConditions.java deleted file mode 100644 index 0b079e68..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/FlightConditions.java +++ /dev/null @@ -1,467 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import java.util.ArrayList; -import java.util.EventListener; -import java.util.EventObject; -import java.util.List; - -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.StateChangeListener; -import net.sf.openrocket.util.UniqueID; - -/** - * A class defining the momentary flight conditions of a rocket, including - * the angle of attack, lateral wind angle, atmospheric conditions etc. - * - * @author Sampo Niskanen - */ -public class FlightConditions implements Cloneable, ChangeSource, Monitorable { - - private List listenerList = new ArrayList(); - private EventObject event = new EventObject(this); - - - /** Reference length used in calculations. */ - private double refLength = 1.0; - - /** Reference area used in calculations. */ - private double refArea = Math.PI * 0.25; - - - /** Angle of attack. */ - private double aoa = 0; - - /** Sine of the angle of attack. */ - private double sinAOA = 0; - - /** - * The fraction sin(aoa) / aoa. At an AOA of zero this value - * must be one. This value may be used in many cases to avoid checking for - * division by zero. - */ - private double sincAOA = 1.0; - - /** Lateral wind direction. */ - private double theta = 0; - - /** Current Mach speed. */ - private double mach = 0.3; - - /** - * Sqrt(1 - M^2) for M<1 - * Sqrt(M^2 - 1) for M>1 - */ - private double beta = MathUtil.safeSqrt(1 - mach * mach); - - - /** Current roll rate. */ - private double rollRate = 0; - - private double pitchRate = 0; - private double yawRate = 0; - - private Coordinate pitchCenter = Coordinate.NUL; - - - private AtmosphericConditions atmosphericConditions = new AtmosphericConditions(); - - - private int modID; - private int modIDadd = 0; - - - /** - * Sole constructor. The reference length is initialized to the reference length - * of the Configuration, and the reference area accordingly. - * If config is null, then the reference length is set - * to 1 meter. - * - * @param config the configuration of which the reference length is taken. - */ - public FlightConditions(Configuration config) { - if (config != null) - setRefLength(config.getReferenceLength()); - this.modID = UniqueID.next(); - } - - - /** - * Set the reference length from the given configuration. - * @param config the configuration from which to get the reference length. - */ - public void setReference(Configuration config) { - setRefLength(config.getReferenceLength()); - } - - - /** - * Set the reference length and area. - */ - public void setRefLength(double length) { - refLength = length; - - refArea = Math.PI * MathUtil.pow2(length / 2); - fireChangeEvent(); - } - - /** - * Return the reference length. - */ - public double getRefLength() { - return refLength; - } - - /** - * Set the reference area and length. - */ - public void setRefArea(double area) { - refArea = area; - refLength = MathUtil.safeSqrt(area / Math.PI) * 2; - fireChangeEvent(); - } - - /** - * Return the reference area. - */ - public double getRefArea() { - return refArea; - } - - - /** - * Sets the angle of attack. It calculates values also for the methods - * {@link #getSinAOA()} and {@link #getSincAOA()}. - * - * @param aoa the angle of attack. - */ - public void setAOA(double aoa) { - aoa = MathUtil.clamp(aoa, 0, Math.PI); - if (MathUtil.equals(this.aoa, aoa)) - return; - - this.aoa = aoa; - if (aoa < 0.001) { - this.sinAOA = aoa; - this.sincAOA = 1.0; - } else { - this.sinAOA = Math.sin(aoa); - this.sincAOA = sinAOA / aoa; - } - fireChangeEvent(); - } - - - /** - * Sets the angle of attack with the sine. The value sinAOA is assumed - * to be the sine of aoa for cases in which this value is known. - * The AOA must still be specified, as the sine is not unique in the range - * of 0..180 degrees. - * - * @param aoa the angle of attack in radians. - * @param sinAOA the sine of the angle of attack. - */ - public void setAOA(double aoa, double sinAOA) { - aoa = MathUtil.clamp(aoa, 0, Math.PI); - sinAOA = MathUtil.clamp(sinAOA, 0, 1); - if (MathUtil.equals(this.aoa, aoa)) - return; - - assert (Math.abs(Math.sin(aoa) - sinAOA) < 0.0001) : "Illegal sine: aoa=" + aoa + " sinAOA=" + sinAOA; - - this.aoa = aoa; - this.sinAOA = sinAOA; - if (aoa < 0.001) { - this.sincAOA = 1.0; - } else { - this.sincAOA = sinAOA / aoa; - } - fireChangeEvent(); - } - - - /** - * Return the angle of attack. - */ - public double getAOA() { - return aoa; - } - - /** - * Return the sine of the angle of attack. - */ - public double getSinAOA() { - return sinAOA; - } - - /** - * Return the sinc of the angle of attack (sin(AOA) / AOA). This method returns - * one if the angle of attack is zero. - */ - public double getSincAOA() { - return sincAOA; - } - - - /** - * Set the direction of the lateral airflow. - */ - public void setTheta(double theta) { - if (MathUtil.equals(this.theta, theta)) - return; - this.theta = theta; - fireChangeEvent(); - } - - /** - * Return the direction of the lateral airflow. - */ - public double getTheta() { - return theta; - } - - - /** - * Set the current Mach speed. This should be (but is not required to be) in - * reference to the speed of sound of the atmospheric conditions. - */ - public void setMach(double mach) { - mach = Math.max(mach, 0); - if (MathUtil.equals(this.mach, mach)) - return; - - this.mach = mach; - if (mach < 1) - this.beta = MathUtil.safeSqrt(1 - mach * mach); - else - this.beta = MathUtil.safeSqrt(mach * mach - 1); - fireChangeEvent(); - } - - /** - * Return the current Mach speed. - */ - public double getMach() { - return mach; - } - - /** - * Returns the current rocket velocity, calculated from the Mach number and the - * speed of sound. If either of these parameters are changed, the velocity changes - * as well. - * - * @return the velocity of the rocket. - */ - public double getVelocity() { - return mach * atmosphericConditions.getMachSpeed(); - } - - /** - * Sets the Mach speed according to the given velocity and the current speed of sound. - * - * @param velocity the current velocity. - */ - public void setVelocity(double velocity) { - setMach(velocity / atmosphericConditions.getMachSpeed()); - } - - - /** - * Return sqrt(abs(1 - Mach^2)). This is calculated in the setting call and is - * therefore fast. - */ - public double getBeta() { - return beta; - } - - - /** - * Return the current roll rate. - */ - public double getRollRate() { - return rollRate; - } - - - /** - * Set the current roll rate. - */ - public void setRollRate(double rate) { - if (MathUtil.equals(this.rollRate, rate)) - return; - - this.rollRate = rate; - fireChangeEvent(); - } - - - public double getPitchRate() { - return pitchRate; - } - - - public void setPitchRate(double pitchRate) { - if (MathUtil.equals(this.pitchRate, pitchRate)) - return; - this.pitchRate = pitchRate; - fireChangeEvent(); - } - - - public double getYawRate() { - return yawRate; - } - - - public void setYawRate(double yawRate) { - if (MathUtil.equals(this.yawRate, yawRate)) - return; - this.yawRate = yawRate; - fireChangeEvent(); - } - - - - - /** - * @return the pitchCenter - */ - public Coordinate getPitchCenter() { - return pitchCenter; - } - - - /** - * @param pitchCenter the pitchCenter to set - */ - public void setPitchCenter(Coordinate pitchCenter) { - if (this.pitchCenter.equals(pitchCenter)) - return; - this.pitchCenter = pitchCenter; - fireChangeEvent(); - } - - - /** - * Return the current atmospheric conditions. Note that this method returns a - * reference to the {@link AtmosphericConditions} object used by this object. - * Changes made to the object will modify the encapsulated object, but will NOT - * generate change events. - * - * @return the current atmospheric conditions. - */ - public AtmosphericConditions getAtmosphericConditions() { - return atmosphericConditions; - } - - /** - * Set the current atmospheric conditions. This method will fire a change event - * if a change occurs. - */ - public void setAtmosphericConditions(AtmosphericConditions cond) { - if (atmosphericConditions.equals(cond)) - return; - modIDadd += atmosphericConditions.getModID(); - atmosphericConditions = cond; - fireChangeEvent(); - } - - - /** - * Retrieve the modification count of this object. Each time it is modified - * the modification count is increased by one. - * - * @return the number of times this object has been modified since instantiation. - */ - @Override - public int getModID() { - return modID + modIDadd + this.atmosphericConditions.getModID(); - } - - - @Override - public String toString() { - return String.format("FlightConditions[" + - "aoa=%.2f\u00b0," + - "theta=%.2f\u00b0," + - "mach=%.3f," + - "rollRate=%.2f," + - "pitchRate=%.2f," + - "yawRate=%.2f," + - "refLength=%.3f," + - "pitchCenter=" + pitchCenter.toString() + "," + - "atmosphericConditions=" + atmosphericConditions.toString() + - "]", - aoa * 180 / Math.PI, theta * 180 / Math.PI, mach, rollRate, pitchRate, yawRate, refLength); - } - - - /** - * Return a copy of the flight conditions. The copy has no listeners. The - * atmospheric conditions is also cloned. - */ - @Override - public FlightConditions clone() { - try { - FlightConditions cond = (FlightConditions) super.clone(); - cond.listenerList = new ArrayList(); - cond.event = new EventObject(cond); - cond.atmosphericConditions = atmosphericConditions.clone(); - return cond; - } catch (CloneNotSupportedException e) { - throw new BugException("clone not supported!", e); - } - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof FlightConditions)) - return false; - - FlightConditions other = (FlightConditions) obj; - - return (MathUtil.equals(this.refLength, other.refLength) && - MathUtil.equals(this.aoa, other.aoa) && - MathUtil.equals(this.theta, other.theta) && - MathUtil.equals(this.mach, other.mach) && - MathUtil.equals(this.rollRate, other.rollRate) && - MathUtil.equals(this.pitchRate, other.pitchRate) && - MathUtil.equals(this.yawRate, other.yawRate) && - this.pitchCenter.equals(other.pitchCenter) && this.atmosphericConditions.equals(other.atmosphericConditions)); - } - - @Override - public int hashCode() { - return (int) (1000 * (refLength + aoa + theta + mach + rollRate + pitchRate + yawRate)); - } - - - @Override - public void addChangeListener(EventListener listener) { - listenerList.add(0, listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - listenerList.remove(listener); - } - - protected void fireChangeEvent() { - modID = UniqueID.next(); - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] listeners = listenerList.toArray(new EventListener[0]); - for (EventListener l : listeners) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(event); - } - } - } -} diff --git a/core/src/net/sf/openrocket/aerodynamics/Warning.java b/core/src/net/sf/openrocket/aerodynamics/Warning.java deleted file mode 100644 index 363606d7..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/Warning.java +++ /dev/null @@ -1,328 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public abstract class Warning { - - private static final Translator trans = Application.getTranslator(); - - /** - * Return a Warning with the specific text. - */ - public static Warning fromString(String text) { - return new Warning.Other(text); - } - - - /** - * Return true if the other warning should replace - * this warning. The method should return true if the other - * warning indicates a "worse" condition than the current warning. - * - * @param other the warning to compare to - * @return whether this warning should be replaced - */ - public abstract boolean replaceBy(Warning other); - - - /** - * Two Warnings are by default considered equal if they are of - * the same class. Therefore only one instance of a particular warning type - * is stored in a {@link WarningSet}. Subclasses may override this method for - * more specific functionality. - */ - @Override - public boolean equals(Object o) { - return o != null && (o.getClass() == this.getClass()); - } - - /** - * A hashCode method compatible with the equals method. - */ - @Override - public int hashCode() { - return this.getClass().hashCode(); - } - - - - - ///////////// Specific warning classes ///////////// - - - /** - * A Warning indicating a large angle of attack was encountered. - * - * @author Sampo Niskanen - */ - public static class LargeAOA extends Warning { - private double aoa; - - /** - * Sole constructor. The argument is the AOA that caused this warning. - * - * @param aoa the angle of attack that caused this warning - */ - public LargeAOA(double aoa) { - this.aoa = aoa; - } - - @Override - public String toString() { - if (Double.isNaN(aoa)) - //// Large angle of attack encountered. - return trans.get("Warning.LargeAOA.str1"); - //// Large angle of attack encountered ( - return (trans.get("Warning.LargeAOA.str2") + - UnitGroup.UNITS_ANGLE.getDefaultUnit().toString(aoa) + ")."); - } - - @Override - public boolean replaceBy(Warning other) { - if (!(other instanceof LargeAOA)) - return false; - - LargeAOA o = (LargeAOA)other; - if (Double.isNaN(this.aoa)) // If this has value NaN then replace - return true; - return (o.aoa > this.aoa); - } - } - - public static class MissingMotor extends Warning { - - private Motor.Type type = null; - private String manufacturer = null; - private String designation = null; - private String digest = null; - private double diameter = Double.NaN; - private double length = Double.NaN; - private double delay = Double.NaN; - - @Override - public String toString() { - String str = "No motor with designation '" + designation + "'"; - if (manufacturer != null) - str += " for manufacturer '" + manufacturer + "'"; - str += " found."; - return str; - } - - public Motor.Type getType() { - return type; - } - - - public void setType(Motor.Type type) { - this.type = type; - } - - - public String getManufacturer() { - return manufacturer; - } - - - public void setManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - } - - - public String getDesignation() { - return designation; - } - - - public void setDesignation(String designation) { - this.designation = designation; - } - - - public String getDigest() { - return digest; - } - - - public void setDigest(String digest) { - this.digest = digest; - } - - - public double getDiameter() { - return diameter; - } - - - public void setDiameter(double diameter) { - this.diameter = diameter; - } - - - public double getLength() { - return length; - } - - - public void setLength(double length) { - this.length = length; - } - - - public double getDelay() { - return delay; - } - - - public void setDelay(double delay) { - this.delay = delay; - } - - - @Override - public boolean replaceBy(Warning other) { - return false; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - long temp; - temp = Double.doubleToLongBits(delay); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result - + ((designation == null) ? 0 : designation.hashCode()); - temp = Double.doubleToLongBits(diameter); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result - + ((digest == null) ? 0 : digest.hashCode()); - temp = Double.doubleToLongBits(length); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result - + ((manufacturer == null) ? 0 : manufacturer.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - MissingMotor other = (MissingMotor) obj; - if (Double.doubleToLongBits(delay) != Double - .doubleToLongBits(other.delay)) - return false; - if (designation == null) { - if (other.designation != null) - return false; - } else if (!designation.equals(other.designation)) - return false; - if (Double.doubleToLongBits(diameter) != Double - .doubleToLongBits(other.diameter)) - return false; - if (digest == null) { - if (other.digest != null) - return false; - } else if (!digest.equals(other.digest)) - return false; - if (Double.doubleToLongBits(length) != Double - .doubleToLongBits(other.length)) - return false; - if (manufacturer == null) { - if (other.manufacturer != null) - return false; - } else if (!manufacturer.equals(other.manufacturer)) - return false; - if (type != other.type) - return false; - return true; - } - - } - - - /** - * An unspecified warning type. This warning type holds a String - * describing it. Two warnings of this type are considered equal if the strings - * are identical. - * - * @author Sampo Niskanen - */ - public static class Other extends Warning { - private String description; - - public Other(String description) { - this.description = description; - } - - @Override - public String toString() { - return description; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof Other)) - return false; - - Other o = (Other)other; - return (o.description.equals(this.description)); - } - - @Override - public int hashCode() { - return description.hashCode(); - } - - @Override - public boolean replaceBy(Warning other) { - return false; - } - } - - - /** A Warning that the body diameter is discontinuous. */ -////Discontinuity in rocket body diameter. - public static final Warning DISCONTINUITY = - new Other(trans.get("Warning.DISCONTINUITY")); - - /** A Warning that the fins are thick compared to the rocket body. */ -////Thick fins may not be modeled accurately. - public static final Warning THICK_FIN = - new Other(trans.get("Warning.THICK_FIN")); - - /** A Warning that the fins have jagged edges. */ -////Jagged-edged fin predictions may be inaccurate. - public static final Warning JAGGED_EDGED_FIN = - new Other(trans.get("Warning.JAGGED_EDGED_FIN")); - - /** A Warning that simulation listeners have affected the simulation */ -////Listeners modified the flight simulation - public static final Warning LISTENERS_AFFECTED = - new Other(trans.get("Warning.LISTENERS_AFFECTED")); - -////Recovery device opened while motor still burning. - public static final Warning RECOVERY_DEPLOYMENT_WHILE_BURNING = - new Other(trans.get("Warning.RECOVERY_DEPLOYMENT_WHILE_BURNING")); - - - //// Invalid parameter encountered, ignoring. - public static final Warning FILE_INVALID_PARAMETER = - new Other(trans.get("Warning.FILE_INVALID_PARAMETER")); - - public static final Warning PARALLEL_FINS = - new Other(trans.get("Warning.PARALLEL_FINS")); - - public static final Warning SUPERSONIC = - new Other(trans.get("Warning.SUPERSONIC")); - - public static final Warning RECOVERY_LAUNCH_ROD = - new Other(trans.get("Warning.RECOVERY_LAUNCH_ROD")); -} diff --git a/core/src/net/sf/openrocket/aerodynamics/WarningSet.java b/core/src/net/sf/openrocket/aerodynamics/WarningSet.java deleted file mode 100644 index c4e81c62..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/WarningSet.java +++ /dev/null @@ -1,136 +0,0 @@ -package net.sf.openrocket.aerodynamics; - -import java.util.AbstractSet; -import java.util.Iterator; - -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.Mutable; - -/** - * A set that contains multiple Warnings. When adding a - * {@link Warning} to this set, the contents is checked for a warning of the - * same type. If one is found, then the warning left in the set is determined - * by the method {@link Warning#replaceBy(Warning)}. - *

- * A WarningSet can be made immutable by calling {@link #immute()}. - * - * @author Sampo Niskanen - */ -public class WarningSet extends AbstractSet implements Cloneable, Monitorable { - - private ArrayList warnings = new ArrayList(); - - private Mutable mutable = new Mutable(); - - private int modID = 0; - - /** - * Add a Warning to the set. If a warning of the same type - * exists in the set, the warning that is left in the set is defined by the - * method {@link Warning#replaceBy(Warning)}. - * - * @throws IllegalStateException if this warning set has been made immutable. - */ - @Override - public boolean add(Warning w) { - mutable.check(); - - modID++; - int index = warnings.indexOf(w); - - if (index < 0) { - warnings.add(w); - return false; - } - - Warning old = warnings.get(index); - if (old.replaceBy(w)) { - warnings.set(index, w); - } - - return true; - } - - /** - * Add a Warning with the specified text to the set. The Warning object - * is created using the {@link Warning#fromString(String)} method. If a warning of the - * same type exists in the set, the warning that is left in the set is defined by the - * method {@link Warning#replaceBy(Warning)}. - * - * @param s the warning text. - * @throws IllegalStateException if this warning set has been made immutable. - */ - public boolean add(String s) { - mutable.check(); - return add(Warning.fromString(s)); - } - - - @Override - public Iterator iterator() { - final Iterator iterator = warnings.iterator(); - return new Iterator() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Warning next() { - return iterator.next(); - } - - @Override - public void remove() { - mutable.check(); - iterator.remove(); - } - - }; - } - - @Override - public int size() { - return warnings.size(); - } - - - public void immute() { - mutable.immute(); - } - - - @Override - public WarningSet clone() { - try { - - WarningSet newSet = (WarningSet) super.clone(); - newSet.warnings = this.warnings.clone(); - newSet.mutable = this.mutable.clone(); - return newSet; - - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException occurred, report bug!", e); - } - } - - - @Override - public String toString() { - String s = ""; - - for (Warning w : warnings) { - if (s.length() > 0) - s = s + ","; - s += w.toString(); - } - return "WarningSet[" + s + "]"; - } - - @Override - public int getModID() { - return modID; - } -} diff --git a/core/src/net/sf/openrocket/aerodynamics/barrowman/FinSetCalc.java b/core/src/net/sf/openrocket/aerodynamics/barrowman/FinSetCalc.java deleted file mode 100644 index 96abf7a6..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/barrowman/FinSetCalc.java +++ /dev/null @@ -1,776 +0,0 @@ -package net.sf.openrocket.aerodynamics.barrowman; - -import static java.lang.Math.pow; -import static net.sf.openrocket.util.MathUtil.pow2; - -import java.util.Arrays; - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.LinearInterpolator; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.PolyInterpolator; - - -public class FinSetCalc extends RocketComponentCalc { - private static final double STALL_ANGLE = (20 * Math.PI / 180); - - /** Number of divisions in the fin chords. */ - protected static final int DIVISIONS = 48; - - - - protected double macLength = Double.NaN; // MAC length - protected double macLead = Double.NaN; // MAC leading edge position - protected double macSpan = Double.NaN; // MAC spanwise position - protected double finArea = Double.NaN; // Fin area - protected double ar = Double.NaN; // Fin aspect ratio - protected double span = Double.NaN; // Fin span - protected double cosGamma = Double.NaN; // Cosine of midchord sweep angle - protected double cosGammaLead = Double.NaN; // Cosine of leading edge sweep angle - protected double rollSum = Double.NaN; // Roll damping sum term - - protected int interferenceFinCount = -1; // No. of fins in interference - - protected double[] chordLead = new double[DIVISIONS]; - protected double[] chordTrail = new double[DIVISIONS]; - protected double[] chordLength = new double[DIVISIONS]; - - - protected final WarningSet geometryWarnings = new WarningSet(); - - private double[] poly = new double[6]; - - private final double thickness; - private final double bodyRadius; - private final int finCount; - private final double baseRotation; - private final double cantAngle; - private final FinSet.CrossSection crossSection; - - public FinSetCalc(RocketComponent component) { - super(component); - if (!(component instanceof FinSet)) { - throw new IllegalArgumentException("Illegal component type " + component); - } - - FinSet fin = (FinSet) component; - thickness = fin.getThickness(); - bodyRadius = fin.getBodyRadius(); - finCount = fin.getFinCount(); - baseRotation = fin.getBaseRotation(); - cantAngle = fin.getCantAngle(); - span = fin.getSpan(); - finArea = fin.getFinArea(); - crossSection = fin.getCrossSection(); - - calculateFinGeometry(fin); - calculatePoly(); - calculateInterferenceFinCount(fin); - } - - - /* - * Calculates the non-axial forces produced by the fins (normal and side forces, - * pitch, yaw and roll moments, CP position, CNa). - */ - @Override - public void calculateNonaxialForces(FlightConditions conditions, - AerodynamicForces forces, WarningSet warnings) { - - - if (span < 0.001) { - forces.setCm(0); - forces.setCN(0); - forces.setCNa(0); - forces.setCP(Coordinate.NUL); - forces.setCroll(0); - forces.setCrollDamp(0); - forces.setCrollForce(0); - forces.setCside(0); - forces.setCyaw(0); - return; - } - - - // Add warnings (radius/2 == diameter/4) - if (thickness > bodyRadius / 2) { - warnings.add(Warning.THICK_FIN); - } - warnings.addAll(geometryWarnings); - - - - //////// Calculate CNa. ///////// - - // One fin without interference (both sub- and supersonic): - double cna1 = calculateFinCNa1(conditions); - - - - // Multiple fins with fin-fin interference - double cna; - double theta = conditions.getTheta(); - double angle = baseRotation; - - - // Compute basic CNa without interference effects - if (finCount == 1 || finCount == 2) { - // Basic CNa from geometry - double mul = 0; - for (int i = 0; i < finCount; i++) { - mul += MathUtil.pow2(Math.sin(theta - angle)); - angle += 2 * Math.PI / finCount; - } - cna = cna1 * mul; - } else { - // Basic CNa assuming full efficiency - cna = cna1 * finCount / 2.0; - } - - - // Take into account fin-fin interference effects - switch (interferenceFinCount) { - case 1: - case 2: - case 3: - case 4: - // No interference effect - break; - - case 5: - cna *= 0.948; - break; - - case 6: - cna *= 0.913; - break; - - case 7: - cna *= 0.854; - break; - - case 8: - cna *= 0.81; - break; - - default: - // Assume 75% efficiency - cna *= 0.75; - warnings.add(Warning.PARALLEL_FINS); - break; - } - - /* - * Used in 0.9.5 and earlier. Takes into account rotation angle for three - * and four fins, does not take into account interference from other fin sets. - * - switch (fins) { - case 1: - case 2: - // from geometry - double mul = 0; - for (int i=0; i < fins; i++) { - mul += MathUtil.pow2(Math.sin(theta - angle)); - angle += 2 * Math.PI / fins; - } - cna = cna1*mul; - break; - - case 3: - // multiplier 1.5, sinusoidal reduction of 15% - cna = cna1 * 1.5 * (1 - 0.15*pow2(Math.cos(1.5 * (theta-angle)))); - break; - - case 4: - // multiplier 2.0, sinusoidal reduction of 6% - cna = cna1 * 2.0 * (1 - 0.06*pow2(Math.sin(2 * (theta-angle)))); - break; - - case 5: - cna = 2.37 * cna1; - break; - - case 6: - cna = 2.74 * cna1; - break; - - case 7: - cna = 2.99 * cna1; - break; - - case 8: - cna = 3.24 * cna1; - break; - - default: - // Assume N/2 * 3/4 efficiency for more fins - cna = cna1 * fins * 3.0/8.0; - break; - } - */ - - // Body-fin interference effect - double r = bodyRadius; - double tau = r / (span + r); - if (Double.isNaN(tau) || Double.isInfinite(tau)) - tau = 0; - cna *= 1 + tau; // Classical Barrowman - // cna *= pow2(1 + tau); // Barrowman thesis (too optimistic??) - - - - // TODO: LOW: check for fin tip mach cone interference - // (Barrowman thesis pdf-page 40) - - // TODO: LOW: fin-fin mach cone effect, MIL-HDBK page 5-25 - - - - // Calculate CP position - double x = macLead + calculateCPPos(conditions) * macLength; - - - - // Calculate roll forces, reduce forcing above stall angle - - // Without body-fin interference effect: - // forces.CrollForce = fins * (macSpan+r) * cna1 * component.getCantAngle() / - // conditions.getRefLength(); - // With body-fin interference effect: - forces.setCrollForce(finCount * (macSpan + r) * cna1 * (1 + tau) * cantAngle / conditions.getRefLength()); - - - - - if (conditions.getAOA() > STALL_ANGLE) { - // System.out.println("Fin stalling in roll"); - forces.setCrollForce(forces.getCrollForce() * MathUtil.clamp( - 1 - (conditions.getAOA() - STALL_ANGLE) / (STALL_ANGLE / 2), 0, 1)); - } - forces.setCrollDamp(calculateDampingMoment(conditions)); - forces.setCroll(forces.getCrollForce() - forces.getCrollDamp()); - - - - // System.out.printf(component.getName() + ": roll rate:%.3f force:%.3f damp:%.3f " + - // "total:%.3f\n", - // conditions.getRollRate(), forces.CrollForce, forces.CrollDamp, forces.Croll); - - forces.setCNa(cna); - forces.setCN(cna * MathUtil.min(conditions.getAOA(), STALL_ANGLE)); - forces.setCP(new Coordinate(x, 0, 0, cna)); - forces.setCm(forces.getCN() * x / conditions.getRefLength()); - - /* - * TODO: HIGH: Compute actual side force and yaw moment. - * This is not currently performed because it produces strange results for - * stable rockets that have two fins in the front part of the fuselage, - * where the rocket flies at an ever-increasing angle of attack. This may - * be due to incorrect computation of pitch/yaw damping moments. - */ - // if (fins == 1 || fins == 2) { - // forces.Cside = fins * cna1 * Math.cos(theta-angle) * Math.sin(theta-angle); - // forces.Cyaw = fins * forces.Cside * x / conditions.getRefLength(); - // } else { - // forces.Cside = 0; - // forces.Cyaw = 0; - // } - forces.setCside(0); - forces.setCyaw(0); - - - } - - - /** - * Returns the MAC length of the fin. This is required in the friction drag - * computation. - * - * @return the MAC length of the fin. - */ - public double getMACLength() { - return macLength; - } - - public double getMidchordPos() { - return macLead + 0.5 * macLength; - } - - - - /** - * Pre-calculates the fin geometry values. - */ - protected void calculateFinGeometry(FinSet component) { - - span = component.getSpan(); - finArea = component.getFinArea(); - ar = 2 * pow2(span) / finArea; - - Coordinate[] points = component.getFinPoints(); - - // Check for jagged edges - geometryWarnings.clear(); - boolean down = false; - for (int i = 1; i < points.length; i++) { - if ((points[i].y > points[i - 1].y + 0.001) && down) { - geometryWarnings.add(Warning.JAGGED_EDGED_FIN); - break; - } - if (points[i].y < points[i - 1].y - 0.001) { - down = true; - } - } - - - // Calculate the chord lead and trail positions and length - - Arrays.fill(chordLead, Double.POSITIVE_INFINITY); - Arrays.fill(chordTrail, Double.NEGATIVE_INFINITY); - Arrays.fill(chordLength, 0); - - for (int point = 1; point < points.length; point++) { - double x1 = points[point - 1].x; - double y1 = points[point - 1].y; - double x2 = points[point].x; - double y2 = points[point].y; - - if (MathUtil.equals(y1, y2)) - continue; - - int i1 = (int) (y1 * 1.0001 / span * (DIVISIONS - 1)); - int i2 = (int) (y2 * 1.0001 / span * (DIVISIONS - 1)); - i1 = MathUtil.clamp(i1, 0, DIVISIONS - 1); - i2 = MathUtil.clamp(i2, 0, DIVISIONS - 1); - if (i1 > i2) { - int tmp = i2; - i2 = i1; - i1 = tmp; - } - - for (int i = i1; i <= i2; i++) { - // Intersection point (x,y) - double y = i * span / (DIVISIONS - 1); - double x = (y - y2) / (y1 - y2) * x1 + (y1 - y) / (y1 - y2) * x2; - if (x < chordLead[i]) - chordLead[i] = x; - if (x > chordTrail[i]) - chordTrail[i] = x; - - // TODO: LOW: If fin point exactly on chord line, might be counted twice: - if (y1 < y2) { - chordLength[i] -= x; - } else { - chordLength[i] += x; - } - } - } - - // Check and correct any inconsistencies - for (int i = 0; i < DIVISIONS; i++) { - if (Double.isInfinite(chordLead[i]) || Double.isInfinite(chordTrail[i]) || - Double.isNaN(chordLead[i]) || Double.isNaN(chordTrail[i])) { - chordLead[i] = 0; - chordTrail[i] = 0; - } - if (chordLength[i] < 0 || Double.isNaN(chordLength[i])) { - chordLength[i] = 0; - } - if (chordLength[i] > chordTrail[i] - chordLead[i]) { - chordLength[i] = chordTrail[i] - chordLead[i]; - } - } - - - /* Calculate fin properties: - * - * macLength // MAC length - * macLead // MAC leading edge position - * macSpan // MAC spanwise position - * ar // Fin aspect ratio (already set) - * span // Fin span (already set) - */ - macLength = 0; - macLead = 0; - macSpan = 0; - cosGamma = 0; - cosGammaLead = 0; - rollSum = 0; - double area = 0; - double radius = component.getBodyRadius(); - - final double dy = span / (DIVISIONS - 1); - for (int i = 0; i < DIVISIONS; i++) { - double length = chordTrail[i] - chordLead[i]; - double y = i * dy; - - macLength += length * length; - macSpan += y * length; - macLead += chordLead[i] * length; - area += length; - rollSum += chordLength[i] * pow2(radius + y); - - if (i > 0) { - double dx = (chordTrail[i] + chordLead[i]) / 2 - (chordTrail[i - 1] + chordLead[i - 1]) / 2; - cosGamma += dy / MathUtil.hypot(dx, dy); - - dx = chordLead[i] - chordLead[i - 1]; - cosGammaLead += dy / MathUtil.hypot(dx, dy); - } - } - - macLength *= dy; - macSpan *= dy; - macLead *= dy; - area *= dy; - rollSum *= dy; - - macLength /= area; - macSpan /= area; - macLead /= area; - cosGamma /= (DIVISIONS - 1); - cosGammaLead /= (DIVISIONS - 1); - } - - - /////////////// CNa1 calculation //////////////// - - private static final double CNA_SUBSONIC = 0.9; - private static final double CNA_SUPERSONIC = 1.5; - private static final double CNA_SUPERSONIC_B = pow(pow2(CNA_SUPERSONIC) - 1, 1.5); - private static final double GAMMA = 1.4; - private static final LinearInterpolator K1, K2, K3; - private static final PolyInterpolator cnaInterpolator = new PolyInterpolator( - new double[] { CNA_SUBSONIC, CNA_SUPERSONIC }, - new double[] { CNA_SUBSONIC, CNA_SUPERSONIC }, - new double[] { CNA_SUBSONIC } - ); - /* Pre-calculate the values for K1, K2 and K3 */ - static { - // Up to Mach 5 - int n = (int) ((5.0 - CNA_SUPERSONIC) * 10); - double[] x = new double[n]; - double[] k1 = new double[n]; - double[] k2 = new double[n]; - double[] k3 = new double[n]; - for (int i = 0; i < n; i++) { - double M = CNA_SUPERSONIC + i * 0.1; - double beta = MathUtil.safeSqrt(M * M - 1); - x[i] = M; - k1[i] = 2.0 / beta; - k2[i] = ((GAMMA + 1) * pow(M, 4) - 4 * pow2(beta)) / (4 * pow(beta, 4)); - k3[i] = ((GAMMA + 1) * pow(M, 8) + (2 * pow2(GAMMA) - 7 * GAMMA - 5) * pow(M, 6) + - 10 * (GAMMA + 1) * pow(M, 4) + 8) / (6 * pow(beta, 7)); - } - K1 = new LinearInterpolator(x, k1); - K2 = new LinearInterpolator(x, k2); - K3 = new LinearInterpolator(x, k3); - - // System.out.println("K1[m="+CNA_SUPERSONIC+"] = "+k1[0]); - // System.out.println("K2[m="+CNA_SUPERSONIC+"] = "+k2[0]); - // System.out.println("K3[m="+CNA_SUPERSONIC+"] = "+k3[0]); - } - - - protected double calculateFinCNa1(FlightConditions conditions) { - double mach = conditions.getMach(); - double ref = conditions.getRefArea(); - double alpha = MathUtil.min(conditions.getAOA(), - Math.PI - conditions.getAOA(), STALL_ANGLE); - - // Subsonic case - if (mach <= CNA_SUBSONIC) { - return 2 * Math.PI * pow2(span) / (1 + MathUtil.safeSqrt(1 + (1 - pow2(mach)) * - pow2(pow2(span) / (finArea * cosGamma)))) / ref; - } - - // Supersonic case - if (mach >= CNA_SUPERSONIC) { - return finArea * (K1.getValue(mach) + K2.getValue(mach) * alpha + - K3.getValue(mach) * pow2(alpha)) / ref; - } - - // Transonic case, interpolate - double subV, superV; - double subD, superD; - - double sq = MathUtil.safeSqrt(1 + (1 - pow2(CNA_SUBSONIC)) * pow2(span * span / (finArea * cosGamma))); - subV = 2 * Math.PI * pow2(span) / ref / (1 + sq); - subD = 2 * mach * Math.PI * pow(span, 6) / (pow2(finArea * cosGamma) * ref * - sq * pow2(1 + sq)); - - superV = finArea * (K1.getValue(CNA_SUPERSONIC) + K2.getValue(CNA_SUPERSONIC) * alpha + - K3.getValue(CNA_SUPERSONIC) * pow2(alpha)) / ref; - superD = -finArea / ref * 2 * CNA_SUPERSONIC / CNA_SUPERSONIC_B; - - // System.out.println("subV="+subV+" superV="+superV+" subD="+subD+" superD="+superD); - - return cnaInterpolator.interpolate(mach, subV, superV, subD, superD, 0); - } - - - - - private double calculateDampingMoment(FlightConditions conditions) { - double rollRate = conditions.getRollRate(); - - if (Math.abs(rollRate) < 0.1) - return 0; - - double mach = conditions.getMach(); - double absRate = Math.abs(rollRate); - - - /* - * At low speeds and relatively large roll rates (i.e. near apogee) the - * fin tips rotate well above stall angle. In this case sum the chords - * separately. - */ - if (absRate * (bodyRadius + span) / conditions.getVelocity() > 15 * Math.PI / 180) { - double sum = 0; - for (int i = 0; i < DIVISIONS; i++) { - double dist = bodyRadius + span * i / DIVISIONS; - double aoa = Math.min(absRate * dist / conditions.getVelocity(), 15 * Math.PI / 180); - sum += chordLength[i] * dist * aoa; - } - sum = sum * (span / DIVISIONS) * 2 * Math.PI / conditions.getBeta() / - (conditions.getRefArea() * conditions.getRefLength()); - - // System.out.println("SPECIAL: " + - // (MathUtil.sign(rollRate) *component.getFinCount() * sum)); - return MathUtil.sign(rollRate) * finCount * sum; - } - - - - if (mach <= CNA_SUBSONIC) { - // System.out.println("BASIC: "+ - // (component.getFinCount() * 2*Math.PI * rollRate * rollSum / - // (conditions.getRefArea() * conditions.getRefLength() * - // conditions.getVelocity() * conditions.getBeta()))); - - return finCount * 2 * Math.PI * rollRate * rollSum / - (conditions.getRefArea() * conditions.getRefLength() * - conditions.getVelocity() * conditions.getBeta()); - } - if (mach >= CNA_SUPERSONIC) { - - double vel = conditions.getVelocity(); - double k1 = K1.getValue(mach); - double k2 = K2.getValue(mach); - double k3 = K3.getValue(mach); - - double sum = 0; - - for (int i = 0; i < DIVISIONS; i++) { - double y = i * span / (DIVISIONS - 1); - double angle = rollRate * (bodyRadius + y) / vel; - - sum += (k1 * angle + k2 * angle * angle + k3 * angle * angle * angle) - * chordLength[i] * (bodyRadius + y); - } - - return finCount * sum * span / (DIVISIONS - 1) / - (conditions.getRefArea() * conditions.getRefLength()); - } - - // Transonic, do linear interpolation - - FlightConditions cond = conditions.clone(); - cond.setMach(CNA_SUBSONIC - 0.01); - double subsonic = calculateDampingMoment(cond); - cond.setMach(CNA_SUPERSONIC + 0.01); - double supersonic = calculateDampingMoment(cond); - - return subsonic * (CNA_SUPERSONIC - mach) / (CNA_SUPERSONIC - CNA_SUBSONIC) + - supersonic * (mach - CNA_SUBSONIC) / (CNA_SUPERSONIC - CNA_SUBSONIC); - } - - - - - /** - * Return the relative position of the CP along the mean aerodynamic chord. - * Below mach 0.5 it is at the quarter chord, above mach 2 calculated using an - * empirical formula, between these two using an interpolation polynomial. - * - * @param cond Mach speed used - * @return CP position along the MAC - */ - private double calculateCPPos(FlightConditions cond) { - double m = cond.getMach(); - if (m <= 0.5) { - // At subsonic speeds CP at quarter chord - return 0.25; - } - if (m >= 2) { - // At supersonic speeds use empirical formula - double beta = cond.getBeta(); - return (ar * beta - 0.67) / (2 * ar * beta - 1); - } - - // In between use interpolation polynomial - double x = 1.0; - double val = 0; - - for (int i = 0; i < poly.length; i++) { - val += poly[i] * x; - x *= m; - } - - return val; - } - - /** - * Calculate CP position interpolation polynomial coefficients from the - * fin geometry. This is a fifth order polynomial that satisfies - * - * p(0.5)=0.25 - * p'(0.5)=0 - * p(2) = f(2) - * p'(2) = f'(2) - * p''(2) = 0 - * p'''(2) = 0 - * - * where f(M) = (ar*sqrt(M^2-1) - 0.67) / (2*ar*sqrt(M^2-1) - 1). - * - * The values were calculated analytically in Mathematica. The coefficients - * are used as poly[0] + poly[1]*x + poly[2]*x^2 + ... - */ - private void calculatePoly() { - double denom = pow2(1 - 3.4641 * ar); // common denominator - - poly[5] = (-1.58025 * (-0.728769 + ar) * (-0.192105 + ar)) / denom; - poly[4] = (12.8395 * (-0.725688 + ar) * (-0.19292 + ar)) / denom; - poly[3] = (-39.5062 * (-0.72074 + ar) * (-0.194245 + ar)) / denom; - poly[2] = (55.3086 * (-0.711482 + ar) * (-0.196772 + ar)) / denom; - poly[1] = (-31.6049 * (-0.705375 + ar) * (-0.198476 + ar)) / denom; - poly[0] = (9.16049 * (-0.588838 + ar) * (-0.20624 + ar)) / denom; - } - - - // @SuppressWarnings("null") - // public static void main(String arg[]) { - // Rocket rocket = TestRocket.makeRocket(); - // FinSet finset = null; - // - // Iterator iter = rocket.deepIterator(); - // while (iter.hasNext()) { - // RocketComponent c = iter.next(); - // if (c instanceof FinSet) { - // finset = (FinSet)c; - // break; - // } - // } - // - // ((TrapezoidFinSet)finset).setHeight(0.10); - // ((TrapezoidFinSet)finset).setRootChord(0.10); - // ((TrapezoidFinSet)finset).setTipChord(0.10); - // ((TrapezoidFinSet)finset).setSweep(0.0); - // - // - // FinSetCalc calc = new FinSetCalc(finset); - // - // calc.calculateFinGeometry(); - // FlightConditions cond = new FlightConditions(new Configuration(rocket)); - // for (double m=0; m < 3; m+=0.05) { - // cond.setMach(m); - // cond.setAOA(0.0*Math.PI/180); - // double cna = calc.calculateFinCNa1(cond); - // System.out.printf("%5.2f "+cna+"\n", m); - // } - // - // } - - - @Override - public double calculatePressureDragForce(FlightConditions conditions, - double stagnationCD, double baseCD, WarningSet warnings) { - - double mach = conditions.getMach(); - double drag = 0; - - // Pressure fore-drag - if (crossSection == FinSet.CrossSection.AIRFOIL || - crossSection == FinSet.CrossSection.ROUNDED) { - - // Round leading edge - if (mach < 0.9) { - drag = Math.pow(1 - pow2(mach), -0.417) - 1; - } else if (mach < 1) { - drag = 1 - 1.785 * (mach - 0.9); - } else { - drag = 1.214 - 0.502 / pow2(mach) + 0.1095 / pow2(pow2(mach)); - } - - } else if (crossSection == FinSet.CrossSection.SQUARE) { - drag = stagnationCD; - } else { - throw new UnsupportedOperationException("Unsupported fin profile: " + crossSection); - } - - // Slanted leading edge - drag *= pow2(cosGammaLead); - - // Trailing edge drag - if (crossSection == FinSet.CrossSection.SQUARE) { - drag += baseCD; - } else if (crossSection == FinSet.CrossSection.ROUNDED) { - drag += baseCD / 2; - } - // Airfoil assumed to have zero base drag - - - // Scale to correct reference area - drag *= finCount * span * thickness / conditions.getRefArea(); - - return drag; - } - - - private void calculateInterferenceFinCount(FinSet component) { - RocketComponent parent = component.getParent(); - if (parent == null) { - throw new IllegalStateException("fin set without parent component"); - } - - double lead = component.toRelative(Coordinate.NUL, parent)[0].x; - double trail = component.toRelative(new Coordinate(component.getLength()), - parent)[0].x; - - /* - * The counting fails if the fin root chord is very small, in that case assume - * no other fin interference than this fin set. - */ - if (trail - lead < 0.007) { - interferenceFinCount = finCount; - } else { - interferenceFinCount = 0; - for (RocketComponent c : parent.getChildren()) { - if (c instanceof FinSet) { - double finLead = c.toRelative(Coordinate.NUL, parent)[0].x; - double finTrail = c.toRelative(new Coordinate(c.getLength()), parent)[0].x; - - // Compute overlap of the fins - - if ((finLead < trail - 0.005) && (finTrail > lead + 0.005)) { - interferenceFinCount += ((FinSet) c).getFinCount(); - } - } - } - } - if (interferenceFinCount < component.getFinCount()) { - throw new BugException("Counted " + interferenceFinCount + " parallel fins, " + - "when component itself has " + component.getFinCount() + - ", fin points=" + Arrays.toString(component.getFinPoints())); - } - } - -} diff --git a/core/src/net/sf/openrocket/aerodynamics/barrowman/LaunchLugCalc.java b/core/src/net/sf/openrocket/aerodynamics/barrowman/LaunchLugCalc.java deleted file mode 100644 index cd7fea01..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/barrowman/LaunchLugCalc.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.sf.openrocket.aerodynamics.barrowman; - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.MathUtil; - -public class LaunchLugCalc extends RocketComponentCalc { - - private double CDmul; - private double refArea; - - public LaunchLugCalc(RocketComponent component) { - super(component); - - LaunchLug lug = (LaunchLug)component; - double ld = lug.getLength() / (2*lug.getOuterRadius()); - - CDmul = Math.max(1.3 - ld, 1); - refArea = Math.PI * MathUtil.pow2(lug.getOuterRadius()) - - Math.PI * MathUtil.pow2(lug.getInnerRadius()) * Math.max(1 - ld, 0); - } - - @Override - public void calculateNonaxialForces(FlightConditions conditions, - AerodynamicForces forces, WarningSet warnings) { - // Nothing to be done - } - - @Override - public double calculatePressureDragForce(FlightConditions conditions, - double stagnationCD, double baseCD, WarningSet warnings) { - - return CDmul*stagnationCD * refArea / conditions.getRefArea(); - } - -} diff --git a/core/src/net/sf/openrocket/aerodynamics/barrowman/RocketComponentCalc.java b/core/src/net/sf/openrocket/aerodynamics/barrowman/RocketComponentCalc.java deleted file mode 100644 index 71f4ef0c..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/barrowman/RocketComponentCalc.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.aerodynamics.barrowman; - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; - -public abstract class RocketComponentCalc { - - public RocketComponentCalc(RocketComponent component) { - - } - - /** - * Calculate the non-axial forces produced by the component (normal and side forces, - * pitch, yaw and roll moments and CP position). The values are stored in the - * AerodynamicForces object. Additionally the value of CNa is computed - * and stored if possible without large amount of extra calculation, otherwise - * NaN is stored. The CP coordinate is stored in local coordinates and moments are - * computed around the local origin. - * - * @param conditions the flight conditions. - * @param forces the object in which to store the values. - * @param warnings set in which to store possible warnings. - */ - public abstract void calculateNonaxialForces(FlightConditions conditions, - AerodynamicForces forces, WarningSet warnings); - - - /** - * Calculates the pressure drag of the component. This component does NOT include - * the effect of discontinuities in the rocket body. - * - * @param conditions the flight conditions. - * @param stagnationCD the current stagnation drag coefficient - * @param baseCD the current base drag coefficient - * @param warnings set in which to store possible warnings - * @return the pressure drag of the component - */ - public abstract double calculatePressureDragForce(FlightConditions conditions, - double stagnationCD, double baseCD, WarningSet warnings); -} diff --git a/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java b/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java deleted file mode 100644 index 458cbe19..00000000 --- a/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java +++ /dev/null @@ -1,441 +0,0 @@ -package net.sf.openrocket.aerodynamics.barrowman; - -import static net.sf.openrocket.models.atmosphere.AtmosphericConditions.GAMMA; -import static net.sf.openrocket.util.MathUtil.pow2; -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.LinearInterpolator; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.PolyInterpolator; - - - -/** - * Calculates the aerodynamic properties of a SymmetricComponent. - *

- * CP and CNa are calculated by the Barrowman method extended to account for body lift - * by the method presented by Galejs. Supersonic CNa and CP are assumed to be the - * same as the subsonic values. - * - * - * @author Sampo Niskanen - */ -public class SymmetricComponentCalc extends RocketComponentCalc { - - public static final double BODY_LIFT_K = 1.1; - - private final double length; - private final double foreRadius, aftRadius; - private final double fineness; - private final Transition.Shape shape; - private final double param; - private final double frontalArea; - private final double fullVolume; - private final double planformArea, planformCenter; - private final double sinphi; - - public SymmetricComponentCalc(RocketComponent c) { - super(c); - if (!(c instanceof SymmetricComponent)) { - throw new IllegalArgumentException("Illegal component type " + c); - } - SymmetricComponent component = (SymmetricComponent) c; - - - length = component.getLength(); - foreRadius = component.getForeRadius(); - aftRadius = component.getAftRadius(); - - fineness = length / (2 * Math.abs(aftRadius - foreRadius)); - fullVolume = component.getFullVolume(); - planformArea = component.getComponentPlanformArea(); - planformCenter = component.getComponentPlanformCenter(); - - if (component instanceof BodyTube) { - shape = null; - param = 0; - frontalArea = 0; - sinphi = 0; - } else if (component instanceof Transition) { - shape = ((Transition) component).getType(); - param = ((Transition) component).getShapeParameter(); - frontalArea = Math.abs(Math.PI * (foreRadius * foreRadius - aftRadius * aftRadius)); - - double r = component.getRadius(0.99 * length); - sinphi = (aftRadius - r) / MathUtil.hypot(aftRadius - r, 0.01 * length); - } else { - throw new UnsupportedOperationException("Unknown component type " + - component.getComponentName()); - } - } - - - private boolean isTube = false; - private double cnaCache = Double.NaN; - private double cpCache = Double.NaN; - - - /** - * Calculates the non-axial forces produced by the fins (normal and side forces, - * pitch, yaw and roll moments, CP position, CNa). - *

- * This method uses the Barrowman method for CP and CNa calculation and the - * extension presented by Galejs for the effect of body lift. - *

- * The CP and CNa at supersonic speeds are assumed to be the same as those at - * subsonic speeds. - */ - @Override - public void calculateNonaxialForces(FlightConditions conditions, - AerodynamicForces forces, WarningSet warnings) { - - // Pre-calculate and store the results - if (Double.isNaN(cnaCache)) { - final double r0 = foreRadius; - final double r1 = aftRadius; - - if (MathUtil.equals(r0, r1)) { - isTube = true; - cnaCache = 0; - } else { - isTube = false; - - final double A0 = Math.PI * pow2(r0); - final double A1 = Math.PI * pow2(r1); - - cnaCache = 2 * (A1 - A0); - // System.out.println("cnaCache = " + cnaCache); - cpCache = (length * A1 - fullVolume) / (A1 - A0); - } - } - - Coordinate cp; - - // If fore == aft, only body lift is encountered - if (isTube) { - cp = getLiftCP(conditions, warnings); - } else { - cp = new Coordinate(cpCache, 0, 0, cnaCache * conditions.getSincAOA() / - conditions.getRefArea()).average(getLiftCP(conditions, warnings)); - } - - forces.setCP(cp); - forces.setCNa(cp.weight); - forces.setCN(forces.getCNa() * conditions.getAOA()); - forces.setCm(forces.getCN() * cp.x / conditions.getRefLength()); - forces.setCroll(0); - forces.setCrollDamp(0); - forces.setCrollForce(0); - forces.setCside(0); - forces.setCyaw(0); - - - // Add warning on supersonic flight - if (conditions.getMach() > 1.1) { - warnings.add(Warning.SUPERSONIC); - } - - } - - - - /** - * Calculate the body lift effect according to Galejs. - */ - protected Coordinate getLiftCP(FlightConditions conditions, WarningSet warnings) { - - /* - * Without this extra multiplier the rocket may become unstable at apogee - * when turning around, and begin oscillating horizontally. During the flight - * of the rocket this has no effect. It is effective only when AOA > 45 deg - * and the velocity is less than 15 m/s. - * - * TODO: MEDIUM: This causes an anomaly to the flight results with the CP jumping at apogee - */ - double mul = 1; - if ((conditions.getMach() < 0.05) && (conditions.getAOA() > Math.PI / 4)) { - mul = pow2(conditions.getMach() / 0.05); - } - - return new Coordinate(planformCenter, 0, 0, mul * BODY_LIFT_K * planformArea / conditions.getRefArea() * - conditions.getSinAOA() * conditions.getSincAOA()); // sin(aoa)^2 / aoa - } - - - - private LinearInterpolator interpolator = null; - - @Override - public double calculatePressureDragForce(FlightConditions conditions, - double stagnationCD, double baseCD, WarningSet warnings) { - - // Check for simple cases first - if (MathUtil.equals(foreRadius, aftRadius)) - return 0; - - if (length < 0.001) { - if (foreRadius < aftRadius) { - return stagnationCD * frontalArea / conditions.getRefArea(); - } else { - return baseCD * frontalArea / conditions.getRefArea(); - } - } - - - // Boattail drag computed directly from base drag - if (aftRadius < foreRadius) { - if (fineness >= 3) - return 0; - double cd = baseCD * frontalArea / conditions.getRefArea(); - if (fineness <= 1) - return cd; - return cd * (3 - fineness) / 2; - } - - - // All nose cones and shoulders from pre-calculated and interpolating - if (interpolator == null) { - calculateNoseInterpolator(); - } - - return interpolator.getValue(conditions.getMach()) * frontalArea / conditions.getRefArea(); - } - - - - /* - * Experimental values of pressure drag for different nose cone shapes with a fineness - * ratio of 3. The data is taken from 'Collection of Zero-Lift Drag Data on Bodies - * of Revolution from Free-Flight Investigations', NASA TR-R-100, NTRS 19630004995, - * page 16. - * - * This data is extrapolated for other fineness ratios. - */ - - private static final LinearInterpolator ellipsoidInterpolator = new LinearInterpolator( - new double[] { 1.2, 1.25, 1.3, 1.4, 1.6, 2.0, 2.4 }, - new double[] { 0.110, 0.128, 0.140, 0.148, 0.152, 0.159, 0.162 /* constant */} - ); - private static final LinearInterpolator x14Interpolator = new LinearInterpolator( - new double[] { 1.2, 1.3, 1.4, 1.6, 1.8, 2.2, 2.6, 3.0, 3.6 }, - new double[] { 0.140, 0.156, 0.169, 0.192, 0.206, 0.227, 0.241, 0.249, 0.252 } - ); - private static final LinearInterpolator x12Interpolator = new LinearInterpolator( - new double[] { 0.925, 0.95, 1.0, 1.05, 1.1, 1.2, 1.3, 1.7, 2.0 }, - new double[] { 0, 0.014, 0.050, 0.060, 0.059, 0.081, 0.084, 0.085, 0.078 } - ); - private static final LinearInterpolator x34Interpolator = new LinearInterpolator( - new double[] { 0.8, 0.9, 1.0, 1.06, 1.2, 1.4, 1.6, 2.0, 2.8, 3.4 }, - new double[] { 0, 0.015, 0.078, 0.121, 0.110, 0.098, 0.090, 0.084, 0.078, 0.074 } - ); - private static final LinearInterpolator vonKarmanInterpolator = new LinearInterpolator( - new double[] { 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.4, 1.6, 2.0, 3.0 }, - new double[] { 0, 0.010, 0.027, 0.055, 0.070, 0.081, 0.095, 0.097, 0.091, 0.083 } - ); - private static final LinearInterpolator lvHaackInterpolator = new LinearInterpolator( - new double[] { 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.4, 1.6, 2.0 }, - new double[] { 0, 0.010, 0.024, 0.066, 0.084, 0.100, 0.114, 0.117, 0.113 } - ); - private static final LinearInterpolator parabolicInterpolator = new LinearInterpolator( - new double[] { 0.95, 0.975, 1.0, 1.05, 1.1, 1.2, 1.4, 1.7 }, - new double[] { 0, 0.016, 0.041, 0.092, 0.109, 0.119, 0.113, 0.108 } - ); - private static final LinearInterpolator parabolic12Interpolator = new LinearInterpolator( - new double[] { 0.8, 0.9, 0.95, 1.0, 1.05, 1.1, 1.3, 1.5, 1.8 }, - new double[] { 0, 0.016, 0.042, 0.100, 0.126, 0.125, 0.100, 0.090, 0.088 } - ); - private static final LinearInterpolator parabolic34Interpolator = new LinearInterpolator( - new double[] { 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.4, 1.7 }, - new double[] { 0, 0.023, 0.073, 0.098, 0.107, 0.106, 0.089, 0.082 } - ); - private static final LinearInterpolator bluntInterpolator = new LinearInterpolator(); - static { - for (double m = 0; m < 3; m += 0.05) - bluntInterpolator.addPoint(m, BarrowmanCalculator.calculateStagnationCD(m)); - } - - /** - * Calculate the LinearInterpolator 'interpolator'. After this call, if can be used - * to get the pressure drag coefficient at any Mach number. - * - * First, the transonic/supersonic region is computed. For conical and ogive shapes - * this is calculated directly. For other shapes, the values for fineness-ratio 3 - * transitions are taken from the experimental values stored above (for parameterized - * shapes the values are interpolated between the parameter values). These are then - * extrapolated to the current fineness ratio. - * - * Finally, if the first data points in the interpolator are not zero, the subsonic - * region is interpolated in the form Cd = a*M^b + Cd(M=0). - */ - @SuppressWarnings("null") - private void calculateNoseInterpolator() { - LinearInterpolator int1 = null, int2 = null; - double p = 0; - - interpolator = new LinearInterpolator(); - - - /* - * Take into account nose cone shape. Conical and ogive generate the interpolator - * directly. Others store a interpolator for fineness ratio 3 into int1, or - * for parameterized shapes store the bounding fineness ratio 3 interpolators into - * int1 and int2 and set 0 <= p <= 1 according to the bounds. - */ - switch (shape) { - case CONICAL: - interpolator = calculateOgiveNoseInterpolator(0, sinphi); // param==0 -> conical - break; - - case OGIVE: - interpolator = calculateOgiveNoseInterpolator(param, sinphi); - break; - - case ELLIPSOID: - int1 = ellipsoidInterpolator; - break; - - case POWER: - if (param <= 0.25) { - int1 = bluntInterpolator; - int2 = x14Interpolator; - p = param * 4; - } else if (param <= 0.5) { - int1 = x14Interpolator; - int2 = x12Interpolator; - p = (param - 0.25) * 4; - } else if (param <= 0.75) { - int1 = x12Interpolator; - int2 = x34Interpolator; - p = (param - 0.5) * 4; - } else { - int1 = x34Interpolator; - int2 = calculateOgiveNoseInterpolator(0, 1 / MathUtil.safeSqrt(1 + 4 * pow2(fineness))); - p = (param - 0.75) * 4; - } - break; - - case PARABOLIC: - if (param <= 0.5) { - int1 = calculateOgiveNoseInterpolator(0, 1 / MathUtil.safeSqrt(1 + 4 * pow2(fineness))); - int2 = parabolic12Interpolator; - p = param * 2; - } else if (param <= 0.75) { - int1 = parabolic12Interpolator; - int2 = parabolic34Interpolator; - p = (param - 0.5) * 4; - } else { - int1 = parabolic34Interpolator; - int2 = parabolicInterpolator; - p = (param - 0.75) * 4; - } - break; - - case HAACK: - int1 = vonKarmanInterpolator; - int2 = lvHaackInterpolator; - p = param * 3; - break; - - default: - throw new UnsupportedOperationException("Unknown transition shape: " + shape); - } - - if (p < 0 || p > 1.00001) { - throw new BugException("Inconsistent parameter value p=" + p + " shape=" + shape); - } - - - // Check for parameterized shape and interpolate if necessary - if (int2 != null) { - LinearInterpolator int3 = new LinearInterpolator(); - for (double m : int1.getXPoints()) { - int3.addPoint(m, p * int2.getValue(m) + (1 - p) * int1.getValue(m)); - } - for (double m : int2.getXPoints()) { - int3.addPoint(m, p * int2.getValue(m) + (1 - p) * int1.getValue(m)); - } - int1 = int3; - } - - // Extrapolate for fineness ratio if necessary - if (int1 != null) { - double log4 = Math.log(fineness + 1) / Math.log(4); - for (double m : int1.getXPoints()) { - double stag = bluntInterpolator.getValue(m); - interpolator.addPoint(m, stag * Math.pow(int1.getValue(m) / stag, log4)); - } - } - - - /* - * Now the transonic/supersonic region is ok. We still need to interpolate - * the subsonic region, if the values are non-zero. - */ - - double min = interpolator.getXPoints()[0]; - double minValue = interpolator.getValue(min); - if (minValue < 0.001) { - // No interpolation necessary - return; - } - - double cdMach0 = 0.8 * pow2(sinphi); - double minDeriv = (interpolator.getValue(min + 0.01) - minValue) / 0.01; - - // These should not occur, but might cause havoc for the interpolation - if ((cdMach0 >= minValue - 0.01) || (minDeriv <= 0.01)) { - return; - } - - // Cd = a*M^b + cdMach0 - double a = minValue - cdMach0; - double b = minDeriv / a; - - for (double m = 0; m < minValue; m += 0.05) { - interpolator.addPoint(m, a * Math.pow(m, b) + cdMach0); - } - } - - - private static final PolyInterpolator conicalPolyInterpolator = - new PolyInterpolator(new double[] { 1.0, 1.3 }, new double[] { 1.0, 1.3 }); - - private static LinearInterpolator calculateOgiveNoseInterpolator(double param, - double sinphi) { - LinearInterpolator interpolator = new LinearInterpolator(); - - // In the range M = 1 ... 1.3 use polynomial approximation - double cdMach1 = 2.1 * pow2(sinphi) + 0.6019 * sinphi; - - double[] poly = conicalPolyInterpolator.interpolator( - 1.0 * sinphi, cdMach1, - 4 / (GAMMA + 1) * (1 - 0.5 * cdMach1), -1.1341 * sinphi - ); - - // Shape parameter multiplier - double mul = 0.72 * pow2(param - 0.5) + 0.82; - - for (double m = 1; m < 1.3001; m += 0.02) { - interpolator.addPoint(m, mul * PolyInterpolator.eval(m, poly)); - } - - // Above M = 1.3 use direct formula - for (double m = 1.32; m < 4; m += 0.02) { - interpolator.addPoint(m, mul * (2.1 * pow2(sinphi) + 0.5 * sinphi / MathUtil.safeSqrt(m * m - 1))); - } - - return interpolator; - } - - - -} diff --git a/core/src/net/sf/openrocket/arch/SystemInfo.java b/core/src/net/sf/openrocket/arch/SystemInfo.java deleted file mode 100644 index 316f313c..00000000 --- a/core/src/net/sf/openrocket/arch/SystemInfo.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.sf.openrocket.arch; - -import java.io.File; -import java.util.Locale; - -import net.sf.openrocket.util.BugException; - -public class SystemInfo { - - - /** - * Enumeration of supported operating systems. - * - * @see JNLP os and arch Value Collection - * @author Sampo Niskanen - */ - public enum Platform { - WINDOWS, - MAC_OS, - UNIX; - } - - - /** - * Return the current operating system. - * - * @return the operating system of the current system. - */ - public static Platform getPlatform() { - String os = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); - - if (os.indexOf("win") >= 0) { - return Platform.WINDOWS; - } else if (os.indexOf("mac") >= 0) { - return Platform.MAC_OS; - } else { - /* - * Assume UNIX otherwise, e.g. "Linux", "Solaris", "AIX" etc. - */ - return Platform.UNIX; - } - } - - - - - /** - * Return the application data directory of this user. The location depends - * on the current platform. - *

- * The directory will not be created by this method. - * - * @return the application directory for OpenRocket - */ - public static File getUserApplicationDirectory() { - final String homeDir = System.getProperty("user.home"); - final File dir; - - switch (getPlatform()) { - case WINDOWS: - String appdata = System.getenv("APPDATA"); - if (appdata != null) { - dir = new File(appdata, "OpenRocket/"); - } else { - dir = new File(homeDir, "OpenRocket/"); - } - break; - - case MAC_OS: - dir = new File(homeDir, "Library/Application Support/OpenRocket/"); - break; - - case UNIX: - dir = new File(homeDir, ".openrocket/"); - break; - - default: - throw new BugException("Not implemented for platform " + getPlatform()); - } - - return dir; - } - -} diff --git a/core/src/net/sf/openrocket/communication/BugReporter.java b/core/src/net/sf/openrocket/communication/BugReporter.java deleted file mode 100644 index 7f081ba9..00000000 --- a/core/src/net/sf/openrocket/communication/BugReporter.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.sf.openrocket.communication; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; - -import net.sf.openrocket.util.BuildProperties; - -public class BugReporter extends Communicator { - - // Inhibit instantiation - private BugReporter() { - } - - - /** - * Send the provided report to the OpenRocket bug report URL. If the connection - * fails or the server does not respond with the correct response code, an - * exception is thrown. - * - * @param report the report to send. - * @throws IOException if an error occurs while connecting to the server or - * the server responds with a wrong response code. - */ - public static void sendBugReport(String report) throws IOException { - - HttpURLConnection connection = connectionSource.getConnection(BUG_REPORT_URL); - - connection.setConnectTimeout(CONNECTION_TIMEOUT); - connection.setInstanceFollowRedirects(true); - connection.setRequestMethod("POST"); - connection.setUseCaches(false); - connection.setRequestProperty("X-OpenRocket-Version", encode(BuildProperties.getVersion())); - - String post; - post = (VERSION_PARAM + "=" + encode(BuildProperties.getVersion()) - + "&" + BUG_REPORT_PARAM + "=" + encode(report)); - - OutputStreamWriter wr = null; - try { - // Send post information - connection.setDoOutput(true); - wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); - wr.write(post); - wr.flush(); - - if (connection.getResponseCode() != BUG_REPORT_RESPONSE_CODE) { - throw new IOException("Server responded with code " + - connection.getResponseCode() + ", expecting " + BUG_REPORT_RESPONSE_CODE); - } - } finally { - if (wr != null) - wr.close(); - connection.disconnect(); - } - } - -} diff --git a/core/src/net/sf/openrocket/communication/Communicator.java b/core/src/net/sf/openrocket/communication/Communicator.java deleted file mode 100644 index 06c666b7..00000000 --- a/core/src/net/sf/openrocket/communication/Communicator.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.sf.openrocket.communication; - -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URLEncoder; - -import net.sf.openrocket.util.BugException; - -public abstract class Communicator { - - protected static final String BUG_REPORT_URL; - - protected static final String UPDATE_INFO_URL; - - static { - String url; - url = System.getProperty("openrocket.debug.bugurl"); - if (url == null) - url = "http://openrocket.sourceforge.net/actions/reportbug"; - BUG_REPORT_URL = url; - - url = System.getProperty("openrocket.debug.updateurl"); - if (url == null) - url = "http://openrocket.sourceforge.net/actions/updates"; - UPDATE_INFO_URL = url; - } - - - protected static final String VERSION_PARAM = "version"; - - - protected static final String BUG_REPORT_PARAM = "content"; - protected static final int BUG_REPORT_RESPONSE_CODE = HttpURLConnection.HTTP_ACCEPTED; - protected static final int CONNECTION_TIMEOUT = 10000; // in milliseconds - - protected static final int UPDATE_INFO_UPDATE_AVAILABLE = HttpURLConnection.HTTP_OK; - protected static final int UPDATE_INFO_NO_UPDATE_CODE = HttpURLConnection.HTTP_NO_CONTENT; - protected static final String UPDATE_INFO_CONTENT_TYPE = "text/plain"; - - // Limit the number of bytes that can be read from the server - protected static final int MAX_INPUT_BYTES = 20000; - - - protected static ConnectionSource connectionSource = new DefaultConnectionSource(); - - - /** - * Set the source of the network connections. This can be used for unit testing. - * By default the source is a DefaultConnectionSource. - * - * @param source the source of the connections. - */ - public static void setConnectionSource(ConnectionSource source) { - connectionSource = source; - } - - - /** - * URL-encode the specified string in UTF-8 encoding. - * - * @param str the string to encode (null ok) - * @return the encoded string or "null" - */ - public static String encode(String str) { - if (str == null) - return "null"; - try { - return URLEncoder.encode(str, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new BugException("Unsupported encoding UTF-8", e); - } - } - -} diff --git a/core/src/net/sf/openrocket/communication/ConnectionSource.java b/core/src/net/sf/openrocket/communication/ConnectionSource.java deleted file mode 100644 index b5b0fdcc..00000000 --- a/core/src/net/sf/openrocket/communication/ConnectionSource.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.communication; - -import java.io.IOException; -import java.net.HttpURLConnection; - -/** - * A source for network connections. This interface exists to enable unit testing. - * - * @author Sampo Niskanen - */ -public interface ConnectionSource { - - /** - * Return a connection to the specified url. - * @param url the URL to connect to. - * @return the corresponding HttpURLConnection - * @throws IOException if an IOException occurs - */ - public HttpURLConnection getConnection(String url) throws IOException; - -} diff --git a/core/src/net/sf/openrocket/communication/DefaultConnectionSource.java b/core/src/net/sf/openrocket/communication/DefaultConnectionSource.java deleted file mode 100644 index 501c37ac..00000000 --- a/core/src/net/sf/openrocket/communication/DefaultConnectionSource.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.communication; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; - -/** - * Default implementation of ConnectionSource, which simply opens a new - * HttpURLConnection from a URL object. - * - * @author Sampo Niskanen - */ -public class DefaultConnectionSource implements ConnectionSource { - - @Override - public HttpURLConnection getConnection(String urlString) throws IOException { - URL url = new URL(urlString); - return (HttpURLConnection) url.openConnection(); - } - -} diff --git a/core/src/net/sf/openrocket/communication/UpdateInfo.java b/core/src/net/sf/openrocket/communication/UpdateInfo.java deleted file mode 100644 index 78458b81..00000000 --- a/core/src/net/sf/openrocket/communication/UpdateInfo.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.sf.openrocket.communication; - -import java.util.List; - -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.ComparablePair; - -public class UpdateInfo { - - private final String latestVersion; - - private final ArrayList> updates; - - - public UpdateInfo() { - this.latestVersion = BuildProperties.getVersion(); - this.updates = new ArrayList>(); - } - - public UpdateInfo(String version, List> updates) { - this.latestVersion = version; - this.updates = new ArrayList>(updates); - } - - - - /** - * Get the latest OpenRocket version. If it is the current version, then the value - * of {@link BuildProperties#getVersion()} is returned. - * - * @return the latest OpenRocket version. - */ - public String getLatestVersion() { - return latestVersion; - } - - - /** - * Return a list of the new features/updates that are available. The list has a - * priority for each update and a message text. The returned list may be modified. - * - * @return a modifiable list of the updates. - */ - public List> getUpdates() { - return updates.clone(); - } - - @Override - public String toString() { - return "UpdateInfo[version=" + latestVersion + "; updates=" + updates.toString() + "]"; - } - -} diff --git a/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java b/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java deleted file mode 100644 index 799c2a3d..00000000 --- a/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java +++ /dev/null @@ -1,241 +0,0 @@ -package net.sf.openrocket.communication; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Locale; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.ComparablePair; -import net.sf.openrocket.util.LimitedInputStream; - -public class UpdateInfoRetriever { - private static final LogHelper log = Application.getLogger(); - - private UpdateInfoFetcher fetcher = null; - - - /** - * Start an asynchronous task that will fetch information about the latest - * OpenRocket version. This will overwrite any previous fetching operation. - * This call will return immediately. - */ - public void start() { - fetcher = new UpdateInfoFetcher(); - fetcher.setName("UpdateInfoFetcher"); - fetcher.setDaemon(true); - fetcher.start(); - } - - - /** - * Check whether the update info fetching is still in progress. - * - * @return true if the communication is still in progress. - */ - public boolean isRunning() { - if (fetcher == null) { - throw new IllegalStateException("startFetchUpdateInfo() has not been called"); - } - return fetcher.isAlive(); - } - - - /** - * Retrieve the result of the background update info fetcher. This method returns - * the result of the previous call to {@link #start()}. It must be - * called before calling this method. - *

- * This method will return null if the info fetcher is still running or - * if it encountered a problem in communicating with the server. The difference can - * be checked using {@link #isRunning()}. - * - * @return the update result, or null if the fetching is still in progress - * or an error occurred while communicating with the server. - * @throws IllegalStateException if {@link #start()} has not been called. - */ - public UpdateInfo getUpdateInfo() { - if (fetcher == null) { - throw new IllegalStateException("start() has not been called"); - } - return fetcher.info; - } - - - - /** - * Parse the data received from the server. - * - * @param r the Reader from which to read. - * @return an UpdateInfo construct, or null if the data was invalid. - * @throws IOException if an I/O exception occurs. - */ - /* package-private */ - static UpdateInfo parseUpdateInput(Reader r) throws IOException { - BufferedReader reader; - if (r instanceof BufferedReader) { - reader = (BufferedReader) r; - } else { - reader = new BufferedReader(r); - } - - - String version = null; - ArrayList> updates = - new ArrayList>(); - - String str = reader.readLine(); - while (str != null) { - if (str.matches("^Version: *[0-9]+\\.[0-9]+\\.[0-9]+[a-zA-Z0-9.-]* *$")) { - version = str.substring(8).trim(); - } else if (str.matches("^[0-9]+:\\p{Print}+$")) { - int index = str.indexOf(':'); - int value = Integer.parseInt(str.substring(0, index)); - String desc = str.substring(index + 1).trim(); - if (!desc.equals("")) { - updates.add(new ComparablePair(value, desc)); - } - } - // Ignore anything else - str = reader.readLine(); - } - - if (version != null) { - return new UpdateInfo(version, updates); - } else { - return null; - } - } - - - - /** - * An asynchronous task that fetches and parses the update info. - * - * @author Sampo Niskanen - */ - private class UpdateInfoFetcher extends Thread { - - private volatile UpdateInfo info = null; - - @Override - public void run() { - try { - doConnection(); - } catch (IOException e) { - log.info("Fetching update failed: " + e); - return; - } - } - - - private void doConnection() throws IOException { - String url = Communicator.UPDATE_INFO_URL + "?" + Communicator.VERSION_PARAM + "=" - + Communicator.encode(BuildProperties.getVersion()); - - HttpURLConnection connection = Communicator.connectionSource.getConnection(url); - - connection.setConnectTimeout(Communicator.CONNECTION_TIMEOUT); - connection.setInstanceFollowRedirects(true); - connection.setRequestMethod("GET"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setRequestProperty("X-OpenRocket-Version", - Communicator.encode(BuildProperties.getVersion() + " " + BuildProperties.getBuildSource())); - connection.setRequestProperty("X-OpenRocket-ID", - Communicator.encode(Application.getPreferences().getUniqueID())); - connection.setRequestProperty("X-OpenRocket-OS", - Communicator.encode(System.getProperty("os.name") + " " + - System.getProperty("os.arch"))); - connection.setRequestProperty("X-OpenRocket-Java", - Communicator.encode(System.getProperty("java.vendor") + " " + - System.getProperty("java.version"))); - connection.setRequestProperty("X-OpenRocket-Country", - Communicator.encode(System.getProperty("user.country") + " " + - System.getProperty("user.timezone"))); - connection.setRequestProperty("X-OpenRocket-Locale", - Communicator.encode(Locale.getDefault().toString())); - connection.setRequestProperty("X-OpenRocket-CPUs", "" + Runtime.getRuntime().availableProcessors()); - - InputStream is = null; - try { - connection.connect(); - - log.debug("Update response code: " + connection.getResponseCode()); - - if (connection.getResponseCode() == Communicator.UPDATE_INFO_NO_UPDATE_CODE) { - // No updates are available - log.info("No updates available"); - info = new UpdateInfo(); - return; - } - - if (connection.getResponseCode() != Communicator.UPDATE_INFO_UPDATE_AVAILABLE) { - // Error communicating with server - log.warn("Unknown server response code: " + connection.getResponseCode()); - return; - } - - String contentType = connection.getContentType(); - if (contentType == null || - contentType.toLowerCase(Locale.ENGLISH).indexOf(Communicator.UPDATE_INFO_CONTENT_TYPE) < 0) { - // Unknown response type - log.warn("Unknown Content-type received:" + contentType); - return; - } - - // Update is available, parse input - is = connection.getInputStream(); - is = new LimitedInputStream(is, Communicator.MAX_INPUT_BYTES); - String encoding = connection.getContentEncoding(); - if (encoding == null || encoding.equals("")) - encoding = "UTF-8"; - BufferedReader reader = new BufferedReader(new InputStreamReader(is, encoding)); - - String version = null; - ArrayList> updates = - new ArrayList>(); - - String line = reader.readLine(); - while (line != null) { - - if (line.matches("^Version:[a-zA-Z0-9._ -]{1,30}$")) { - version = line.substring(8).trim(); - } else if (line.matches("^[0-9]{1,9}:\\P{Cntrl}{1,300}$")) { - String[] split = line.split(":", 2); - int n = Integer.parseInt(split[0]); - updates.add(new ComparablePair(n, split[1].trim())); - } - // Ignore line otherwise - line = reader.readLine(); - } - - // Check version input - if (version == null || version.length() == 0 || - version.equalsIgnoreCase(BuildProperties.getVersion())) { - // Invalid response - log.warn("Invalid version received, ignoring."); - return; - } - - - info = new UpdateInfo(version, updates); - log.info("Found update: " + info); - } finally { - try { - if (is != null) - is.close(); - connection.disconnect(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } -} diff --git a/core/src/net/sf/openrocket/database/ComponentPresetDao.java b/core/src/net/sf/openrocket/database/ComponentPresetDao.java deleted file mode 100644 index a27a7f5d..00000000 --- a/core/src/net/sf/openrocket/database/ComponentPresetDao.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sf.openrocket.database; - -import java.util.List; - -import net.sf.openrocket.preset.ComponentPreset; - -public interface ComponentPresetDao { - - public List listAll(); - - public void insert( ComponentPreset preset ); - - public List listForType( ComponentPreset.Type type ); - - /** - * Return a list of component presets based on the type. - * All components returned will be of Type type. - * - * @param type - * @param favorite if true, only return the favorites. otherwise return all matching. - * @return - */ - public List listForType( ComponentPreset.Type type, boolean favorite ); - - public List listForTypes( ComponentPreset.Type ... type ); - - public List listForTypes( List types ); - - public void setFavorite( ComponentPreset preset, ComponentPreset.Type type, boolean favorite ); - - public List find( String manufacturer, String partNo ); - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/database/ComponentPresetDatabase.java b/core/src/net/sf/openrocket/database/ComponentPresetDatabase.java deleted file mode 100644 index bb2fae2b..00000000 --- a/core/src/net/sf/openrocket/database/ComponentPresetDatabase.java +++ /dev/null @@ -1,208 +0,0 @@ -package net.sf.openrocket.database; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.startup.Application; - -public abstract class ComponentPresetDatabase extends Database implements ComponentPresetDao { - - private static final LogHelper logger = Application.getLogger(); - - private volatile boolean startedLoading = false; - private volatile boolean endedLoading = false; - private final boolean asynchronous; - - /** Set to true the first time {@link #blockUntilLoaded()} is called. */ - protected volatile boolean inUse = false; - - public ComponentPresetDatabase() { - super(); - this.asynchronous = false; - } - - public ComponentPresetDatabase(boolean asynchronous ) { - super(); - this.asynchronous = asynchronous; - } - - @Override - public List listAll() { - blockUntilLoaded(); - return list; - } - - @Override - public void insert( ComponentPreset preset ) { - list.add(preset); - } - - @Override - public List listForType( ComponentPreset.Type type ) { - blockUntilLoaded(); - if ( type == null ) { - return Collections.emptyList(); - } - - List result = new ArrayList(list.size()/6); - - for( ComponentPreset preset : list ) { - if ( preset.get(ComponentPreset.TYPE).equals(type) ) { - result.add(preset); - } - } - return result; - - } - - /** - * Return a list of component presets based on the type. - * All components returned will be of Type type. - * - * @param type - * @param favorite if true, only return the favorites. otherwise return all matching. - * @return - */ - @Override - public List listForType( ComponentPreset.Type type, boolean favorite ) { - blockUntilLoaded(); - - if ( !favorite ) { - return listForType(type); - } - - List result = new ArrayList(list.size()/6); - - Set favorites = Application.getPreferences().getComponentFavorites(type); - - for( ComponentPreset preset : list ) { - if ( preset.get(ComponentPreset.TYPE).equals(type) && favorites.contains(preset.preferenceKey())) { - result.add(preset); - } - } - return result; - } - - @Override - public List listForTypes( ComponentPreset.Type ... type ) { - blockUntilLoaded(); - - if( type == null || type.length == 0 ) { - return Collections.emptyList(); - } - - if (type.length == 1 ) { - return listForType(type[0]); - } - - List result = new ArrayList(list.size()/6); - - for( ComponentPreset preset : list ) { - ComponentPreset.Type presetType = preset.get(ComponentPreset.TYPE); - typeLoop: for( int i=0; i listForTypes( List types ) { - blockUntilLoaded(); - return listForTypes( (ComponentPreset.Type[]) types.toArray() ); - } - - @Override - public List find(String manufacturer, String partNo) { - blockUntilLoaded(); - List presets = new ArrayList(); - for( ComponentPreset preset : list ) { - if ( preset.getManufacturer().getSimpleName().equals(manufacturer) && preset.getPartNo().equals(partNo) ) { - presets.add(preset); - } - } - return presets; - } - - @Override - public void setFavorite( ComponentPreset preset, ComponentPreset.Type type, boolean favorite ) { - blockUntilLoaded(); - Application.getPreferences().setComponentFavorite( preset, type, favorite ); - this.fireAddEvent(preset); - } - - - /** - * Used for loading the component preset database. This method will be called in a background - * thread to load the presets asynchronously. - */ - protected abstract void load(); - - /** - * Start loading the presets. - * - * @throws IllegalStateException if this method has already been called. - */ - public void startLoading() { - if (startedLoading) { - throw new IllegalStateException("Already called startLoading"); - } - startedLoading = true; - if (asynchronous) { - new LoadingThread().start(); - } else { - load(); - } - synchronized (this) { - endedLoading = true; - this.notifyAll(); - } - } - - /** - * Background thread for loading the presets. - */ - private class LoadingThread extends Thread { - - private LoadingThread() { - this.setName("PresetLoadingThread"); - this.setPriority(MIN_PRIORITY); - } - @Override - public void run() { - load(); - } - } - - /** - * Block the current thread until loading of the presets has been completed. - * - * @throws IllegalStateException if startLoading() has not been called. - */ - public void blockUntilLoaded() { - inUse = true; - if (!startedLoading) { - throw new IllegalStateException("startLoading() has not been called"); - } - if (!endedLoading) { - synchronized (this) { - while (!endedLoading) { - try { - this.wait(); - } catch (InterruptedException e) { - logger.warn("InterruptedException occurred, ignoring", e); - } - } - } - } - } - -} diff --git a/core/src/net/sf/openrocket/database/Database.java b/core/src/net/sf/openrocket/database/Database.java deleted file mode 100644 index d0909cd6..00000000 --- a/core/src/net/sf/openrocket/database/Database.java +++ /dev/null @@ -1,270 +0,0 @@ -package net.sf.openrocket.database; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import net.sf.openrocket.file.Loader; -import net.sf.openrocket.file.iterator.DirectoryIterator; -import net.sf.openrocket.file.iterator.FileIterator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.JarUtil; -import net.sf.openrocket.util.Pair; - - - -/** - * A database set. This class functions as a Set that contains items - * of a specific type. Additionally, the items can be accessed via an index number. - * The elements are always kept in their natural order. - * - * @author Sampo Niskanen - */ -public class Database> extends AbstractSet { - private static final LogHelper log = Application.getLogger(); - - protected final List list = new ArrayList(); - private final ArrayList> listeners = - new ArrayList>(); - private final Loader loader; - - - public Database() { - loader = null; - } - - public Database(Loader loader) { - this.loader = loader; - } - - - - @Override - public Iterator iterator() { - return new DBIterator(); - } - - @Override - public int size() { - return list.size(); - } - - @Override - public boolean add(T element) { - int index; - - index = Collections.binarySearch(list, element); - if (index >= 0) { - // List might contain the element - if (list.contains(element)) { - return false; - } - } else { - index = -(index + 1); - } - list.add(index, element); - fireAddEvent(element); - return true; - } - - - /** - * Get the element with the specified index. - * @param index the index to retrieve. - * @return the element at the index. - */ - public T get(int index) { - return list.get(index); - } - - /** - * Return the index of the given Motor, or -1 if not in the database. - * - * @param m the motor - * @return the index of the motor - */ - public int indexOf(T m) { - return list.indexOf(m); - } - - - public void addDatabaseListener(DatabaseListener listener) { - listeners.add(listener); - } - - public void removeChangeListener(DatabaseListener listener) { - listeners.remove(listener); - } - - - - @SuppressWarnings("unchecked") - protected void fireAddEvent(T element) { - Object[] array = listeners.toArray(); - for (Object l : array) { - ((DatabaseListener) l).elementAdded(element, this); - } - } - - @SuppressWarnings("unchecked") - protected void fireRemoveEvent(T element) { - Object[] array = listeners.toArray(); - for (Object l : array) { - ((DatabaseListener) l).elementRemoved(element, this); - } - } - - - - //////// Directory loading - - public void load( String dir, final String pattern ) throws IOException { - - FileFilter filter = new FileFilter() { - - @Override - public boolean accept(File pathname) { - return pathname.getName().matches(pattern); - } - - }; - - FileIterator files = DirectoryIterator.findDirectory(dir, filter); - while( files != null && files.hasNext() ) { - Pair file = files.next(); - try { - this.addAll(loader.load(file.getV(), file.getU())); - } catch (IOException e) { - log.warn("Error loading file " + file + ": " + e.getMessage(), e); - } - } - if ( files != null ) { - files.close(); - } - } - - /** - * Load all files in a directory to the motor database. Only files with file - * names matching the given pattern (as matched by String.matches(String)) - * are processed. - * - * @param dir the directory to read. - * @param pattern the pattern to match the file names to. - * @throws IOException if an IO error occurs when reading the JAR archive - * (errors reading individual files are printed to stderr). - */ - public void loadDirectory(File dir, final String pattern) throws IOException { - if (loader == null) { - throw new IllegalStateException("no file loader set"); - } - - File[] files = dir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File directory, String name) { - return name.matches(pattern); - } - }); - if (files == null) { - throw new IOException("not a directory: " + dir); - } - for (File file : files) { - try { - this.addAll(loader.load(new FileInputStream(file), file.getName())); - } catch (IOException e) { - log.warn("Error loading file " + file + ": " + e.getMessage(), e); - } - } - } - - - /** - * Read all files in a directory contained in the JAR file that this class belongs to. - * Only files whose names match the given pattern (as matched by - * String.matches(String)) will be read. - * - * @param dir the directory within the JAR archive to read. - * @param pattern the pattern to match the file names to. - * @throws IOException if an IO error occurs when reading the JAR archive - * (errors reading individual files are printed to stderr). - */ - public void loadJarDirectory(String dir, String pattern) throws IOException { - - // Process directory and extension - if (!dir.endsWith("/")) { - dir += "/"; - } - - // Find and open the jar file this class is contained in - File file = JarUtil.getCurrentJarFile(); - JarFile jarFile = new JarFile(file); - - try { - - // Loop through JAR entries searching for files to load - Enumeration entries = jarFile.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - String name = entry.getName(); - if (name.startsWith(dir) && name.matches(pattern)) { - try { - InputStream stream = jarFile.getInputStream(entry); - this.addAll(loader.load(stream, name)); - } catch (IOException e) { - log.warn("Error loading file " + file + ": " + e.getMessage(), e); - } - } - } - - } finally { - jarFile.close(); - } - } - - - - public void load(File file) throws IOException { - if (loader == null) { - throw new IllegalStateException("no file loader set"); - } - this.addAll(loader.load(new FileInputStream(file), file.getName())); - } - - - - /** - * Iterator class implementation that fires changes if remove() is called. - */ - private class DBIterator implements Iterator { - private Iterator iterator = list.iterator(); - private T current = null; - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - current = iterator.next(); - return current; - } - - @Override - public void remove() { - iterator.remove(); - fireRemoveEvent(current); - } - } -} diff --git a/core/src/net/sf/openrocket/database/DatabaseListener.java b/core/src/net/sf/openrocket/database/DatabaseListener.java deleted file mode 100644 index a24b2dde..00000000 --- a/core/src/net/sf/openrocket/database/DatabaseListener.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.sf.openrocket.database; - -public interface DatabaseListener> { - - public void elementAdded(T element, Database source); - - public void elementRemoved(T element, Database source); - -} diff --git a/core/src/net/sf/openrocket/database/Databases.java b/core/src/net/sf/openrocket/database/Databases.java deleted file mode 100644 index 853790bf..00000000 --- a/core/src/net/sf/openrocket/database/Databases.java +++ /dev/null @@ -1,210 +0,0 @@ -package net.sf.openrocket.database; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.material.Material.Type; -import net.sf.openrocket.material.MaterialStorage; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - - -/** - * A class that contains single instances of {@link Database} for specific purposes. - * - * @author Sampo Niskanen - */ -public class Databases { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - /* Static implementations of specific databases: */ - - /** - * A database of bulk materials (with bulk densities). - */ - public static final Database BULK_MATERIAL = new Database(); - /** - * A database of surface materials (with surface densities). - */ - public static final Database SURFACE_MATERIAL = new Database(); - /** - * A database of linear material (with length densities). - */ - public static final Database LINE_MATERIAL = new Database(); - - - - static { - - // Add default materials - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Acrylic", 1190)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Aluminum", 2700)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Balsa", 170)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Basswood", 500)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Birch", 670)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Brass", 8600)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Cardboard", 680)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Carbon fiber", 1780)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Cork", 240)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Depron (XPS)", 40)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Fiberglass", 1850)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Kraft phenolic", 950)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Maple", 755)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Paper (office)", 820)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Pine", 530)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Plywood (birch)", 630)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Polycarbonate (Lexan)", 1200)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Polystyrene", 1050)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "PVC", 1390)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Spruce", 450)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Steel", 7850)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Styrofoam (generic EPS)", 20)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Styrofoam \"Blue foam\" (XPS)", 32)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Titanium", 4500)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Quantum tubing", 1050)); - BULK_MATERIAL.add(newMaterial(Material.Type.BULK, "Blue tube", 1300)); - - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Ripstop nylon", 0.067)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Mylar", 0.021)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Polyethylene (thin)", 0.015)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Polyethylene (heavy)", 0.040)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Silk", 0.060)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Paper (office)", 0.080)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Cellophane", 0.018)); - SURFACE_MATERIAL.add(newMaterial(Material.Type.SURFACE, "Cr\u00eape paper", 0.025)); - - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Thread (heavy-duty)", 0.0003)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Elastic cord (round 2 mm, 1/16 in)", 0.0018)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Elastic cord (flat 6 mm, 1/4 in)", 0.0043)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Elastic cord (flat 12 mm, 1/2 in)", 0.008)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Elastic cord (flat 19 mm, 3/4 in)", 0.0012)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Elastic cord (flat 25 mm, 1 in)", 0.0016)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Braided nylon (2 mm, 1/16 in)", 0.001)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Braided nylon (3 mm, 1/8 in)", 0.0035)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Tubular nylon (11 mm, 7/16 in)", 0.013)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Tubular nylon (14 mm, 9/16 in)", 0.016)); - LINE_MATERIAL.add(newMaterial(Material.Type.LINE, "Tubular nylon (25 mm, 1 in)", 0.029)); - - - // Add user-defined materials - for (Material m : Application.getPreferences().getUserMaterials()) { - switch (m.getType()) { - case LINE: - LINE_MATERIAL.add(m); - break; - - case SURFACE: - SURFACE_MATERIAL.add(m); - break; - - case BULK: - BULK_MATERIAL.add(m); - break; - - default: - log.warn("ERROR: Unknown material type " + m); - } - } - - // Add database storage listener - MaterialStorage listener = new MaterialStorage(); - LINE_MATERIAL.addDatabaseListener(listener); - SURFACE_MATERIAL.addDatabaseListener(listener); - BULK_MATERIAL.addDatabaseListener(listener); - } - - - private static Material newMaterial(Type type, String baseName, double density) { - String name = trans.get("material", baseName); - return Material.newMaterial(type, name, density, false); - } - - - - - /* - * Used just for ensuring initialization of the class. - */ - public static void fakeMethod() { - - } - - /** - * Find a material from the database with the specified type and name. Returns - * null if the specified material could not be found. - *

- * This method will attempt to localize the material name to the current locale, or use - * the provided name if unable to do so. - * - * @param type the material type. - * @param baseName the material base name in the database. - * @return the material, or null if not found. - */ - public static Material findMaterial(Material.Type type, String baseName) { - Database db; - switch (type) { - case BULK: - db = BULK_MATERIAL; - break; - case SURFACE: - db = SURFACE_MATERIAL; - break; - case LINE: - db = LINE_MATERIAL; - break; - default: - throw new IllegalArgumentException("Illegal material type: " + type); - } - - String name = trans.get("material", baseName); - - for (Material m : db) { - if (m.getName().equalsIgnoreCase(name)) { - return m; - } - } - return null; - } - - - /** - * Find a material from the database or return a new user defined material if the specified - * material with the specified density is not found. - *

- * This method will attempt to localize the material name to the current locale, or use - * the provided name if unable to do so. - * - * @param type the material type. - * @param baseName the base name of the material. - * @param density the density of the material. - * @return the material object from the database or a new material. - */ - public static Material findMaterial(Material.Type type, String baseName, double density) { - Database db; - switch (type) { - case BULK: - db = BULK_MATERIAL; - break; - case SURFACE: - db = SURFACE_MATERIAL; - break; - case LINE: - db = LINE_MATERIAL; - break; - default: - throw new IllegalArgumentException("Illegal material type: " + type); - } - - String name = trans.get("material", baseName); - - for (Material m : db) { - if (m.getName().equalsIgnoreCase(name) && MathUtil.equals(m.getDensity(), density)) { - return m; - } - } - return Material.newMaterial(type, name, density, true); - } - -} diff --git a/core/src/net/sf/openrocket/database/MotorDatabase.java b/core/src/net/sf/openrocket/database/MotorDatabase.java deleted file mode 100644 index 0a1e9095..00000000 --- a/core/src/net/sf/openrocket/database/MotorDatabase.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.database; - -import java.util.List; - -import net.sf.openrocket.motor.Motor; - -public interface MotorDatabase { - - /** - * Return all motors in the database matching a search criteria. Any search criteria that - * is null or NaN is ignored. - * - * @param type the motor type, or null. - * @param manufacturer the manufacturer, or null. - * @param designation the designation, or null. - * @param diameter the diameter, or NaN. - * @param length the length, or NaN. - * @return a list of all the matching motors. - */ - public List findMotors(Motor.Type type, - String manufacturer, String designation, double diameter, - double length); - -} diff --git a/core/src/net/sf/openrocket/database/ThrustCurveMotorSet.java b/core/src/net/sf/openrocket/database/ThrustCurveMotorSet.java deleted file mode 100644 index 3bcadad9..00000000 --- a/core/src/net/sf/openrocket/database/ThrustCurveMotorSet.java +++ /dev/null @@ -1,304 +0,0 @@ -package net.sf.openrocket.database; - -import java.text.Collator; -import java.util.Collections; -import java.util.Comparator; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sf.openrocket.motor.DesignationComparator; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.Motor.Type; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.MathUtil; - -public class ThrustCurveMotorSet implements Comparable { - - // Comparators: - private static final Collator COLLATOR = Collator.getInstance(Locale.US); - static { - COLLATOR.setStrength(Collator.PRIMARY); - } - private static final DesignationComparator DESIGNATION_COMPARATOR = new DesignationComparator(); - private static final ThrustCurveMotorComparator comparator = new ThrustCurveMotorComparator(); - - - - private final ArrayList motors = new ArrayList(); - private final Map digestMap = - new IdentityHashMap(); - - private final List delays = new ArrayList(); - - private Manufacturer manufacturer = null; - private String designation = null; - private String simplifiedDesignation = null; - private double diameter = -1; - private double length = -1; - private Motor.Type type = Motor.Type.UNKNOWN; - - - - public void addMotor(ThrustCurveMotor motor) { - - // Check for first insertion - if (motors.isEmpty()) { - manufacturer = motor.getManufacturer(); - designation = motor.getDesignation(); - simplifiedDesignation = simplifyDesignation(designation); - diameter = motor.getDiameter(); - length = motor.getLength(); - } - - // Verify that the motor can be added - if (!matches(motor)) { - throw new IllegalArgumentException("Motor does not match the set:" + - " manufacturer=" + manufacturer + - " designation=" + designation + - " diameter=" + diameter + - " length=" + length + - " set_size=" + motors.size() + - " motor=" + motor); - } - - // Update the type if now known - if (type == Motor.Type.UNKNOWN) { - type = motor.getMotorType(); - // Add "Plugged" option if hybrid - if (type == Motor.Type.HYBRID) { - if (!delays.contains(Motor.PLUGGED)) { - delays.add(Motor.PLUGGED); - } - } - } - - // Change the simplified designation if necessary - if (!designation.equalsIgnoreCase(motor.getDesignation().trim())) { - designation = simplifiedDesignation; - } - - // Add the standard delays - for (double d : motor.getStandardDelays()) { - d = Math.rint(d); - if (!delays.contains(d)) { - delays.add(d); - } - } - Collections.sort(delays); - - - // Check whether to add as new motor or overwrite existing - final String digest = motor.getDigest(); - for (int index = 0; index < motors.size(); index++) { - Motor m = motors.get(index); - - if (digest.equals(digestMap.get(m)) && - motor.getDesignation().equals(m.getDesignation())) { - - // Match found, check which one to keep (or both) based on comment - String newCmt = motor.getDescription().replaceAll("\\s+", " ").trim(); - String oldCmt = m.getDescription().replaceAll("\\s+", " ").trim(); - - if (newCmt.length() == 0 || newCmt.equals(oldCmt)) { - // Do not replace and do not add - return; - } else if (oldCmt.length() == 0) { - // Replace existing motor - motors.set(index, motor); - digestMap.put(motor, digest); - return; - } - // else continue search and add both - - } - } - - // Motor not present, add it - motors.add(motor); - digestMap.put(motor, digest); - Collections.sort(motors, comparator); - - } - - - public boolean matches(ThrustCurveMotor m) { - if (motors.isEmpty()) - return true; - - if (manufacturer != m.getManufacturer()) - return false; - - if (!MathUtil.equals(diameter, m.getDiameter())) - return false; - - if (!MathUtil.equals(length, m.getLength())) - return false; - - if ((type != Type.UNKNOWN) && (m.getMotorType() != Type.UNKNOWN) && - (type != m.getMotorType())) { - return false; - } - - if (!simplifiedDesignation.equals(simplifyDesignation(m.getDesignation()))) - return false; - - return true; - } - - - public List getMotors() { - return motors.clone(); - } - - - public int getMotorCount() { - return motors.size(); - } - - - /** - * Return the standard delays applicable to this motor type. This is a union of - * all the delays of the motors included in this set. - * @return the delays - */ - public List getDelays() { - return Collections.unmodifiableList(delays); - } - - - /** - * Return the manufacturer of this motor type. - * @return the manufacturer - */ - public Manufacturer getManufacturer() { - return manufacturer; - } - - - /** - * Return the designation of this motor type. This is either the exact or simplified - * designation, depending on what motors have been added. - * @return the designation - */ - public String getDesignation() { - return designation; - } - - - /** - * Return the diameter of this motor type. - * @return the diameter - */ - public double getDiameter() { - return diameter; - } - - - /** - * Return the length of this motor type. - * @return the length - */ - public double getLength() { - return length; - } - - - /** - * Return the type of this motor type. If any of the added motors has a type different - * from UNKNOWN, then that type will be returned. - * @return the type - */ - public Motor.Type getType() { - return type; - } - - - - - @Override - public String toString() { - return "ThrustCurveMotorSet[" + manufacturer + " " + designation + - ", type=" + type + ", count=" + motors.size() + "]"; - } - - - - - private static final Pattern SIMPLIFY_PATTERN = Pattern.compile("^[0-9]*[ -]*([A-Z][0-9]+).*"); - - /** - * Simplify a motor designation, if possible. This attempts to reduce the designation - * into a simple letter + number notation for the impulse class and average thrust. - * - * @param str the designation to simplify - * @return the simplified designation, or the string itself if the format was not detected - */ - public static String simplifyDesignation(String str) { - str = str.trim(); - Matcher m = SIMPLIFY_PATTERN.matcher(str); - if (m.matches()) { - return m.group(1); - } else { - return str; - } - } - - - /** - * Comparator for deciding in which order to display matching motors. - */ - private static class ThrustCurveMotorComparator implements Comparator { - - @Override - public int compare(ThrustCurveMotor o1, ThrustCurveMotor o2) { - // 1. Designation - if (!o1.getDesignation().equals(o2.getDesignation())) { - return o1.getDesignation().compareTo(o2.getDesignation()); - } - - // 2. Number of data points (more is better) - if (o1.getTimePoints().length != o2.getTimePoints().length) { - return o2.getTimePoints().length - o1.getTimePoints().length; - } - - // 3. Comment length (longer is better) - return o2.getDescription().length() - o1.getDescription().length(); - } - - } - - - @Override - public int compareTo(ThrustCurveMotorSet other) { - - int value; - - // 1. Manufacturer - value = COLLATOR.compare(this.manufacturer.getDisplayName(), - other.manufacturer.getDisplayName()); - if (value != 0) - return value; - - // 2. Designation - value = DESIGNATION_COMPARATOR.compare(this.designation, other.designation); - if (value != 0) - return value; - - // 3. Diameter - value = (int) ((this.diameter - other.diameter) * 1000000); - if (value != 0) - return value; - - // 4. Length - value = (int) ((this.length - other.length) * 1000000); - return value; - - } - -} diff --git a/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java b/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java deleted file mode 100644 index 9b4c8b18..00000000 --- a/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java +++ /dev/null @@ -1,217 +0,0 @@ -package net.sf.openrocket.database; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; - -/** - * A database containing ThrustCurveMotorSet objects and allowing adding a motor - * to the database. - * - * @author Sampo Niskanen - */ -public abstract class ThrustCurveMotorSetDatabase implements MotorDatabase { - - private static final LogHelper logger = Application.getLogger(); - - protected List motorSets; - - private volatile boolean startedLoading = false; - private volatile boolean endedLoading = false; - private final boolean asynchronous; - - /** Set to true the first time {@link #blockUntilLoaded()} is called. */ - protected volatile boolean inUse = false; - - /** - * Sole constructor. - * - * @param asynchronous whether to load motors asynchronously in a background thread. - */ - public ThrustCurveMotorSetDatabase(boolean asynchronous) { - this.asynchronous = asynchronous; - } - - - /* (non-Javadoc) - * @see net.sf.openrocket.database.ThrustCurveMotorSetDatabaseI#getMotorSets() - */ - public List getMotorSets() { - blockUntilLoaded(); - return motorSets; - } - - - - /* (non-Javadoc) - * @see net.sf.openrocket.database.ThrustCurveMotorSetDatabaseI#findMotors(net.sf.openrocket.motor.Motor.Type, java.lang.String, java.lang.String, double, double) - */ - @Override - public List findMotors(Motor.Type type, String manufacturer, String designation, - double diameter, double length) { - blockUntilLoaded(); - ArrayList results = new ArrayList(); - - for (ThrustCurveMotorSet set : motorSets) { - for (ThrustCurveMotor m : set.getMotors()) { - boolean match = true; - if (type != null && type != set.getType()) - match = false; - else if (manufacturer != null && !m.getManufacturer().matches(manufacturer)) - match = false; - else if (designation != null && !designation.equalsIgnoreCase(m.getDesignation())) - match = false; - else if (!Double.isNaN(diameter) && (Math.abs(diameter - m.getDiameter()) > 0.0015)) - match = false; - else if (!Double.isNaN(length) && (Math.abs(length - m.getLength()) > 0.0015)) - match = false; - - if (match) - results.add(m); - } - } - - return results; - } - - - /** - * Add a motor to the database. If a matching ThrustCurveMototSet is found, - * the motor is added to that set, otherwise a new set is created and added to the - * database. - * - * @param motor the motor to add - */ - protected void addMotor(ThrustCurveMotor motor) { - // Iterate from last to first, as this is most likely to hit early when loading files - for (int i = motorSets.size() - 1; i >= 0; i--) { - ThrustCurveMotorSet set = motorSets.get(i); - if (set.matches(motor)) { - set.addMotor(motor); - return; - } - } - - ThrustCurveMotorSet newSet = new ThrustCurveMotorSet(); - newSet.addMotor(motor); - motorSets.add(newSet); - } - - - - - - /** - * Start loading the motors. If asynchronous - * - * @throws IllegalStateException if this method has already been called. - */ - public void startLoading() { - if (startedLoading) { - throw new IllegalStateException("Already called startLoading"); - } - startedLoading = true; - if (asynchronous) { - new LoadingThread().start(); - } else { - performMotorLoading(); - } - } - - - /** - * Return whether loading the database has ended. - * - * @return whether background loading has ended. - */ - public boolean isLoaded() { - return endedLoading; - } - - - /** - * Mark that this database is in use or a place is waiting for the database to - * become loaded. This can be used in conjunction with {@link #isLoaded()} to load - * the database without blocking. - */ - public void setInUse() { - inUse = true; - } - - - /** - * Block the current thread until loading of the motors has been completed. - * - * @throws IllegalStateException if startLoading() has not been called. - */ - public void blockUntilLoaded() { - inUse = true; - if (!startedLoading) { - throw new IllegalStateException("startLoading() has not been called"); - } - if (!endedLoading) { - synchronized (this) { - while (!endedLoading) { - try { - this.wait(); - } catch (InterruptedException e) { - logger.warn("InterruptedException occurred, ignoring", e); - } - } - } - } - } - - - /** - * Used for loading the motor database. This method will be called in a background - * thread to load the motors asynchronously. This method should call - * {@link #addMotor(ThrustCurveMotor)} to add the motors to the database. - */ - protected abstract void loadMotors(); - - - - /** - * Creates the motor list, calls {@link #loadMotors()}, sorts the list and marks - * the motors as loaded. This method is called either synchronously or from the - * background thread. - */ - private void performMotorLoading() { - motorSets = new ArrayList(); - try { - loadMotors(); - } catch (Exception e) { - logger.error("Loading motors failed", e); - } - Collections.sort(motorSets); - motorSets = Collections.unmodifiableList(motorSets); - synchronized (ThrustCurveMotorSetDatabase.this) { - endedLoading = true; - ThrustCurveMotorSetDatabase.this.notifyAll(); - } - } - - - /** - * Background thread for loading the motors. This creates the motor list, - * calls loadMotors(), sorts the database, makes it unmodifiable, and finally - * marks the database as loaded and notifies any blocked threads. - */ - private class LoadingThread extends Thread { - private LoadingThread() { - this.setName("MotorLoadingThread"); - this.setPriority(MIN_PRIORITY); - } - @Override - public void run() { - performMotorLoading(); - } - } - -} diff --git a/core/src/net/sf/openrocket/document/OpenRocketDocument.java b/core/src/net/sf/openrocket/document/OpenRocketDocument.java deleted file mode 100644 index 12535220..00000000 --- a/core/src/net/sf/openrocket/document/OpenRocketDocument.java +++ /dev/null @@ -1,592 +0,0 @@ -package net.sf.openrocket.document; - -import java.io.File; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import net.sf.openrocket.document.events.DocumentChangeEvent; -import net.sf.openrocket.document.events.DocumentChangeListener; -import net.sf.openrocket.document.events.SimulationChangeEvent; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.simulation.exception.SimulationListenerException; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayList; - -/** - * Class describing an entire OpenRocket document, including a rocket and - * simulations. The document contains: - *

- * - the rocket definition - * - a default Configuration - * - Simulation instances - * - the stored file and file save information - * - undo/redo information - * - * @author Sampo Niskanen - */ -public class OpenRocketDocument implements ComponentChangeListener { - private static final LogHelper log = Application.getLogger(); - - /** - * The minimum number of undo levels that are stored. - */ - public static final int UNDO_LEVELS = 50; - /** - * The margin of the undo levels. After the number of undo levels exceeds - * UNDO_LEVELS by this amount the undo is purged to that length. - */ - public static final int UNDO_MARGIN = 10; - - public static final String SIMULATION_NAME_PREFIX = "Simulation "; - - /** Whether an undo error has already been reported to the user */ - private static boolean undoErrorReported = false; - - private final Rocket rocket; - private final Configuration configuration; - - private final ArrayList simulations = new ArrayList(); - private ArrayList customExpressions = new ArrayList(); - - - /* - * The undo/redo variables and mechanism are documented in doc/undo-redo-flow.* - */ - - /** - * The undo history of the rocket. Whenever a new undo position is created while the - * rocket is in "dirty" state, the rocket is copied here. - */ - private LinkedList undoHistory = new LinkedList(); - private LinkedList undoDescription = new LinkedList(); - - /** - * The position in the undoHistory we are currently at. If modifications have been - * made to the rocket, the rocket is in "dirty" state and this points to the previous - * "clean" state. - */ - private int undoPosition = -1; // Illegal position, init in constructor - - /** - * The description of the next action that modifies this rocket. - */ - private String nextDescription = null; - private String storedDescription = null; - - - private ArrayList undoRedoListeners = new ArrayList(2); - - private File file = null; - private int savedID = -1; - - private final StorageOptions storageOptions = new StorageOptions(); - - - private final List listeners = - new ArrayList(); - - public OpenRocketDocument(Rocket rocket) { - this(rocket.getDefaultConfiguration()); - } - - - private OpenRocketDocument(Configuration configuration) { - this.configuration = configuration; - this.rocket = configuration.getRocket(); - - clearUndo(); - - rocket.addComponentChangeListener(this); - } - - - public void addCustomExpression(CustomExpression expression){ - if (customExpressions.contains(expression)){ - log.user("Could not add custom expression "+expression.getName()+" to document as document alerady has a matching expression."); - } else { - customExpressions.add(expression); - } - } - - public void removeCustomExpression(CustomExpression expression){ - customExpressions.remove(expression); - } - - public List getCustomExpressions(){ - return customExpressions; - } - - /* - * Returns a set of all the flight data types defined or available in any way in the rocket document - */ - public Set getFlightDataTypes(){ - Set allTypes = new LinkedHashSet(); - - // built in - Collections.addAll(allTypes, FlightDataType.ALL_TYPES); - - // custom expressions - for (CustomExpression exp : customExpressions){ - allTypes.add(exp.getType()); - } - - // simulation listeners - for (Simulation sim : simulations){ - for (String className : sim.getSimulationListeners()) { - SimulationListener l = null; - try { - Class c = Class.forName(className); - l = (SimulationListener) c.newInstance(); - - Collections.addAll(allTypes, l.getFlightDataTypes()); - //System.out.println("This document has expression datatype from "+l.getName()); - } catch (Exception e) { - log.error("Could not instantiate listener: " + className); - } - } - } - - // imported data - /// not implemented yet - - - return allTypes; - } - - - public Rocket getRocket() { - return rocket; - } - - - public Configuration getDefaultConfiguration() { - return configuration; - } - - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - - public boolean isSaved() { - return rocket.getModID() == savedID; - } - - public void setSaved(boolean saved) { - if (saved == false) - this.savedID = -1; - else - this.savedID = rocket.getModID(); - } - - /** - * Retrieve the default storage options for this document. - * - * @return the storage options. - */ - public StorageOptions getDefaultStorageOptions() { - return storageOptions; - } - - - - - - public List getSimulations() { - return simulations.clone(); - } - - public int getSimulationCount() { - return simulations.size(); - } - - public Simulation getSimulation(int n) { - return simulations.get(n); - } - - public int getSimulationIndex(Simulation simulation) { - return simulations.indexOf(simulation); - } - - public void addSimulation(Simulation simulation) { - simulations.add(simulation); - fireDocumentChangeEvent(new SimulationChangeEvent(simulation)); - } - - public void addSimulation(Simulation simulation, int n) { - simulations.add(n, simulation); - fireDocumentChangeEvent(new SimulationChangeEvent(simulation)); - } - - public void removeSimulation(Simulation simulation) { - simulations.remove(simulation); - fireDocumentChangeEvent(new SimulationChangeEvent(simulation)); - } - - public Simulation removeSimulation(int n) { - Simulation simulation = simulations.remove(n); - fireDocumentChangeEvent(new SimulationChangeEvent(simulation)); - return simulation; - } - - /** - * Return a unique name suitable for the next simulation. The name begins - * with {@link #SIMULATION_NAME_PREFIX} and has a unique number larger than any - * previous simulation. - * - * @return the new name. - */ - public String getNextSimulationName() { - // Generate unique name for the simulation - int maxValue = 0; - for (Simulation s : simulations) { - String name = s.getName(); - if (name.startsWith(SIMULATION_NAME_PREFIX)) { - try { - maxValue = Math.max(maxValue, - Integer.parseInt(name.substring(SIMULATION_NAME_PREFIX.length()))); - } catch (NumberFormatException ignore) { - } - } - } - return SIMULATION_NAME_PREFIX + (maxValue + 1); - } - - - /** - * Adds an undo point at this position. This method should be called *before* any - * action that is to be undoable. All actions after the call will be undone by a - * single "Undo" action. - *

- * The description should be a short, descriptive string of the actions that will - * follow. This is shown to the user e.g. in the Edit-menu, for example - * "Undo (Modify body tube)". If the actions are not known (in general should not - * be the case!) description may be null. - *

- * If this method is called successively without any change events occurring between the - * calls, only the last call will have any effect. - * - * @param description A short description of the following actions. - */ - public void addUndoPosition(String description) { - - if (storedDescription != null) { - logUndoError("addUndoPosition called while storedDescription=" + storedDescription + - " description=" + description); - } - - // Check whether modifications have been done since last call - if (isCleanState()) { - // No modifications - log.info("Adding undo position '" + description + "' to " + this + ", document was in clean state"); - nextDescription = description; - return; - } - - log.info("Adding undo position '" + description + "' to " + this + ", document is in unclean state"); - - /* - * Modifications have been made to the rocket. We should be at the end of the - * undo history, but check for consistency and try to recover. - */ - if (undoPosition != undoHistory.size() - 1) { - logUndoError("undo position inconsistency"); - } - while (undoPosition < undoHistory.size() - 1) { - undoHistory.removeLast(); - undoDescription.removeLast(); - } - - - // Add the current state to the undo history - undoHistory.add(rocket.copyWithOriginalID()); - undoDescription.add(null); - nextDescription = description; - undoPosition++; - - - // Maintain maximum undo size - if (undoHistory.size() > UNDO_LEVELS + UNDO_MARGIN && undoPosition > UNDO_MARGIN) { - for (int i = 0; i < UNDO_MARGIN; i++) { - undoHistory.removeFirst(); - undoDescription.removeFirst(); - undoPosition--; - } - } - } - - - /** - * Start a time-limited undoable operation. After the operation {@link #stopUndo()} - * must be called, which will restore the previous undo description into effect. - * Only one level of start-stop undo descriptions is supported, i.e. start-stop - * undo cannot be nested, and no other undo operations may be called between - * the start and stop calls. - * - * @param description Description of the following undoable operations. - */ - public void startUndo(String description) { - if (storedDescription != null) { - logUndoError("startUndo called while storedDescription=" + storedDescription + - " description=" + description); - } - log.info("Starting time-limited undoable operation '" + description + "' for " + this); - String store = nextDescription; - addUndoPosition(description); - storedDescription = store; - } - - /** - * End the previous time-limited undoable operation. This must be called after - * {@link #startUndo(String)} has been called before any other undo operations are - * performed. - */ - public void stopUndo() { - log.info("Ending time-limited undoable operation for " + this + " nextDescription=" + - nextDescription + " storedDescription=" + storedDescription); - String stored = storedDescription; - storedDescription = null; - addUndoPosition(stored); - } - - - /** - * Clear the undo history. - */ - public void clearUndo() { - log.info("Clearing undo history of " + this); - undoHistory.clear(); - undoDescription.clear(); - - undoHistory.add(rocket.copyWithOriginalID()); - undoDescription.add(null); - undoPosition = 0; - - fireUndoRedoChangeEvent(); - } - - - @Override - public void componentChanged(ComponentChangeEvent e) { - - if (!e.isUndoChange()) { - if (undoPosition < undoHistory.size() - 1) { - log.info("Rocket changed while in undo history, removing redo information for " + this + - " undoPosition=" + undoPosition + " undoHistory.size=" + undoHistory.size() + - " isClean=" + isCleanState()); - } - // Remove any redo information if available - while (undoPosition < undoHistory.size() - 1) { - undoHistory.removeLast(); - undoDescription.removeLast(); - } - - // Set the latest description - undoDescription.set(undoPosition, nextDescription); - } - - fireUndoRedoChangeEvent(); - } - - - /** - * Return whether undo action is available. - * @return true if undo can be performed - */ - public boolean isUndoAvailable() { - if (undoPosition > 0) - return true; - - return !isCleanState(); - } - - /** - * Return the description of what action would be undone if undo is called. - * @return the description what would be undone, or null if description unavailable. - */ - public String getUndoDescription() { - if (!isUndoAvailable()) - return null; - - if (isCleanState()) { - return undoDescription.get(undoPosition - 1); - } else { - return undoDescription.get(undoPosition); - } - } - - - /** - * Return whether redo action is available. - * @return true if redo can be performed - */ - public boolean isRedoAvailable() { - return undoPosition < undoHistory.size() - 1; - } - - /** - * Return the description of what action would be redone if redo is called. - * @return the description of what would be redone, or null if description unavailable. - */ - public String getRedoDescription() { - if (!isRedoAvailable()) - return null; - - return undoDescription.get(undoPosition); - } - - - /** - * Perform undo operation on the rocket. - */ - public void undo() { - log.info("Performing undo for " + this + " undoPosition=" + undoPosition + - " undoHistory.size=" + undoHistory.size() + " isClean=" + isCleanState()); - if (!isUndoAvailable()) { - logUndoError("Undo not available"); - fireUndoRedoChangeEvent(); - return; - } - if (storedDescription != null) { - logUndoError("undo() called with storedDescription=" + storedDescription); - } - - // Update history position - - if (isCleanState()) { - // We are in a clean state, simply move backwards in history - undoPosition--; - } else { - if (undoPosition != undoHistory.size() - 1) { - logUndoError("undo position inconsistency"); - } - // Modifications have been made, save the state and restore previous state - undoHistory.add(rocket.copyWithOriginalID()); - undoDescription.add(null); - } - - rocket.checkComponentStructure(); - undoHistory.get(undoPosition).checkComponentStructure(); - undoHistory.get(undoPosition).copyWithOriginalID().checkComponentStructure(); - rocket.loadFrom(undoHistory.get(undoPosition).copyWithOriginalID()); - rocket.checkComponentStructure(); - } - - - /** - * Perform redo operation on the rocket. - */ - public void redo() { - log.info("Performing redo for " + this + " undoPosition=" + undoPosition + - " undoHistory.size=" + undoHistory.size() + " isClean=" + isCleanState()); - if (!isRedoAvailable()) { - logUndoError("Redo not available"); - fireUndoRedoChangeEvent(); - return; - } - if (storedDescription != null) { - logUndoError("redo() called with storedDescription=" + storedDescription); - } - - undoPosition++; - - rocket.loadFrom(undoHistory.get(undoPosition).copyWithOriginalID()); - } - - - private boolean isCleanState() { - return rocket.getModID() == undoHistory.get(undoPosition).getModID(); - } - - - /** - * Log a non-fatal undo/redo error or inconsistency. Reports it to the user the first - * time it occurs, but not on subsequent times. Logs automatically the undo system state. - */ - private void logUndoError(String error) { - log.error(1, error + ": this=" + this + " undoPosition=" + undoPosition + - " undoHistory.size=" + undoHistory.size() + " isClean=" + isCleanState() + - " nextDescription=" + nextDescription + " storedDescription=" + storedDescription, - new TraceException()); - - if (!undoErrorReported) { - undoErrorReported = true; - Application.getExceptionHandler().handleErrorCondition("Undo/Redo error: " + error); - } - } - - - - /** - * Return a copy of this document. The rocket is copied with original ID's, the default - * motor configuration ID is maintained and the simulations are copied to the new rocket. - * No undo/redo information or file storage information is maintained. - * - * @return a copy of this document. - */ - public OpenRocketDocument copy() { - Rocket rocketCopy = rocket.copyWithOriginalID(); - OpenRocketDocument documentCopy = new OpenRocketDocument(rocketCopy); - documentCopy.getDefaultConfiguration().setMotorConfigurationID(configuration.getMotorConfigurationID()); - for (Simulation s : simulations) { - documentCopy.addSimulation(s.duplicateSimulation(rocketCopy)); - } - return documentCopy; - } - - - - /////// Listeners - - public void addUndoRedoListener( UndoRedoListener listener ) { - undoRedoListeners.add(listener); - } - - public void removeUndoRedoListener( UndoRedoListener listener ) { - undoRedoListeners.remove(listener); - } - - private void fireUndoRedoChangeEvent() { - UndoRedoListener[] array = undoRedoListeners.toArray(new UndoRedoListener[0]); - for (UndoRedoListener l : array) { - l.setAllValues(); - } - - } - - public void addDocumentChangeListener(DocumentChangeListener listener) { - listeners.add(listener); - } - - public void removeDocumentChangeListener(DocumentChangeListener listener) { - listeners.remove(listener); - } - - protected void fireDocumentChangeEvent(DocumentChangeEvent event) { - DocumentChangeListener[] array = listeners.toArray(new DocumentChangeListener[0]); - for (DocumentChangeListener l : array) { - l.documentChanged(event); - } - } - - - - -} diff --git a/core/src/net/sf/openrocket/document/Simulation.java b/core/src/net/sf/openrocket/document/Simulation.java deleted file mode 100644 index edb093c3..00000000 --- a/core/src/net/sf/openrocket/document/Simulation.java +++ /dev/null @@ -1,467 +0,0 @@ -package net.sf.openrocket.document; - -import java.util.EventListener; -import java.util.EventObject; -import java.util.List; - -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.simulation.BasicEventSimulationEngine; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.RK4SimulationStepper; -import net.sf.openrocket.simulation.SimulationConditions; -import net.sf.openrocket.simulation.SimulationEngine; -import net.sf.openrocket.simulation.SimulationOptions; -import net.sf.openrocket.simulation.SimulationStepper; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.exception.SimulationListenerException; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.SafetyMutex; -import net.sf.openrocket.util.StateChangeListener; - -/** - * A class defining a simulation, its conditions and simulated data. - *

- * This class is not thread-safe and enforces single-threaded access with a - * SafetyMutex. - * - * @author Sampo Niskanen - */ -public class Simulation implements ChangeSource, Cloneable { - private static final LogHelper log = Application.getLogger(); - - public static enum Status { - /** Up-to-date */ - UPTODATE, - - /** Loaded from file, status probably up-to-date */ - LOADED, - - /** Data outdated */ - OUTDATED, - - /** Imported external data */ - EXTERNAL, - - /** Not yet simulated */ - NOT_SIMULATED - } - - private SafetyMutex mutex = SafetyMutex.newInstance(); - - private final Rocket rocket; - - private String name = ""; - - private Status status = Status.NOT_SIMULATED; - - /** The conditions to use */ - // TODO: HIGH: Change to use actual conditions class?? - private SimulationOptions options; - - private ArrayList simulationListeners = new ArrayList(); - - private final Class simulationEngineClass = BasicEventSimulationEngine.class; - private Class simulationStepperClass = RK4SimulationStepper.class; - private Class aerodynamicCalculatorClass = BarrowmanCalculator.class; - private Class massCalculatorClass = BasicMassCalculator.class; - - /** Listeners for this object */ - private List listeners = new ArrayList(); - - - /** The conditions actually used in the previous simulation, or null */ - private SimulationOptions simulatedConditions = null; - private String simulatedMotors = null; - private FlightData simulatedData = null; - private int simulatedRocketID = -1; - - - /** - * Create a new simulation for the rocket. Parent document should also be provided. - * The initial motor configuration is taken from the default rocket configuration. - * - * @param rocket the rocket associated with the simulation. - */ - public Simulation(Rocket rocket) { - this.rocket = rocket; - this.status = Status.NOT_SIMULATED; - - options = new SimulationOptions(rocket); - options.setMotorConfigurationID( - rocket.getDefaultConfiguration().getMotorConfigurationID()); - options.addChangeListener(new ConditionListener()); - } - - - public Simulation(Rocket rocket, Status status, String name, SimulationOptions options, - List listeners, FlightData data) { - - if (rocket == null) - throw new IllegalArgumentException("rocket cannot be null"); - if (status == null) - throw new IllegalArgumentException("status cannot be null"); - if (name == null) - throw new IllegalArgumentException("name cannot be null"); - if (options == null) - throw new IllegalArgumentException("options cannot be null"); - - this.rocket = rocket; - - if (status == Status.UPTODATE) { - this.status = Status.LOADED; - } else if (data == null) { - this.status = Status.NOT_SIMULATED; - } else { - this.status = status; - } - - this.name = name; - - this.options = options; - options.addChangeListener(new ConditionListener()); - - if (listeners != null) { - this.simulationListeners.addAll(listeners); - } - - - if (data != null && this.status != Status.NOT_SIMULATED) { - simulatedData = data; - if (this.status == Status.LOADED) { - simulatedConditions = options.clone(); - simulatedRocketID = rocket.getModID(); - } - } - - } - - /** - * Return the rocket associated with this simulation. - * - * @return the rocket. - */ - public Rocket getRocket() { - mutex.verify(); - return rocket; - } - - - /** - * Return a newly created Configuration for this simulation. The configuration - * has the motor ID set and all stages active. - * - * @return a newly created Configuration of the launch conditions. - */ - public Configuration getConfiguration() { - mutex.verify(); - Configuration c = new Configuration(rocket); - c.setMotorConfigurationID(options.getMotorConfigurationID()); - c.setAllStages(); - return c; - } - - /** - * Returns the simulation options attached to this simulation. The options - * may be modified freely, and the status of the simulation will change to reflect - * the changes. - * - * @return the simulation conditions. - */ - public SimulationOptions getOptions() { - mutex.verify(); - return options; - } - - - /** - * Get the list of simulation listeners. The returned list is the one used by - * this object; changes to it will reflect changes in the simulation. - * - * @return the actual list of simulation listeners. - */ - public List getSimulationListeners() { - mutex.verify(); - return simulationListeners; - } - - - /** - * Return the user-defined name of the simulation. - * - * @return the name for the simulation. - */ - public String getName() { - mutex.verify(); - return name; - } - - /** - * Set the user-defined name of the simulation. Setting the name to - * null yields an empty name. - * - * @param name the name of the simulation. - */ - public void setName(String name) { - mutex.lock("setName"); - try { - if (this.name.equals(name)) - return; - - if (name == null) - this.name = ""; - else - this.name = name; - - fireChangeEvent(); - } finally { - mutex.unlock("setName"); - } - } - - - /** - * Returns the status of this simulation. This method examines whether the - * simulation has been outdated and returns {@link Status#OUTDATED} accordingly. - * - * @return the status - * @see Status - */ - public Status getStatus() { - mutex.verify(); - - if (status == Status.UPTODATE || status == Status.LOADED) { - if (rocket.getFunctionalModID() != simulatedRocketID || - !options.equals(simulatedConditions)) - return Status.OUTDATED; - } - - return status; - } - - - - /** - * Simulate the flight. - * - * @param additionalListeners additional simulation listeners (those defined by the simulation are used in any case) - * @throws SimulationException if a problem occurs during simulation - */ - public void simulate(SimulationListener... additionalListeners) - throws SimulationException { - mutex.lock("simulate"); - try { - - if (this.status == Status.EXTERNAL) { - throw new SimulationException("Cannot simulate imported simulation."); - } - - SimulationEngine simulator; - - try { - simulator = simulationEngineClass.newInstance(); - } catch (InstantiationException e) { - throw new IllegalStateException("Cannot instantiate simulator.", e); - } catch (IllegalAccessException e) { - throw new IllegalStateException("Cannot access simulator instance?! BUG!", e); - } - - SimulationConditions simulationConditions = options.toSimulationConditions(); - simulationConditions.setSimulation(this); - for (SimulationListener l : additionalListeners) { - simulationConditions.getSimulationListenerList().add(l); - } - - for (String className : simulationListeners) { - SimulationListener l = null; - try { - Class c = Class.forName(className); - l = (SimulationListener) c.newInstance(); - } catch (Exception e) { - throw new SimulationListenerException("Could not instantiate listener of " + - "class: " + className, e); - } - simulationConditions.getSimulationListenerList().add(l); - } - - long t1, t2; - log.debug("Simulation: calling simulator"); - t1 = System.currentTimeMillis(); - simulatedData = simulator.simulate(simulationConditions); - t2 = System.currentTimeMillis(); - log.debug("Simulation: returning from simulator, simulation took " + (t2 - t1) + "ms"); - - // Set simulated info after simulation, will not be set in case of exception - simulatedConditions = options.clone(); - simulatedMotors = getConfiguration().getMotorConfigurationDescription(); - simulatedRocketID = rocket.getFunctionalModID(); - - status = Status.UPTODATE; - fireChangeEvent(); - } finally { - mutex.unlock("simulate"); - } - } - - - /** - * Return the conditions used in the previous simulation, or null - * if this simulation has not been run. - * - * @return the conditions used in the previous simulation, or null. - */ - public SimulationOptions getSimulatedConditions() { - mutex.verify(); - return simulatedConditions; - } - - /** - * Return the warnings generated in the previous simulation, or - * null if this simulation has not been run. This is the same - * warning set as contained in the FlightData object. - * - * @return the warnings during the previous simulation, or null. - * @see FlightData#getWarningSet() - */ - public WarningSet getSimulatedWarnings() { - mutex.verify(); - if (simulatedData == null) - return null; - return simulatedData.getWarningSet(); - } - - - /** - * Return a string describing the motor configuration of the previous simulation, - * or null if this simulation has not been run. - * - * @return a description of the motor configuration of the previous simulation, or - * null. - * @see Rocket#getMotorConfigurationNameOrDescription(String) - */ - public String getSimulatedMotorDescription() { - mutex.verify(); - return simulatedMotors; - } - - /** - * Return the flight data of the previous simulation, or null if - * this simulation has not been run. - * - * @return the flight data of the previous simulation, or null. - */ - public FlightData getSimulatedData() { - mutex.verify(); - return simulatedData; - } - - - - /** - * Returns a copy of this simulation suitable for cut/copy/paste operations. - * The rocket refers to the same instance as the original simulation. - * This excludes any simulated data. - * - * @return a copy of this simulation and its conditions. - */ - public Simulation copy() { - mutex.lock("copy"); - try { - - Simulation copy = (Simulation) super.clone(); - - copy.mutex = SafetyMutex.newInstance(); - copy.status = Status.NOT_SIMULATED; - copy.options = this.options.clone(); - copy.simulationListeners = this.simulationListeners.clone(); - copy.listeners = new ArrayList(); - copy.simulatedConditions = null; - copy.simulatedMotors = null; - copy.simulatedData = null; - copy.simulatedRocketID = -1; - - return copy; - - } catch (CloneNotSupportedException e) { - throw new BugException("Clone not supported, BUG", e); - } finally { - mutex.unlock("copy"); - } - } - - - /** - * Create a duplicate of this simulation with the specified rocket. The new - * simulation is in non-simulated state. - * - * @param newRocket the rocket for the new simulation. - * @return a new simulation with the same conditions and properties. - */ - public Simulation duplicateSimulation(Rocket newRocket) { - mutex.lock("duplicateSimulation"); - try { - Simulation copy = new Simulation(newRocket); - - copy.name = this.name; - copy.options.copyFrom(this.options); - copy.simulationListeners = this.simulationListeners.clone(); - copy.simulationStepperClass = this.simulationStepperClass; - copy.aerodynamicCalculatorClass = this.aerodynamicCalculatorClass; - - return copy; - } finally { - mutex.unlock("duplicateSimulation"); - } - } - - - - @Override - public void addChangeListener(EventListener listener) { - mutex.verify(); - listeners.add(listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - mutex.verify(); - listeners.remove(listener); - } - - protected void fireChangeEvent() { - EventObject e = new EventObject(this); - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] ls = listeners.toArray(new EventListener[0]); - for (EventListener l : ls) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(e); - } - } - } - - - - - private class ConditionListener implements StateChangeListener { - - private Status oldStatus = null; - - @Override - public void stateChanged(EventObject e) { - if (getStatus() != oldStatus) { - oldStatus = getStatus(); - fireChangeEvent(); - } - } - } -} diff --git a/core/src/net/sf/openrocket/document/StorageOptions.java b/core/src/net/sf/openrocket/document/StorageOptions.java deleted file mode 100644 index 7e1186c1..00000000 --- a/core/src/net/sf/openrocket/document/StorageOptions.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.sf.openrocket.document; - -import net.sf.openrocket.util.BugException; - -public class StorageOptions implements Cloneable { - - public static final double SIMULATION_DATA_NONE = Double.POSITIVE_INFINITY; - public static final double SIMULATION_DATA_ALL = 0; - - private boolean compressionEnabled = true; - - private double simulationTimeSkip = SIMULATION_DATA_NONE; - - private boolean explicitlySet = false; - - - public boolean isCompressionEnabled() { - return compressionEnabled; - } - - public void setCompressionEnabled(boolean compression) { - this.compressionEnabled = compression; - } - - public double getSimulationTimeSkip() { - return simulationTimeSkip; - } - - public void setSimulationTimeSkip(double simulationTimeSkip) { - this.simulationTimeSkip = simulationTimeSkip; - } - - - - public boolean isExplicitlySet() { - return explicitlySet; - } - - public void setExplicitlySet(boolean explicitlySet) { - this.explicitlySet = explicitlySet; - } - - - - @Override - public StorageOptions clone() { - try { - return (StorageOptions)super.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException?!?", e); - } - } -} diff --git a/core/src/net/sf/openrocket/document/UndoRedoListener.java b/core/src/net/sf/openrocket/document/UndoRedoListener.java deleted file mode 100644 index 4f7900ea..00000000 --- a/core/src/net/sf/openrocket/document/UndoRedoListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.sf.openrocket.document; - -import java.util.EventListener; - -public interface UndoRedoListener extends EventListener { - - public void setAllValues(); -} diff --git a/core/src/net/sf/openrocket/document/events/DocumentChangeEvent.java b/core/src/net/sf/openrocket/document/events/DocumentChangeEvent.java deleted file mode 100644 index cb5662f2..00000000 --- a/core/src/net/sf/openrocket/document/events/DocumentChangeEvent.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.sf.openrocket.document.events; - -import java.util.EventObject; - -public class DocumentChangeEvent extends EventObject { - - public DocumentChangeEvent(Object source) { - super(source); - } - -} diff --git a/core/src/net/sf/openrocket/document/events/DocumentChangeListener.java b/core/src/net/sf/openrocket/document/events/DocumentChangeListener.java deleted file mode 100644 index 01d3dbd4..00000000 --- a/core/src/net/sf/openrocket/document/events/DocumentChangeListener.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.sf.openrocket.document.events; - -public interface DocumentChangeListener { - - public void documentChanged(DocumentChangeEvent event); - -} diff --git a/core/src/net/sf/openrocket/document/events/SimulationChangeEvent.java b/core/src/net/sf/openrocket/document/events/SimulationChangeEvent.java deleted file mode 100644 index 56ed6d1a..00000000 --- a/core/src/net/sf/openrocket/document/events/SimulationChangeEvent.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.sf.openrocket.document.events; - - -public class SimulationChangeEvent extends DocumentChangeEvent { - - public SimulationChangeEvent(Object source) { - super(source); - } - -} diff --git a/core/src/net/sf/openrocket/file/AbstractRocketLoader.java b/core/src/net/sf/openrocket/file/AbstractRocketLoader.java deleted file mode 100644 index f0c7464d..00000000 --- a/core/src/net/sf/openrocket/file/AbstractRocketLoader.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.file; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.OpenRocketDocument; - - -public abstract class AbstractRocketLoader implements RocketLoader { - protected final WarningSet warnings = new WarningSet(); - - - /** - * Loads a rocket from the specified File object. - */ - @Override - public final OpenRocketDocument load(File source, MotorFinder motorFinder) throws RocketLoadException { - warnings.clear(); - InputStream stream = null; - - try { - - stream = new BufferedInputStream(new FileInputStream(source)); - return load(stream, motorFinder); - - } catch (FileNotFoundException e) { - throw new RocketLoadException("File not found: " + source); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - /** - * Loads a rocket from the specified InputStream. - */ - @Override - public final OpenRocketDocument load(InputStream source, MotorFinder motorFinder) throws RocketLoadException { - warnings.clear(); - - try { - return loadFromStream(source, motorFinder); - } catch (RocketLoadException e) { - throw e; - } catch (IOException e) { - throw new RocketLoadException("I/O error: " + e.getMessage(), e); - } - } - - - - /** - * This method is called by the default implementations of #load(File) - * and load(InputStream) to load the rocket. - * - * @throws RocketLoadException if an error occurs during loading. - */ - protected abstract OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws IOException, - RocketLoadException; - - - - @Override - public final WarningSet getWarnings() { - return warnings; - } -} diff --git a/core/src/net/sf/openrocket/file/CSVExport.java b/core/src/net/sf/openrocket/file/CSVExport.java deleted file mode 100644 index f2e8d6fc..00000000 --- a/core/src/net/sf/openrocket/file/CSVExport.java +++ /dev/null @@ -1,213 +0,0 @@ -package net.sf.openrocket.file; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.util.TextUtil; - -public class CSVExport { - - /** - * Exports the specified flight data branch into a CSV file. - * - * @param stream the stream to write to. - * @param simulation the simulation being exported. - * @param branch the branch to export. - * @param fields the fields to export (in appropriate order). - * @param units the units of the fields. - * @param fieldSeparator the field separator string. - * @param commentStarter the comment starting character(s). - * @param simulationComments whether to output general simulation comments. - * @param fieldComments whether to output field comments. - * @param eventComments whether to output comments for the flight events. - * @throws IOException if an I/O exception occurs. - */ - public static void exportCSV(OutputStream stream, Simulation simulation, - FlightDataBranch branch, FlightDataType[] fields, Unit[] units, - String fieldSeparator, String commentStarter, boolean simulationComments, - boolean fieldComments, boolean eventComments) throws IOException { - - if (fields.length != units.length) { - throw new IllegalArgumentException("fields and units lengths must be equal " + - "(" + fields.length + " vs " + units.length + ")"); - } - - - PrintWriter writer = null; - try { - - writer = new PrintWriter(stream); - - // Write the initial comments - if (simulationComments) { - writeSimulationComments(writer, simulation, branch, fields, commentStarter); - } - - if (simulationComments && fieldComments) { - writer.println(commentStarter); - } - - if (fieldComments) { - writer.print(commentStarter + " "); - for (int i = 0; i < fields.length; i++) { - writer.print(fields[i].getName() + " (" + units[i].getUnit() + ")"); - if (i < fields.length - 1) { - writer.print(fieldSeparator); - } - } - writer.println(); - } - - writeData(writer, branch, fields, units, fieldSeparator, - eventComments, commentStarter); - - - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - private static void writeData(PrintWriter writer, FlightDataBranch branch, - FlightDataType[] fields, Unit[] units, String fieldSeparator, boolean eventComments, - String commentStarter) { - - // Number of data points - int n = branch.getLength(); - - // Flight events in occurrance order - List events = branch.getEvents(); - Collections.sort(events); - int eventPosition = 0; - - // List of field values - List> fieldValues = new ArrayList>(); - for (FlightDataType t : fields) { - fieldValues.add(branch.get(t)); - } - - // Time variable - List time = branch.get(FlightDataType.TYPE_TIME); - if (eventComments && time == null) { - // If time information is not available, print events at beginning of file - for (FlightEvent e : events) { - printEvent(writer, e, commentStarter); - } - eventPosition = events.size(); - } - - - // Loop over all data points - for (int pos = 0; pos < n; pos++) { - - // Check for events to store - if (eventComments && time != null) { - double t = time.get(pos); - - while ((eventPosition < events.size()) && - (events.get(eventPosition).getTime() <= t)) { - printEvent(writer, events.get(eventPosition), commentStarter); - eventPosition++; - } - } - - // Store CSV line - for (int i = 0; i < fields.length; i++) { - double value = fieldValues.get(i).get(pos); - writer.print(TextUtil.doubleToString(units[i].toUnit(value))); - if (i < fields.length - 1) { - writer.print(fieldSeparator); - } - } - writer.println(); - - } - - // Store any remaining events - if (eventComments && time != null) { - while (eventPosition < events.size()) { - printEvent(writer, events.get(eventPosition), commentStarter); - eventPosition++; - } - } - - } - - - private static void printEvent(PrintWriter writer, FlightEvent e, - String commentStarter) { - writer.println(commentStarter + " Event " + e.getType().name() + - " occurred at t=" + TextUtil.doubleToString(e.getTime()) + " seconds"); - } - - private static void writeSimulationComments(PrintWriter writer, - Simulation simulation, FlightDataBranch branch, FlightDataType[] fields, - String commentStarter) { - - String line; - - line = simulation.getName(); - - FlightData data = simulation.getSimulatedData(); - - switch (simulation.getStatus()) { - case UPTODATE: - line += " (Up to date)"; - break; - - case LOADED: - line += " (Data loaded from a file)"; - break; - - case OUTDATED: - line += " (Data is out of date)"; - break; - - case EXTERNAL: - line += " (Imported data)"; - break; - - case NOT_SIMULATED: - line += " (Not simulated yet)"; - break; - } - - writer.println(commentStarter + " " + line); - - - writer.println(commentStarter + " " + branch.getLength() + " data points written for " - + fields.length + " variables."); - - - if (data == null) { - writer.println(commentStarter + " No simulation data available."); - return; - } - WarningSet warnings = data.getWarningSet(); - - if (!warnings.isEmpty()) { - writer.println(commentStarter + " Simulation warnings:"); - for (Warning w : warnings) { - writer.println(commentStarter + " " + w.toString()); - } - } - } - -} diff --git a/core/src/net/sf/openrocket/file/DatabaseMotorFinder.java b/core/src/net/sf/openrocket/file/DatabaseMotorFinder.java deleted file mode 100644 index 0232bbd1..00000000 --- a/core/src/net/sf/openrocket/file/DatabaseMotorFinder.java +++ /dev/null @@ -1,95 +0,0 @@ -package net.sf.openrocket.file; - -import java.util.List; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.Motor.Type; -import net.sf.openrocket.startup.Application; - -/** - * A MotorFinder implementation that searches the thrust curve motor database - * for a motor. - * - * @author Sampo Niskanen - */ -public class DatabaseMotorFinder implements MotorFinder { - - /** - * Do something when a missing motor is found. - * - * This implementation adds a Warning.MissingMotor to the warning set and returns null. - * - * Override this function to change the behavior. - * - * @return The Motor which will be put in the Rocket. - */ - protected Motor handleMissingMotor(Type type, String manufacturer, String designation, double diameter, double length, String digest, WarningSet warnings) { - Warning.MissingMotor mmw = new Warning.MissingMotor(); - mmw.setDesignation(designation); - mmw.setDigest(digest); - mmw.setDiameter(diameter); - mmw.setLength(length); - mmw.setManufacturer(manufacturer); - mmw.setType(type); - warnings.add(mmw); - return null; - } - - @Override - public Motor findMotor(Type type, String manufacturer, String designation, double diameter, double length, String digest, WarningSet warnings) { - - if (designation == null) { - warnings.add(Warning.fromString("No motor specified, ignoring.")); - return null; - } - - List motors = Application.getMotorSetDatabase().findMotors(type, manufacturer, designation, diameter, length); - - // No motors - if (motors.size() == 0) { - return handleMissingMotor(type, manufacturer, designation, diameter, length, digest, warnings); - } - - // One motor - if (motors.size() == 1) { - Motor m = motors.get(0); - if (digest != null && !digest.equals(m.getDigest())) { - String str = "Motor with designation '" + designation + "'"; - if (manufacturer != null) - str += " for manufacturer '" + manufacturer + "'"; - str += " has differing thrust curve than the original."; - warnings.add(str); - } - return m; - } - - // Multiple motors, check digest for which one to use - if (digest != null) { - - // Check for motor with correct digest - for (Motor m : motors) { - if (digest.equals(m.getDigest())) { - return m; - } - } - String str = "Motor with designation '" + designation + "'"; - if (manufacturer != null) - str += " for manufacturer '" + manufacturer + "'"; - str += " has differing thrust curve than the original."; - warnings.add(str); - - } else { - - String str = "Multiple motors with designation '" + designation + "'"; - if (manufacturer != null) - str += " for manufacturer '" + manufacturer + "'"; - str += " found, one chosen arbitrarily."; - warnings.add(str); - - } - return motors.get(0); - } - -} diff --git a/core/src/net/sf/openrocket/file/DatabaseMotorFinderWithMissingMotors.java b/core/src/net/sf/openrocket/file/DatabaseMotorFinderWithMissingMotors.java deleted file mode 100644 index 5270151b..00000000 --- a/core/src/net/sf/openrocket/file/DatabaseMotorFinderWithMissingMotors.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.file; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.Motor.Type; -import net.sf.openrocket.motor.ThrustCurveMotorPlaceholder; - -public class DatabaseMotorFinderWithMissingMotors extends DatabaseMotorFinder -implements MotorFinder { - - /** - * This implementation returns a ThrustCurveMotorPlaceholder. - */ - @Override - protected Motor handleMissingMotor(Type type, String manufacturer, String designation, double diameter, double length, String digest, WarningSet warnings) { - Motor motor = new ThrustCurveMotorPlaceholder(type, - manufacturer, - designation, - diameter, - length, - digest, - /* delay */ Double.NaN, - /*launchMass*/ Double.NaN, - /*emptyMass*/ Double.NaN); - return motor; - } -} diff --git a/core/src/net/sf/openrocket/file/GeneralRocketLoader.java b/core/src/net/sf/openrocket/file/GeneralRocketLoader.java deleted file mode 100644 index da6858d8..00000000 --- a/core/src/net/sf/openrocket/file/GeneralRocketLoader.java +++ /dev/null @@ -1,115 +0,0 @@ -package net.sf.openrocket.file; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.zip.GZIPInputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.openrocket.importt.OpenRocketLoader; -import net.sf.openrocket.file.rocksim.importt.RocksimLoader; -import net.sf.openrocket.util.ArrayUtils; -import net.sf.openrocket.util.TextUtil; - - -/** - * A rocket loader that auto-detects the document type and uses the appropriate - * loading. Supports loading of GZIPed files as well with transparent - * uncompression. - * - * @author Sampo Niskanen - */ -public class GeneralRocketLoader extends AbstractRocketLoader { - - private static final int READ_BYTES = 300; - - private static final byte[] GZIP_SIGNATURE = { 31, -117 }; // 0x1f, 0x8b - private static final byte[] ZIP_SIGNATURE = TextUtil.convertStringToBytes("PK",Charset.forName("US-ASCII")); - private static final byte[] OPENROCKET_SIGNATURE = TextUtil.convertStringToBytes(" { - - public Collection load(InputStream stream, String filename) throws IOException; - -} diff --git a/core/src/net/sf/openrocket/file/MotorFinder.java b/core/src/net/sf/openrocket/file/MotorFinder.java deleted file mode 100644 index b17e6643..00000000 --- a/core/src/net/sf/openrocket/file/MotorFinder.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.file; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.motor.Motor; - -/** - * Interface for finding the appropriate motor for one defined in an ORK file. - * - * @author Sampo Niskanen - */ -public interface MotorFinder { - - /** - * Return the motor to inject to the rocket design when loading a file. - * This may also return dysfunctional motor placeholders that will later be - * replaced with the appropriate motor. - *

- * Any parameter that is null/NaN should be ignored when finding the motors. - * The method can also add appropriate warnings to the provided warning set - * in case there are problems selecting the motor. - * - * @return the motor to use in the design, or null for no motor. - */ - public Motor findMotor(Motor.Type type, String manufacturer, String designation, double diameter, - double length, String digest, WarningSet warnings); - - -} diff --git a/core/src/net/sf/openrocket/file/RocketLoadException.java b/core/src/net/sf/openrocket/file/RocketLoadException.java deleted file mode 100644 index 2fdd177b..00000000 --- a/core/src/net/sf/openrocket/file/RocketLoadException.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.file; - -public class RocketLoadException extends Exception { - - public RocketLoadException() { - } - - public RocketLoadException(String message) { - super(message); - } - - public RocketLoadException(Throwable cause) { - super(cause); - } - - public RocketLoadException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/file/RocketLoader.java b/core/src/net/sf/openrocket/file/RocketLoader.java deleted file mode 100644 index 81bcb0ac..00000000 --- a/core/src/net/sf/openrocket/file/RocketLoader.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.sf.openrocket.file; - -import java.io.File; -import java.io.InputStream; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.OpenRocketDocument; - -public interface RocketLoader { - - public OpenRocketDocument load(File source, MotorFinder motorFinder) throws RocketLoadException; - - public OpenRocketDocument load(InputStream source, MotorFinder motorFinder) throws RocketLoadException; - - public WarningSet getWarnings(); - -} diff --git a/core/src/net/sf/openrocket/file/RocketSaver.java b/core/src/net/sf/openrocket/file/RocketSaver.java deleted file mode 100644 index 5c18bb8d..00000000 --- a/core/src/net/sf/openrocket/file/RocketSaver.java +++ /dev/null @@ -1,102 +0,0 @@ -package net.sf.openrocket.file; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.StorageOptions; - - -public abstract class RocketSaver { - - /** - * Save the document to the specified file using the default storage options. - * - * @param dest the destination file. - * @param document the document to save. - * @throws IOException in case of an I/O error. - */ - public final void save(File dest, OpenRocketDocument document) throws IOException { - save(dest, document, document.getDefaultStorageOptions()); - } - - - /** - * Save the document to the specified file using the given storage options. - * - * @param dest the destination file. - * @param document the document to save. - * @param options the storage options. - * @throws IOException in case of an I/O error. - */ - public void save(File dest, OpenRocketDocument document, StorageOptions options) - throws IOException { - OutputStream s = new BufferedOutputStream(new FileOutputStream(dest)); - try { - save(s, document, options); - } finally { - s.close(); - } - } - - - /** - * Save the document to the specified output stream using the default storage options. - * - * @param dest the destination stream. - * @param doc the document to save. - * @throws IOException in case of an I/O error. - */ - public final void save(OutputStream dest, OpenRocketDocument doc) throws IOException { - save(dest, doc, doc.getDefaultStorageOptions()); - } - - - /** - * Save the document to the specified output stream using the given storage options. - * - * @param dest the destination stream. - * @param doc the document to save. - * @param options the storage options. - * @throws IOException in case of an I/O error. - */ - public abstract void save(OutputStream dest, OpenRocketDocument doc, - StorageOptions options) throws IOException; - - - - /** - * Provide an estimate of the file size when saving the document with the - * specified options. This is used as an indication to the user and when estimating - * file save progress. - * - * @param doc the document. - * @param options the save options, compression must be taken into account. - * @return the estimated number of bytes the storage would take. - */ - public abstract long estimateFileSize(OpenRocketDocument doc, StorageOptions options); - - - - - public static String escapeXML(String s) { - - s = s.replace("&", "&"); - s = s.replace("<", "<"); - s = s.replace(">", ">"); - s = s.replace("\"","""); - s = s.replace("'", "'"); - - for (int i=0; i < s.length(); i++) { - char n = s.charAt(i); - if (((n < 32) && (n != 9) && (n != 10) && (n != 13)) || (n == 127)) { - s = s.substring(0,i) + "&#" + ((int)n) + ";" + s.substring(i+1); - } - } - - return s; - } -} diff --git a/core/src/net/sf/openrocket/file/TipShapeCode.java b/core/src/net/sf/openrocket/file/TipShapeCode.java deleted file mode 100644 index c7018fd7..00000000 --- a/core/src/net/sf/openrocket/file/TipShapeCode.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.sf.openrocket.file; - -import net.sf.openrocket.rocketcomponent.FinSet; - -/** - */ -public final class TipShapeCode { - - /** - * Convert a Rocksim tip shape to an OpenRocket CrossSection. - * - * @param tipShape the tip shape code from Rocksim - * - * @return a CrossSection instance - */ - public static FinSet.CrossSection convertTipShapeCode (int tipShape) { - switch (tipShape) { - case 0: - return FinSet.CrossSection.SQUARE; - case 1: - return FinSet.CrossSection.ROUNDED; - case 2: - return FinSet.CrossSection.AIRFOIL; - default: - return FinSet.CrossSection.SQUARE; - } - } - - public static int convertTipShapeCode (FinSet.CrossSection cs) { - if (FinSet.CrossSection.ROUNDED.equals(cs)) { - return 1; - } - if (FinSet.CrossSection.AIRFOIL.equals(cs)) { - return 2; - } - return 0; - } -} diff --git a/core/src/net/sf/openrocket/file/UnknownFileTypeException.java b/core/src/net/sf/openrocket/file/UnknownFileTypeException.java deleted file mode 100644 index bcea2bbb..00000000 --- a/core/src/net/sf/openrocket/file/UnknownFileTypeException.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.file; - -import java.io.IOException; - -/** - * An exception marking that a file type was not supported. - * - * @author Sampo Niskanen - */ -public class UnknownFileTypeException extends IOException { - - public UnknownFileTypeException() { - } - - public UnknownFileTypeException(String message) { - super(message); - } - - public UnknownFileTypeException(Throwable cause) { - super(cause); - } - - public UnknownFileTypeException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/file/configuration/XmlContainerElement.java b/core/src/net/sf/openrocket/file/configuration/XmlContainerElement.java deleted file mode 100644 index c227f6d0..00000000 --- a/core/src/net/sf/openrocket/file/configuration/XmlContainerElement.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.file.configuration; - -import java.util.ArrayList; -import java.util.List; - -public class XmlContainerElement extends XmlElement { - - private ArrayList subelements = new ArrayList(); - - public XmlContainerElement(String name) { - super(name); - } - - - public void addElement(XmlElement element) { - subelements.add(element); - } - - @SuppressWarnings("unchecked") - public List getElements() { - return (List) subelements.clone(); - } - -} diff --git a/core/src/net/sf/openrocket/file/configuration/XmlContentElement.java b/core/src/net/sf/openrocket/file/configuration/XmlContentElement.java deleted file mode 100644 index bf469271..00000000 --- a/core/src/net/sf/openrocket/file/configuration/XmlContentElement.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.file.configuration; - -/** - * A simple XML element that contains textual content. - * - * @author Sampo Niskanen - */ -public class XmlContentElement extends XmlElement { - - private String content = ""; - - public XmlContentElement(String name) { - super(name); - } - - - public String getContent() { - return content; - } - - public void setContent(String content) { - if (content == null) { - throw new IllegalArgumentException("XML content cannot be null"); - } - this.content = content; - } - -} diff --git a/core/src/net/sf/openrocket/file/configuration/XmlElement.java b/core/src/net/sf/openrocket/file/configuration/XmlElement.java deleted file mode 100644 index ee094340..00000000 --- a/core/src/net/sf/openrocket/file/configuration/XmlElement.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.sf.openrocket.file.configuration; - -import java.util.HashMap; -import java.util.Map; - -/** - * A base simple XML element. A simple XML element can contain either other XML elements - * (XmlContainerElement) or textual content (XmlContentElement), but not both. - * - * @author Sampo Niskanen - */ -public abstract class XmlElement { - - private final String name; - private final HashMap attributes = new HashMap(); - - - - public XmlElement(String name) { - this.name = name; - } - - - public String getName() { - return name; - } - - public void setAttribute(String key, String value) { - attributes.put(key, value); - } - - public void removeAttribute(String key) { - attributes.remove(key); - } - - public String getAttribute(String key) { - return attributes.get(key); - } - - @SuppressWarnings("unchecked") - public Map getAttributes() { - return (Map) attributes.clone(); - } - -} diff --git a/core/src/net/sf/openrocket/file/iterator/DirectoryIterator.java b/core/src/net/sf/openrocket/file/iterator/DirectoryIterator.java deleted file mode 100644 index c934482c..00000000 --- a/core/src/net/sf/openrocket/file/iterator/DirectoryIterator.java +++ /dev/null @@ -1,187 +0,0 @@ -package net.sf.openrocket.file.iterator; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.JarUtil; -import net.sf.openrocket.util.Pair; - -/** - * A DirectoryIterator that scans for files within a directory in the file system - * matching a FileFilter. The scan is optionally recursive. - * - * @author Sampo Niskanen - */ -public class DirectoryIterator extends FileIterator { - - private static final LogHelper logger = Application.getLogger(); - - private final FileFilter filter; - private final File[] files; - private final boolean recursive; - private int position = 0; - private DirectoryIterator subIterator = null; - - /** - * Sole constructor. - * - * @param directory the directory to read. - * @param filter the filter for selecting files. - * @throws IOException if the directory cannot be read. - */ - public DirectoryIterator(File directory, FileFilter filter, boolean recursive) - throws IOException { - - this.filter = filter; - this.recursive = recursive; - - this.files = directory.listFiles(new DirSelectionFileFilter(filter, recursive)); - if (this.files == null) { - throw new IOException("not a directory or IOException occurred when listing files " + - "from " + directory); - } - } - - - - - - @Override - protected Pair findNext() { - - // Check if we're recursing - if (subIterator != null) { - if (subIterator.hasNext()) { - return subIterator.next(); - } else { - subIterator.close(); - subIterator = null; - } - } - - // Scan through file entries - while (position < files.length) { - File file = files[position]; - position++; - - try { - if (recursive && file.isDirectory()) { - subIterator = new DirectoryIterator(file, filter, recursive); - if (subIterator.hasNext()) { - return subIterator.next(); - } else { - subIterator.close(); - subIterator = null; - continue; - } - } - - InputStream is = new BufferedInputStream(new FileInputStream(file)); - return new Pair(file.getName(), is); - } catch (IOException e) { - logger.warn("Error opening file/directory " + file, e); - } - } - return null; - } - - - - /** - * Return a DirectoryIterator for a directory that can be located either - * within the containing JAR file, in the classpath or in the current directory - * (searched in this order). The first place that contains matching files - * will be iterated through. - * - * @param directory the directory to search for. - * @param filter the filter for matching files in the directory. - * @return a DirectoryIterator for iterating through the files in the - * directory, or null if no directory containing - * matching files can be found. - */ - public static FileIterator findDirectory(String directory, FileFilter filter) { - FileIterator iterator = null; - - // Try to load from containing JAR file - File jarFile = JarUtil.getCurrentJarFile(); - if (jarFile != null) { - try { - iterator = new ZipDirectoryIterator(jarFile, directory, filter); - if (iterator.hasNext()) { - return iterator; - } - iterator.close(); - } catch (IOException e) { - logger.error("Error opening containing JAR file " + jarFile, e); - } - } - - - // Try to find directory as a system resource - URL url = ClassLoader.getSystemResource(directory); - if (url != null) { - try { - File dir = JarUtil.urlToFile(url); - iterator = new DirectoryIterator(dir, filter, true); - if (iterator.hasNext()) { - return iterator; - } - iterator.close(); - } catch (Exception e1) { - logger.error("Error opening directory from URL " + url); - } - } - - - // Try to open directory as such - try { - iterator = new DirectoryIterator(new File(directory), filter, true); - if (iterator.hasNext()) { - return iterator; - } - iterator.close(); - } catch (IOException e) { - logger.error("Error opening directory " + directory); - } - - return null; - } - - - - /** - * A FileFilter wrapper that accepts or discards directories. - */ - private class DirSelectionFileFilter implements FileFilter { - - private final boolean acceptDirs; - private final FileFilter parentFilter; - - - public DirSelectionFileFilter(FileFilter filter, boolean acceptDirs) { - this.acceptDirs = acceptDirs; - this.parentFilter = filter; - } - - - @Override - public boolean accept(File pathname) { - if (pathname.getName().startsWith(".")) { - return false; - } - if (pathname.isDirectory()) { - return acceptDirs; - } - return parentFilter.accept(pathname); - } - - } - -} diff --git a/core/src/net/sf/openrocket/file/iterator/FileIterator.java b/core/src/net/sf/openrocket/file/iterator/FileIterator.java deleted file mode 100644 index 14d220a9..00000000 --- a/core/src/net/sf/openrocket/file/iterator/FileIterator.java +++ /dev/null @@ -1,94 +0,0 @@ -package net.sf.openrocket.file.iterator; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Pair; - -/** - * An abstract class for iterating over files fulfilling some condition. The files are - * returned as pairs of open InputStreams and file names. Conditions can be for example - * files in a directory matching a specific FileFilter. - *

- * Concrete implementations must implement the method {@link #findNext()} and possibly - * {@link #close()}. - * - * @author Sampo Niskanen - */ -public abstract class FileIterator implements Iterator> { - private static final LogHelper logger = Application.getLogger(); - - private Pair next = null; - private int fileCount = 0; - - @Override - public boolean hasNext() { - if (next != null) - return true; - - next = findNext(); - return (next != null); - } - - - @Override - public Pair next() { - if (next == null) { - next = findNext(); - } - if (next == null) { - throw new NoSuchElementException("No more files"); - } - - Pair n = next; - next = null; - fileCount++; - return n; - } - - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() not supported"); - } - - - - /** - * Closes the resources related to this iterator. This method should be - * overridden if the iterator needs to close any resources of its own, but - * must call this method as well. - */ - public void close() { - if (next != null) { - try { - next.getV().close(); - } catch (IOException e) { - logger.error("Error closing file " + next.getU()); - } - next = null; - } - } - - - /** - * Return the number of files that have so far been returned by this iterator. - * - * @return the number of files that this iterator has returned so far. - */ - public int getFileCount() { - return fileCount; - } - - /** - * Return the next pair of file name and InputStream. - * - * @return a pair with the file name and input stream reading the file. - */ - protected abstract Pair findNext(); - -} diff --git a/core/src/net/sf/openrocket/file/iterator/ZipDirectoryIterator.java b/core/src/net/sf/openrocket/file/iterator/ZipDirectoryIterator.java deleted file mode 100644 index 7cf5488b..00000000 --- a/core/src/net/sf/openrocket/file/iterator/ZipDirectoryIterator.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.sf.openrocket.file.iterator; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Pair; - -/** - * A DirectoryIterator that reads files from the specified directory of a - * ZIP (or JAR) file. - * - * TODO: MEDIUM: This is always a recursive search. - * - * @author Sampo Niskanen - */ -public class ZipDirectoryIterator extends FileIterator { - - private static final LogHelper logger = Application.getLogger(); - - private final File zipFileName; - private final String directory; - private final FileFilter filter; - - private ZipFile zipFile; - private Enumeration entries; - - - /** - * Sole constructor. - * - * @param zipFileName the ZIP file to read. - * @param directory the directory within the ZIP file to read, relative to the - * base (an empty string corresponds to the root directory) - * @param filter the filter for accepted files. - * @throws IOException if the ZIP file could not be read. - */ - public ZipDirectoryIterator(File zipFileName, String directory, FileFilter filter) - throws IOException { - - // Process directory and extension - if (!directory.endsWith("/")) { - directory += "/"; - } - - this.zipFileName = zipFileName; - this.directory = directory; - this.filter = filter; - - - // Loop through ZIP entries searching for files to load - this.zipFile = new ZipFile(zipFileName); - entries = zipFile.entries(); - - } - - - @Override - public void close() { - super.close(); - if (zipFile != null) { - try { - zipFile.close(); - } catch (IOException e) { - logger.error("Closing ZIP file failed", e); - } - zipFile = null; - entries = null; - } - } - - - @Override - protected Pair findNext() { - if (entries == null) { - return null; - } - - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - String name = entry.getName(); - File file = new File(name); - if (name.startsWith(directory) && filter.accept(file)) { - try { - InputStream is = zipFile.getInputStream(entry); - return new Pair(name, is); - } catch (IOException e) { - logger.error("IOException when reading ZIP file " + zipFileName, e); - } - } - } - - return null; - } - - -} diff --git a/core/src/net/sf/openrocket/file/motor/AbstractMotorLoader.java b/core/src/net/sf/openrocket/file/motor/AbstractMotorLoader.java deleted file mode 100644 index b166706f..00000000 --- a/core/src/net/sf/openrocket/file/motor/AbstractMotorLoader.java +++ /dev/null @@ -1,200 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.util.ArrayUtils; -import net.sf.openrocket.util.MathUtil; - -public abstract class AbstractMotorLoader implements MotorLoader { - - - /** - * {@inheritDoc} - *

- * This method delegates the reading to the loaded from the Reader using the charset - * returned by {@link #getDefaultCharset()}. - */ - public List load(InputStream stream, String filename) throws IOException { - return load(new InputStreamReader(stream, getDefaultCharset()), filename); - } - - - /** - * Load motors from the specified Reader. - * - * @param reader the source of the motor definitions. - * @param filename the file name of the file, may be null if not - * applicable. - * @return a list of motors contained in the file. - * @throws IOException if an I/O exception occurs of the file format is invalid. - */ - protected abstract List load(Reader reader, String filename) throws IOException; - - - - /** - * Return the default charset to use when loading rocket files of this type. - *

- * If the method {@link #load(InputStream, String)} is overridden as well, this - * method may return null. - * - * @return the charset to use when loading the rocket file. - */ - protected abstract Charset getDefaultCharset(); - - - - - ////////// Helper methods ////////// - - - /** - * Calculate the mass of a motor at distinct points in time based on the - * initial total mass, propellant weight and thrust. - *

- * This calculation assumes that the velocity of the exhaust remains constant - * during the burning. This derives from the mass-flow and thrust relation - *

F = m' * v
- * - * @param time list of time points - * @param thrust thrust at the discrete times - * @param total total weight of the motor - * @param prop propellant amount consumed during burning - * @return a list of the mass at the specified time points - */ - protected static List calculateMass(List time, List thrust, - double total, double prop) { - List mass = new ArrayList(); - List deltam = new ArrayList(); - - double t0, f0; - double totalMassChange = 0; - double scale; - - // First calculate mass change between points - t0 = time.get(0); - f0 = thrust.get(0); - for (int i = 1; i < time.size(); i++) { - double t1 = time.get(i); - double f1 = thrust.get(i); - - double dm = 0.5 * (f0 + f1) * (t1 - t0); - deltam.add(dm); - totalMassChange += dm; - t0 = t1; - f0 = f1; - } - - // Scale mass change and calculate mass - mass.add(total); - scale = prop / totalMassChange; - for (double dm : deltam) { - total -= dm * scale; - mass.add(total); - } - - return mass; - } - - - /** - * Helper method to remove a delay (or plugged) from the end of a motor designation, - * if present. - * - * @param designation the motor designation. - * @return the designation with a possible delay removed. - */ - protected static String removeDelay(String designation) { - if (designation.matches(".*-([0-9]+|[pP])$")) { - designation = designation.substring(0, designation.lastIndexOf('-')); - } - return designation; - } - - - - /** - * Helper method to tokenize a string using whitespace as the delimiter. - */ - protected static String[] split(String str) { - return split(str, "\\s+"); - } - - - /** - * Helper method to tokenize a string using the given delimiter. - */ - protected static String[] split(String str, String delim) { - String[] pieces = str.split(delim); - if (pieces.length == 0 || !pieces[0].equals("")) - return pieces; - return ArrayUtils.copyOfRange(pieces, 1, pieces.length); - } - - - /** - * Sort the primary list and other lists in that order. - * - * @param primary the list to order. - * @param lists lists to order in the same permutation. - */ - protected static void sortLists(List primary, List... lists) { - - // TODO: LOW: Very idiotic sort algorithm, but should be fast enough - // since the time should be sorted already - - int index; - - do { - for (index = 0; index < primary.size() - 1; index++) { - if (primary.get(index + 1) < primary.get(index)) { - Collections.swap(primary, index, index + 1); - for (List l : lists) { - Collections.swap(l, index, index + 1); - } - break; - } - } - } while (index < primary.size() - 1); - } - - - - @SuppressWarnings("unchecked") - protected static void finalizeThrustCurve(List time, List thrust, - List... lists) { - - if (time.size() == 0) - return; - - // Start - if (!MathUtil.equals(time.get(0), 0) || !MathUtil.equals(thrust.get(0), 0)) { - time.add(0, 0.0); - thrust.add(0, 0.0); - for (List l : lists) { - Object o = l.get(0); - l.add(0, o); - } - } - - // End - int n = time.size() - 1; - if (!MathUtil.equals(thrust.get(n), 0)) { - time.add(time.get(n)); - thrust.add(0.0); - for (List l : lists) { - Object o = l.get(n); - l.add(o); - } - } - } - -} diff --git a/core/src/net/sf/openrocket/file/motor/GeneralMotorLoader.java b/core/src/net/sf/openrocket/file/motor/GeneralMotorLoader.java deleted file mode 100644 index 937c6790..00000000 --- a/core/src/net/sf/openrocket/file/motor/GeneralMotorLoader.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import net.sf.openrocket.file.UnknownFileTypeException; -import net.sf.openrocket.motor.Motor; - -/** - * A motor loader class that detects the file type based on the file name extension. - * - * @author Sampo Niskanen - */ -public class GeneralMotorLoader implements MotorLoader { - - private final MotorLoader RASP_LOADER = new RASPMotorLoader(); - private final MotorLoader ROCKSIM_LOADER = new RockSimMotorLoader(); - private final MotorLoader ZIP_LOADER; - - - public GeneralMotorLoader() { - // Must use this loader in order to avoid recursive instantiation - ZIP_LOADER = new ZipFileMotorLoader(this); - } - - - - /** - * {@inheritDoc} - * - * @throws UnknownFileTypeException if the file format is not supported - */ - @Override - public List load(InputStream stream, String filename) throws IOException { - return selectLoader(filename).load(stream, filename); - } - - - - /** - * Return an array containing the supported file extensions. - * - * @return an array of the supported file extensions. - */ - public String[] getSupportedExtensions() { - return new String[] { "rse", "eng", "zip" }; - } - - - /** - * Return the appropriate motor loader based on the file name. - * - * @param filename the file name (may be null). - * @return the appropriate motor loader to use for the file. - * @throws UnknownFileTypeException if the file type cannot be detected from the file name. - */ - private MotorLoader selectLoader(String filename) throws IOException { - if (filename == null) { - throw new UnknownFileTypeException("Unknown file type, filename=null"); - } - - String ext = ""; - int point = filename.lastIndexOf('.'); - - if (point > 0) - ext = filename.substring(point + 1); - - if (ext.equalsIgnoreCase("eng")) { - return RASP_LOADER; - } else if (ext.equalsIgnoreCase("rse")) { - return ROCKSIM_LOADER; - } else if (ext.equalsIgnoreCase("zip")) { - return ZIP_LOADER; - } - - throw new UnknownFileTypeException("Unknown file type, filename=" + filename); - } - -} diff --git a/core/src/net/sf/openrocket/file/motor/MotorLoader.java b/core/src/net/sf/openrocket/file/motor/MotorLoader.java deleted file mode 100644 index 73e14039..00000000 --- a/core/src/net/sf/openrocket/file/motor/MotorLoader.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import net.sf.openrocket.file.Loader; -import net.sf.openrocket.motor.Motor; - - -public interface MotorLoader extends Loader { - - /** - * Load motors from the specified InputStream. - * - * @param stream the source of the motor definitions. - * @param filename the file name of the file, may be null if not - * applicable. - * @return a list of motors contained in the file. - * @throws IOException if an I/O exception occurs of the file format is invalid. - */ - public List load(InputStream stream, String filename) throws IOException; - -} diff --git a/core/src/net/sf/openrocket/file/motor/MotorLoaderHelper.java b/core/src/net/sf/openrocket/file/motor/MotorLoaderHelper.java deleted file mode 100644 index 13a2e423..00000000 --- a/core/src/net/sf/openrocket/file/motor/MotorLoaderHelper.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.file.iterator.DirectoryIterator; -import net.sf.openrocket.file.iterator.FileIterator; -import net.sf.openrocket.gui.util.SimpleFileFilter; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Pair; - -public final class MotorLoaderHelper { - - private static final LogHelper log = Application.getLogger(); - - private MotorLoaderHelper() { - // Prevent construction - } - - /** - * Load a file or directory of thrust curves. Directories are loaded - * recursively. Any errors during loading are logged, but otherwise ignored. - * - * @param target the file or directory to load. - * @return a list of all motors in the file/directory. - */ - public static List load(File target) { - GeneralMotorLoader loader = new GeneralMotorLoader(); - - if (target.isDirectory()) { - - try { - return load(new DirectoryIterator(target, new SimpleFileFilter("", loader.getSupportedExtensions()), true)); - } catch (IOException e) { - log.warn("Could not read directory " + target, e); - return Collections.emptyList(); - } - - } else { - - InputStream is = null; - try { - is = new FileInputStream(target); - return loader.load(new BufferedInputStream(is), target.getName()); - } catch (IOException e) { - log.warn("Could not load file " + target, e); - return Collections.emptyList(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - log.error("Could not close file " + target, e); - } - } - } - - } - } - - public static List load( InputStream is, String fileName ) { - GeneralMotorLoader loader = new GeneralMotorLoader(); - try { - List motors = loader.load(is, fileName); - if (motors.size() == 0) { - log.warn("No motors found in file " + fileName); - } - return motors; - } catch (IOException e) { - log.warn("IOException when loading motor file " + fileName, e); - } - return Collections.emptyList(); - } - - /** - * Load motors from files iterated over by a FileIterator. Any errors during - * loading are logged, but otherwise ignored. - *

- * The iterator is closed at the end of the operation. - * - * @param iterator the FileIterator that iterates of the files to load. - * @return a list of all motors loaded. - */ - public static List load(FileIterator iterator) { - List list = new ArrayList(); - - while (iterator.hasNext()) { - final Pair input = iterator.next(); - log.debug("Loading motors from file " + input.getU()); - try { - List motors = load(input.getV(), input.getU()); - for (Motor m : motors) { - list.add((ThrustCurveMotor) m); - } - } finally { - try { - input.getV().close(); - } catch (IOException e) { - log.error("IOException when closing InputStream", e); - } - } - } - iterator.close(); - - return list; - } - -} diff --git a/core/src/net/sf/openrocket/file/motor/RASPMotorLoader.java b/core/src/net/sf/openrocket/file/motor/RASPMotorLoader.java deleted file mode 100644 index df1ddecc..00000000 --- a/core/src/net/sf/openrocket/file/motor/RASPMotorLoader.java +++ /dev/null @@ -1,214 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorDigest; -import net.sf.openrocket.motor.MotorDigest.DataType; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.Coordinate; - -public class RASPMotorLoader extends AbstractMotorLoader { - - public static final String CHARSET_NAME = "ISO-8859-1"; - - public static final Charset CHARSET = Charset.forName(CHARSET_NAME); - - - - - @Override - protected Charset getDefaultCharset() { - return CHARSET; - } - - - /** - * Load a Motor from a RASP file specified by the Reader. - * The Reader is responsible for using the correct charset. - *

- * The CG is assumed to be located at the center of the motor casing and the mass - * is calculated from the thrust curve by assuming a constant exhaust velocity. - * - * @param reader the source of the file. - * @return a list of the {@link Motor} objects defined in the file. - * @throws IOException if an I/O error occurs or if the file format is illegal. - */ - @Override - public List load(Reader reader, String filename) throws IOException { - List motors = new ArrayList(); - BufferedReader in = new BufferedReader(reader); - - String manufacturer = ""; - String designation = ""; - String comment = ""; - - double length = 0; - double diameter = 0; - ArrayList delays = null; - - List time = new ArrayList(); - List thrust = new ArrayList(); - - double propW = 0; - double totalW = 0; - - try { - String line; - String[] pieces, buf; - - line = in.readLine(); - main: while (line != null) { // Until EOF - - manufacturer = ""; - designation = ""; - comment = ""; - length = 0; - diameter = 0; - delays = new ArrayList(); - propW = 0; - totalW = 0; - time.clear(); - thrust.clear(); - - // Read comment - while (line.length() == 0 || line.charAt(0) == ';') { - if (line.length() > 0) { - comment += line.substring(1).trim() + "\n"; - } - line = in.readLine(); - if (line == null) - break main; - } - comment = comment.trim(); - - // Parse header line, example: - // F32 24 124 5-10-15-P .0377 .0695 RV - // desig diam len delays prop.w tot.w manufacturer - pieces = split(line); - if (pieces.length != 7) { - throw new IOException("Illegal file format."); - } - - designation = pieces[0]; - diameter = Double.parseDouble(pieces[1]) / 1000.0; - length = Double.parseDouble(pieces[2]) / 1000.0; - - if (pieces[3].equalsIgnoreCase("None")) { - - } else { - buf = split(pieces[3], "[-,]+"); - for (int i = 0; i < buf.length; i++) { - if (buf[i].equalsIgnoreCase("P") || - buf[i].equalsIgnoreCase("plugged")) { - delays.add(Motor.PLUGGED); - } else { - // Many RASP files have "100" as an only delay - double d = Double.parseDouble(buf[i]); - if (d < 99) - delays.add(d); - } - } - Collections.sort(delays); - } - - propW = Double.parseDouble(pieces[4]); - totalW = Double.parseDouble(pieces[5]); - manufacturer = pieces[6]; - - if (propW > totalW) { - throw new IOException("Propellant weight exceeds total weight in " + - "RASP file " + filename); - } - - // Read the data - for (line = in.readLine(); (line != null) && (line.length() == 0 || line.charAt(0) != ';'); line = in.readLine()) { - - buf = split(line); - if (buf.length == 0) { - continue; - } else if (buf.length == 2) { - - time.add(Double.parseDouble(buf[0])); - thrust.add(Double.parseDouble(buf[1])); - - } else { - throw new IOException("Illegal file format."); - } - } - - // Comment of EOF encountered, marks the start of the next motor - if (time.size() < 2) { - throw new IOException("Illegal file format, too short thrust-curve."); - } - double[] delayArray = new double[delays.size()]; - for (int i = 0; i < delays.size(); i++) { - delayArray[i] = delays.get(i); - } - motors.add(createRASPMotor(manufacturer, designation, comment, - length, diameter, delayArray, propW, totalW, time, thrust)); - } - - } catch (NumberFormatException e) { - - throw new IOException("Illegal file format."); - - } - - return motors; - } - - - /** - * Create a motor from RASP file data. - * @throws IOException if the data is illegal for a thrust curve - */ - private static Motor createRASPMotor(String manufacturer, String designation, - String comment, double length, double diameter, double[] delays, - double propW, double totalW, List time, List thrust) - throws IOException { - - // Add zero time/thrust if necessary - sortLists(time, thrust); - finalizeThrustCurve(time, thrust); - List mass = calculateMass(time, thrust, totalW, propW); - - double[] timeArray = new double[time.size()]; - double[] thrustArray = new double[time.size()]; - Coordinate[] cgArray = new Coordinate[time.size()]; - for (int i = 0; i < time.size(); i++) { - timeArray[i] = time.get(i); - thrustArray[i] = thrust.get(i); - cgArray[i] = new Coordinate(length / 2, 0, 0, mass.get(i)); - } - - designation = removeDelay(designation); - - // Create the motor digest from data available in RASP files - MotorDigest motorDigest = new MotorDigest(); - motorDigest.update(DataType.TIME_ARRAY, timeArray); - motorDigest.update(DataType.MASS_SPECIFIC, totalW, totalW - propW); - motorDigest.update(DataType.FORCE_PER_TIME, thrustArray); - final String digest = motorDigest.getDigest(); - - try { - - Manufacturer m = Manufacturer.getManufacturer(manufacturer); - return new ThrustCurveMotor(m, designation, comment, m.getMotorType(), - delays, diameter, length, timeArray, thrustArray, cgArray, digest); - - } catch (IllegalArgumentException e) { - - // Bad data read from file. - throw new IOException("Illegal file format.", e); - - } - } -} diff --git a/core/src/net/sf/openrocket/file/motor/RockSimMotorLoader.java b/core/src/net/sf/openrocket/file/motor/RockSimMotorLoader.java deleted file mode 100644 index 5a79d946..00000000 --- a/core/src/net/sf/openrocket/file/motor/RockSimMotorLoader.java +++ /dev/null @@ -1,481 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.IOException; -import java.io.Reader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.simplesax.AbstractElementHandler; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.NullElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.file.simplesax.SimpleSAX; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorDigest; -import net.sf.openrocket.motor.MotorDigest.DataType; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class RockSimMotorLoader extends AbstractMotorLoader { - - private static final LogHelper log = Application.getLogger(); - - public static final String CHARSET_NAME = "UTF-8"; - - public static final Charset CHARSET = Charset.forName(CHARSET_NAME); - - - /** Any delay longer than this will be interpreted as a plugged motor. */ - private static final int DELAY_LIMIT = 90; - - - - @Override - protected Charset getDefaultCharset() { - return CHARSET; - } - - - - /** - * Load a Motor from a RockSim motor definition file specified by the - * Reader. The Reader is responsible for using the correct - * charset. - *

- * If automatic CG/mass calculation is used, then the CG is assumed to be located at - * the center of the motor casing and the mass is calculated from the thrust curve - * by assuming a constant exhaust velocity. - * - * @param reader the source of the file. - * @return a list of the {@link Motor} objects defined in the file. - * @throws IOException if an I/O error occurs or if the file format is invalid. - */ - @Override - public List load(Reader reader, String filename) throws IOException { - InputSource source = new InputSource(reader); - RSEHandler handler = new RSEHandler(); - WarningSet warnings = new WarningSet(); - - try { - SimpleSAX.readXML(source, handler, warnings); - return handler.getMotors(); - } catch (SAXException e) { - throw new IOException(e.getMessage(), e); - } - } - - - - /** - * Initial handler for the RockSim engine files. - */ - private static class RSEHandler extends AbstractElementHandler { - private final List motors = new ArrayList(); - - private RSEMotorHandler motorHandler; - - public List getMotors() { - return motors; - } - - @Override - public ElementHandler openElement(String element, - HashMap attributes, WarningSet warnings) throws SAXException { - - if (element.equals("engine-database") || - element.equals("engine-list")) { - // Ignore and elements - return this; - } - - if (element.equals("version")) { - // Ignore elements completely - return null; - } - - if (element.equals("engine")) { - motorHandler = new RSEMotorHandler(attributes); - return motorHandler; - } - - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - if (element.equals("engine")) { - Motor motor = motorHandler.getMotor(); - motors.add(motor); - } - } - } - - - /** - * Handler for a RockSim engine file element. - */ - private static class RSEMotorHandler extends AbstractElementHandler { - - private final String manufacturer; - private final String designation; - private final double[] delays; - private final double diameter; - private final double length; - private final double initMass; - private final double propMass; - private final Motor.Type type; - private boolean calculateMass; - private boolean calculateCG; - - private String description = ""; - - private List time; - private List force; - private List mass; - private List cg; - - private RSEMotorDataHandler dataHandler = null; - - - public RSEMotorHandler(HashMap attributes) throws SAXException { - String str; - - // Manufacturer - str = attributes.get("mfg"); - if (str == null) - throw new SAXException("Manufacturer missing"); - manufacturer = str; - - // Designation - str = attributes.get("code"); - if (str == null) - throw new SAXException("Designation missing"); - designation = removeDelay(str); - - // Delays - ArrayList delayList = new ArrayList(); - str = attributes.get("delays"); - if (str != null) { - String[] split = str.split(","); - for (String delay : split) { - try { - - double d = Double.parseDouble(delay); - if (d >= DELAY_LIMIT) - d = Motor.PLUGGED; - delayList.add(d); - - } catch (NumberFormatException e) { - if (str.equalsIgnoreCase("P") || str.equalsIgnoreCase("plugged")) { - delayList.add(Motor.PLUGGED); - } - } - } - } - delays = new double[delayList.size()]; - for (int i = 0; i < delayList.size(); i++) { - delays[i] = delayList.get(i); - } - - // Diameter - str = attributes.get("dia"); - if (str == null) - throw new SAXException("Diameter missing"); - try { - diameter = Double.parseDouble(str) / 1000.0; - } catch (NumberFormatException e) { - throw new SAXException("Invalid diameter " + str); - } - - // Length - str = attributes.get("len"); - if (str == null) - throw new SAXException("Length missing"); - try { - length = Double.parseDouble(str) / 1000.0; - } catch (NumberFormatException e) { - throw new SAXException("Invalid length " + str); - } - - // Initial mass - str = attributes.get("initWt"); - if (str == null) - throw new SAXException("Initial mass missing"); - try { - initMass = Double.parseDouble(str) / 1000.0; - } catch (NumberFormatException e) { - throw new SAXException("Invalid initial mass " + str); - } - - // Propellant mass - str = attributes.get("propWt"); - if (str == null) - throw new SAXException("Propellant mass missing"); - try { - propMass = Double.parseDouble(str) / 1000.0; - } catch (NumberFormatException e) { - throw new SAXException("Invalid propellant mass " + str); - } - - if (propMass > initMass) { - throw new SAXException("Propellant weight exceeds total weight in " + - "RockSim engine format"); - } - - // Motor type - str = attributes.get("Type"); - if ("single-use".equalsIgnoreCase(str)) { - type = Motor.Type.SINGLE; - } else if ("hybrid".equalsIgnoreCase(str)) { - type = Motor.Type.HYBRID; - } else if ("reloadable".equalsIgnoreCase(str)) { - type = Motor.Type.RELOAD; - } else { - type = Motor.Type.UNKNOWN; - } - - // Calculate mass - str = attributes.get("auto-calc-mass"); - if ("0".equals(str) || "false".equalsIgnoreCase(str)) { - calculateMass = false; - } else { - calculateMass = true; - } - - // Calculate CG - str = attributes.get("auto-calc-cg"); - if ("0".equals(str) || "false".equalsIgnoreCase(str)) { - calculateCG = false; - } else { - calculateCG = true; - } - } - - @Override - public ElementHandler openElement(String element, - HashMap attributes, WarningSet warnings) throws SAXException { - - if (element.equals("comments")) { - return PlainTextHandler.INSTANCE; - } - - if (element.equals("data")) { - if (dataHandler != null) { - throw new SAXException("Multiple data elements encountered in motor " + - "definition"); - } - dataHandler = new RSEMotorDataHandler(); - return dataHandler; - } - - warnings.add("Unknown element '" + element + "' encountered, ignoring."); - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - - if (element.equals("comments")) { - if (description.length() > 0) { - description = description + "\n\n" + content.trim(); - } else { - description = content.trim(); - } - return; - } - - if (element.equals("data")) { - time = dataHandler.getTime(); - force = dataHandler.getForce(); - mass = dataHandler.getMass(); - cg = dataHandler.getCG(); - - sortLists(time, force, mass, cg); - - for (double d : mass) { - if (Double.isNaN(d)) { - calculateMass = true; - break; - } - } - for (double d : cg) { - if (Double.isNaN(d)) { - calculateCG = true; - break; - } - } - return; - } - } - - public Motor getMotor() throws SAXException { - if (time == null || time.size() == 0) - throw new SAXException("Illegal motor data"); - - - finalizeThrustCurve(time, force, mass, cg); - final int n = time.size(); - - if (hasIllegalValue(mass)) - calculateMass = true; - if (hasIllegalValue(cg)) - calculateCG = true; - - if (calculateMass) { - mass = calculateMass(time, force, initMass, propMass); - } - if (calculateCG) { - for (int i = 0; i < n; i++) { - cg.set(i, length / 2); - } - } - - double[] timeArray = toArray(time); - double[] thrustArray = toArray(force); - Coordinate[] cgArray = new Coordinate[n]; - for (int i = 0; i < n; i++) { - cgArray[i] = new Coordinate(cg.get(i), 0, 0, mass.get(i)); - } - - - // Create the motor digest from all data available in the file - MotorDigest motorDigest = new MotorDigest(); - motorDigest.update(DataType.TIME_ARRAY, timeArray); - if (!calculateMass) { - motorDigest.update(DataType.MASS_PER_TIME, toArray(mass)); - } else { - motorDigest.update(DataType.MASS_SPECIFIC, initMass, initMass - propMass); - } - if (!calculateCG) { - motorDigest.update(DataType.CG_PER_TIME, toArray(cg)); - } - motorDigest.update(DataType.FORCE_PER_TIME, thrustArray); - final String digest = motorDigest.getDigest(); - - - try { - Manufacturer m = Manufacturer.getManufacturer(manufacturer); - Motor.Type t = type; - if (t == Motor.Type.UNKNOWN) { - t = m.getMotorType(); - } else { - if (m.getMotorType() != Motor.Type.UNKNOWN && m.getMotorType() != t) { - log.warn("Loaded motor type inconsistent with manufacturer," + - " loaded type=" + t + " manufacturer=" + m + - " manufacturer type=" + m.getMotorType() + - " designation=" + designation); - } - } - - return new ThrustCurveMotor(m, designation, description, t, - delays, diameter, length, timeArray, thrustArray, cgArray, digest); - } catch (IllegalArgumentException e) { - throw new SAXException("Illegal motor data", e); - } - } - } - - - /** - * Handler for the element in a RockSim engine file motor definition. - */ - private static class RSEMotorDataHandler extends AbstractElementHandler { - - private final List time = new ArrayList(); - private final List force = new ArrayList(); - private final List mass = new ArrayList(); - private final List cg = new ArrayList(); - - - public List getTime() { - return time; - } - - public List getForce() { - return force; - } - - public List getMass() { - return mass; - } - - public List getCG() { - return cg; - } - - - @Override - public ElementHandler openElement(String element, - HashMap attributes, WarningSet warnings) { - - if (element.equals("eng-data")) { - return NullElementHandler.INSTANCE; - } - - warnings.add("Unknown element '" + element + "' encountered, ignoring."); - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - double t = parseDouble(attributes.get("t")); - double f = parseDouble(attributes.get("f")); - double m = parseDouble(attributes.get("m")) / 1000.0; - double g = parseDouble(attributes.get("cg")) / 1000.0; - - if (Double.isNaN(t) || Double.isNaN(f)) { - throw new SAXException("Illegal motor data point encountered"); - } - - time.add(t); - force.add(f); - mass.add(m); - cg.add(g); - } - - - private double parseDouble(String str) { - if (str == null) - return Double.NaN; - try { - return Double.parseDouble(str); - } catch (NumberFormatException e) { - return Double.NaN; - } - } - } - - - - private static boolean hasIllegalValue(List list) { - for (Double d : list) { - if (d == null || d.isNaN() || d.isInfinite()) { - return true; - } - } - return false; - } - - private static double[] toArray(List list) { - final int n = list.size(); - double[] array = new double[n]; - for (int i = 0; i < n; i++) { - array[i] = list.get(i); - } - return array; - } -} diff --git a/core/src/net/sf/openrocket/file/motor/ZipFileMotorLoader.java b/core/src/net/sf/openrocket/file/motor/ZipFileMotorLoader.java deleted file mode 100644 index 804226f0..00000000 --- a/core/src/net/sf/openrocket/file/motor/ZipFileMotorLoader.java +++ /dev/null @@ -1,85 +0,0 @@ -package net.sf.openrocket.file.motor; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import net.sf.openrocket.file.UnknownFileTypeException; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.UncloseableInputStream; - -/** - * A motor loader that loads motors from a ZIP file. - * - * @author Sampo Niskanen - */ -public class ZipFileMotorLoader implements MotorLoader { - private static final LogHelper log = Application.getLogger(); - - private final MotorLoader loader; - - - /** - * Construct a ZipFileMotorLoader that loads files using a - * {@link GeneralMotorLoader}. - */ - public ZipFileMotorLoader() { - this(new GeneralMotorLoader()); - } - - /** - * Constructs a ZipFileMotorLoader that loads files using the provided motor loader. - * - * @param loader the motor loader to use when loading. - */ - public ZipFileMotorLoader(MotorLoader loader) { - this.loader = loader; - } - - - @Override - public List load(InputStream stream, String filename) throws IOException { - List motors = new ArrayList(); - - ZipInputStream is = new ZipInputStream(stream); - - // SAX seems to close the input stream, prevent it - InputStream uncloseable = new UncloseableInputStream(is); - - while (true) { - ZipEntry entry = is.getNextEntry(); - if (entry == null) - break; - - if (entry.isDirectory()) - continue; - - // Get the file name of the entry - String name = entry.getName(); - int index = name.lastIndexOf('/'); - if (index < 0) { - index = name.lastIndexOf('\\'); - } - if (index >= 0) { - name = name.substring(index + 1); - } - - try { - List m = loader.load(uncloseable, entry.getName()); - motors.addAll(m); - log.info("Loaded " + m.size() + " motors from ZIP entry " + entry.getName()); - } catch (UnknownFileTypeException e) { - log.info("Could not read ZIP entry " + entry.getName() + ": " + e.getMessage()); - } - - } - - return motors; - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java b/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java deleted file mode 100644 index 0a5e0479..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java +++ /dev/null @@ -1,633 +0,0 @@ -package net.sf.openrocket.file.openrocket; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.zip.GZIPOutputStream; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.document.StorageOptions; -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RecoveryDevice.DeployEvent; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationOptions; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.TextUtil; - -public class OpenRocketSaver extends RocketSaver { - private static final LogHelper log = Application.getLogger(); - - - /** - * Divisor used in converting an integer version to the point-represented version. - * The integer version divided by this value is the major version and the remainder is - * the minor version. For example 101 corresponds to file version "1.1". - */ - public static final int FILE_VERSION_DIVISOR = 100; - - - private static final String OPENROCKET_CHARSET = "UTF-8"; - - private static final String METHOD_PACKAGE = "net.sf.openrocket.file.openrocket.savers"; - private static final String METHOD_SUFFIX = "Saver"; - - - // Estimated storage used by different portions - // These have been hand-estimated from saved files - private static final int BYTES_PER_COMPONENT_UNCOMPRESSED = 590; - private static final int BYTES_PER_COMPONENT_COMPRESSED = 80; - private static final int BYTES_PER_SIMULATION_UNCOMPRESSED = 1000; - private static final int BYTES_PER_SIMULATION_COMPRESSED = 100; - private static final int BYTES_PER_DATAPOINT_UNCOMPRESSED = 350; - private static final int BYTES_PER_DATAPOINT_COMPRESSED = 100; - - - private int indent; - private Writer dest; - - @Override - public void save(OutputStream output, OpenRocketDocument document, StorageOptions options) - throws IOException { - - log.info("Saving .ork file"); - - if (options.isCompressionEnabled()) { - log.debug("Enabling compression"); - output = new GZIPOutputStream(output); - } - - dest = new BufferedWriter(new OutputStreamWriter(output, OPENROCKET_CHARSET)); - - // Select file version number - final int fileVersion = calculateNecessaryFileVersion(document, options); - final String fileVersionString = - (fileVersion / FILE_VERSION_DIVISOR) + "." + (fileVersion % FILE_VERSION_DIVISOR); - log.debug("Storing file version " + fileVersionString); - - - this.indent = 0; - - - writeln(""); - writeln(""); - indent++; - - // Recursively save the rocket structure - saveComponent(document.getRocket()); - - writeln(""); - - // Save custom expressions; - saveCustomDatatypes(document); - - // Save all simulations - writeln(""); - indent++; - boolean first = true; - for (Simulation s : document.getSimulations()) { - if (!first) - writeln(""); - first = false; - saveSimulation(s, options.getSimulationTimeSkip()); - } - indent--; - writeln(""); - - indent--; - writeln(""); - - log.debug("Writing complete, flushing buffers"); - dest.flush(); - if (options.isCompressionEnabled()) { - ((GZIPOutputStream) output).finish(); - } - } - - /* - * Save all the custom expressions - */ - private void saveCustomDatatypes(OpenRocketDocument doc) throws IOException { - - if (doc.getCustomExpressions().isEmpty()) - return; - - writeln(""); - indent++; - - for (CustomExpression exp : doc.getCustomExpressions()) { - saveCustomExpressionDatatype(exp); - } - - indent--; - writeln(""); - writeln(""); - } - - /* - * Save one custom expression datatype - */ - private void saveCustomExpressionDatatype(CustomExpression exp) throws IOException { - // Write out custom expression - - writeln(""); - indent++; - writeln("" + exp.getName() + ""); - writeln("" + exp.getSymbol() + ""); - writeln("" + exp.getUnit() + ""); // auto unit type means it will be determined from string - writeln("" + exp.getExpressionString() + ""); - indent--; - writeln(""); - } - - @Override - public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) { - - long size = 0; - - // Size per component - int componentCount = 0; - Rocket rocket = doc.getRocket(); - Iterator iterator = rocket.iterator(true); - while (iterator.hasNext()) { - iterator.next(); - componentCount++; - } - - if (options.isCompressionEnabled()) - size += componentCount * BYTES_PER_COMPONENT_COMPRESSED; - else - size += componentCount * BYTES_PER_COMPONENT_UNCOMPRESSED; - - - // Size per simulation - if (options.isCompressionEnabled()) - size += doc.getSimulationCount() * BYTES_PER_SIMULATION_COMPRESSED; - else - size += doc.getSimulationCount() * BYTES_PER_SIMULATION_UNCOMPRESSED; - - - // Size per flight data point - int pointCount = 0; - double timeSkip = options.getSimulationTimeSkip(); - if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) { - for (Simulation s : doc.getSimulations()) { - FlightData data = s.getSimulatedData(); - if (data != null) { - for (int i = 0; i < data.getBranchCount(); i++) { - pointCount += countFlightDataBranchPoints(data.getBranch(i), timeSkip); - } - } - } - } - - if (options.isCompressionEnabled()) - size += pointCount * BYTES_PER_DATAPOINT_COMPRESSED; - else - size += pointCount * BYTES_PER_DATAPOINT_UNCOMPRESSED; - - return size; - } - - - /** - * Determine which file version is required in order to store all the features of the - * current design. By default the oldest version that supports all the necessary features - * will be used. - * - * @param document the document to output. - * @param opts the storage options. - * @return the integer file version to use. - */ - private int calculateNecessaryFileVersion(OpenRocketDocument document, StorageOptions opts) { - /* - * File version 1.5 is requires for: - * - saving designs using ComponentPrests - * - recovery device deployment on lower stage separation - * - custom expressions - * - * File version 1.4 is required for: - * - saving simulation data - * - saving motor data - * - * File version 1.1 is required for: - * - fin tabs - * - components attached to tube coupler - * - * Otherwise use version 1.0. - */ - - // Search the rocket for any ComponentPresets (version 1.5) - for (RocketComponent c : document.getRocket()) { - if (c.getPresetComponent() != null) { - return FILE_VERSION_DIVISOR + 5; - } - } - - // Search for recovery device deployment type LOWER_STAGE_SEPARATION (version 1.5) - for (RocketComponent c : document.getRocket()) { - if (c instanceof RecoveryDevice) { - if (((RecoveryDevice) c).getDeployEvent() == DeployEvent.LOWER_STAGE_SEPARATION) { - return FILE_VERSION_DIVISOR + 5; - } - } - } - - // Check for custom expressions - if (!document.getCustomExpressions().isEmpty()) { - return FILE_VERSION_DIVISOR + 5; - } - - // Check if design has simulations defined (version 1.4) - if (document.getSimulationCount() > 0) { - return FILE_VERSION_DIVISOR + 4; - } - - // Check for motor definitions (version 1.4) - for (RocketComponent c : document.getRocket()) { - if (!(c instanceof MotorMount)) - continue; - - MotorMount mount = (MotorMount) c; - for (String id : document.getRocket().getMotorConfigurationIDs()) { - if (mount.getMotor(id) != null) { - return FILE_VERSION_DIVISOR + 4; - } - } - } - - // Check for fin tabs (version 1.1) - for (RocketComponent c : document.getRocket()) { - // Check for fin tabs - if (c instanceof FinSet) { - FinSet fin = (FinSet) c; - if (!MathUtil.equals(fin.getTabHeight(), 0) && - !MathUtil.equals(fin.getTabLength(), 0)) { - return FILE_VERSION_DIVISOR + 1; - } - } - - // Check for components attached to tube coupler - if (c instanceof TubeCoupler) { - if (c.getChildCount() > 0) { - return FILE_VERSION_DIVISOR + 1; - } - } - } - - // Default (version 1.0) - return FILE_VERSION_DIVISOR + 0; - } - - - - @SuppressWarnings("unchecked") - private void saveComponent(RocketComponent component) throws IOException { - - log.debug("Saving component " + component.getComponentName()); - - Reflection.Method m = Reflection.findMethod(METHOD_PACKAGE, component, METHOD_SUFFIX, - "getElements", RocketComponent.class); - if (m == null) { - throw new BugException("Unable to find saving class for component " + - component.getComponentName()); - } - - // Get the strings to save - List list = (List) m.invokeStatic(component); - int length = list.size(); - - if (length == 0) // Nothing to do - return; - - if (length < 2) { - throw new RuntimeException("BUG, component data length less than two lines."); - } - - // Open element - writeln(list.get(0)); - indent++; - - // Write parameters - for (int i = 1; i < length - 1; i++) { - writeln(list.get(i)); - } - - // Recursively write subcomponents - if (component.getChildCount() > 0) { - writeln(""); - writeln(""); - indent++; - boolean emptyline = false; - for (RocketComponent subcomponent : component.getChildren()) { - if (emptyline) - writeln(""); - emptyline = true; - saveComponent(subcomponent); - } - indent--; - writeln(""); - } - - // Close element - indent--; - writeln(list.get(length - 1)); - } - - - private void saveSimulation(Simulation simulation, double timeSkip) throws IOException { - SimulationOptions cond = simulation.getOptions(); - - writeln(""); - indent++; - - writeln("" + escapeXML(simulation.getName()) + ""); - // TODO: MEDIUM: Other simulators/calculators - - writeln("RK4Simulator"); - writeln("BarrowmanCalculator"); - - writeln(""); - indent++; - - writeElement("configid", cond.getMotorConfigurationID()); - writeElement("launchrodlength", cond.getLaunchRodLength()); - writeElement("launchrodangle", cond.getLaunchRodAngle() * 180.0 / Math.PI); - writeElement("launchroddirection", cond.getLaunchRodDirection() * 180.0 / Math.PI); - writeElement("windaverage", cond.getWindSpeedAverage()); - writeElement("windturbulence", cond.getWindTurbulenceIntensity()); - writeElement("launchaltitude", cond.getLaunchAltitude()); - writeElement("launchlatitude", cond.getLaunchLatitude()); - writeElement("launchlongitude", cond.getLaunchLongitude()); - writeElement("geodeticmethod", cond.getGeodeticComputation().name().toLowerCase(Locale.ENGLISH)); - - if (cond.isISAAtmosphere()) { - writeln(""); - } else { - writeln(""); - indent++; - writeElement("basetemperature", cond.getLaunchTemperature()); - writeElement("basepressure", cond.getLaunchPressure()); - indent--; - writeln(""); - } - - writeElement("timestep", cond.getTimeStep()); - - indent--; - writeln(""); - - - for (String s : simulation.getSimulationListeners()) { - writeElement("listener", escapeXML(s)); - } - - // Write basic simulation data - - FlightData data = simulation.getSimulatedData(); - if (data != null) { - String str = ""); - } - - indent--; - writeln(""); - - } - - - - private void saveFlightDataBranch(FlightDataBranch branch, double timeSkip) - throws IOException { - double previousTime = -100000; - - if (branch == null) - return; - - // Retrieve the types from the branch - FlightDataType[] types = branch.getTypes(); - - if (types.length == 0) - return; - - // Retrieve the data from the branch - List> data = new ArrayList>(types.length); - for (int i = 0; i < types.length; i++) { - data.add(branch.get(types[i])); - } - List timeData = branch.get(FlightDataType.TYPE_TIME); - - // Build the tag - StringBuilder sb = new StringBuilder(); - sb.append(" 0) - sb.append(","); - sb.append(escapeXML(types[i].getKey())); - } - */ - - sb.append("\" types=\""); - for (int i = 0; i < types.length; i++) { - if (i > 0) - sb.append(","); - sb.append(escapeXML(types[i].getName())); - } - sb.append("\">"); - writeln(sb.toString()); - indent++; - - // Write events - for (FlightEvent event : branch.getEvents()) { - writeln(""); - } - - // Write the data - int length = branch.getLength(); - if (length > 0) { - writeDataPointString(data, 0, sb); - previousTime = timeData.get(0); - } - - for (int i = 1; i < length - 1; i++) { - if (timeData != null) { - if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) { - writeDataPointString(data, i, sb); - previousTime = timeData.get(i); - } - } else { - // If time data is not available, write all points - writeDataPointString(data, i, sb); - } - } - - if (length > 1) { - writeDataPointString(data, length - 1, sb); - } - - indent--; - writeln(""); - } - - - - /* TODO: LOW: This is largely duplicated from above! */ - private int countFlightDataBranchPoints(FlightDataBranch branch, double timeSkip) { - int count = 0; - - double previousTime = -100000; - - if (branch == null) - return 0; - - // Retrieve the types from the branch - FlightDataType[] types = branch.getTypes(); - - if (types.length == 0) - return 0; - - List timeData = branch.get(FlightDataType.TYPE_TIME); - if (timeData == null) { - // If time data not available, store all points - return branch.getLength(); - } - - // Write the data - int length = branch.getLength(); - if (length > 0) { - count++; - previousTime = timeData.get(0); - } - - for (int i = 1; i < length - 1; i++) { - if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) { - count++; - previousTime = timeData.get(i); - } - } - - if (length > 1) { - count++; - } - - return count; - } - - - - private void writeDataPointString(List> data, int index, StringBuilder sb) - throws IOException { - sb.setLength(0); - sb.append(""); - for (int j = 0; j < data.size(); j++) { - if (j > 0) - sb.append(","); - sb.append(TextUtil.doubleToString(data.get(j).get(index))); - } - sb.append(""); - writeln(sb.toString()); - } - - - - private void writeElement(String element, Object content) throws IOException { - if (content == null) - content = ""; - writeln("<" + element + ">" + content + ""); - } - - - - private void writeln(String str) throws IOException { - if (str.length() == 0) { - dest.write("\n"); - return; - } - String s = ""; - for (int i = 0; i < indent; i++) - s = s + " "; - s = s + str + "\n"; - dest.write(s); - } - - - - - /** - * Return the XML equivalent of an enum name. - * - * @param e the enum to save. - * @return the corresponding XML name. - */ - public static String enumToXMLName(Enum e) { - return e.name().toLowerCase(Locale.ENGLISH).replace("_", ""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/importt/DocumentLoadingContext.java b/core/src/net/sf/openrocket/file/openrocket/importt/DocumentLoadingContext.java deleted file mode 100644 index cd920eae..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/importt/DocumentLoadingContext.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.file.openrocket.importt; - -import net.sf.openrocket.file.MotorFinder; - -public class DocumentLoadingContext { - - private int fileVersion; - private MotorFinder motorFinder; - - - public int getFileVersion() { - return fileVersion; - } - - public void setFileVersion(int fileVersion) { - this.fileVersion = fileVersion; - } - - public MotorFinder getMotorFinder() { - return motorFinder; - } - - public void setMotorFinder(MotorFinder motorFinder) { - this.motorFinder = motorFinder; - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java b/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java deleted file mode 100644 index 4efdf9db..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java +++ /dev/null @@ -1,2313 +0,0 @@ -package net.sf.openrocket.file.openrocket.importt; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.document.Simulation.Status; -import net.sf.openrocket.document.StorageOptions; -import net.sf.openrocket.file.AbstractRocketLoader; -import net.sf.openrocket.file.MotorFinder; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.file.simplesax.AbstractElementHandler; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.file.simplesax.SimpleSAX; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.BodyComponent; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.ClusterConfiguration; -import net.sf.openrocket.rocketcomponent.Clusterable; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.IllegalFinPointException; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.InternalComponent; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RadiusRingComponent; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.ReferenceType; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent.Position; -import net.sf.openrocket.rocketcomponent.ShockCord; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.StructuralComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.rocketcomponent.ThicknessRingComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.FlightEvent.Type; -import net.sf.openrocket.simulation.SimulationOptions; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Color; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.GeodeticComputationStrategy; -import net.sf.openrocket.util.LineStyle; -import net.sf.openrocket.util.Reflection; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - - -/** - * Class that loads a rocket definition from an OpenRocket rocket file. - *

- * This class uses SAX to read the XML file format. The - * #loadFromStream(InputStream) method simply sets the system up and - * starts the parsing, while the actual logic is in the private inner class - * OpenRocketHandler. - * - * @author Sampo Niskanen - */ -public class OpenRocketLoader extends AbstractRocketLoader { - private static final LogHelper log = Application.getLogger(); - - - @Override - public OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws RocketLoadException, - IOException { - log.info("Loading .ork file"); - DocumentLoadingContext context = new DocumentLoadingContext(); - context.setMotorFinder(motorFinder); - - InputSource xmlSource = new InputSource(source); - OpenRocketHandler handler = new OpenRocketHandler(context); - - - try { - SimpleSAX.readXML(xmlSource, handler, warnings); - } catch (SAXException e) { - log.warn("Malformed XML in input"); - throw new RocketLoadException("Malformed XML in input.", e); - } - - - OpenRocketDocument doc = handler.getDocument(); - doc.getDefaultConfiguration().setAllStages(); - - // Deduce suitable time skip - double timeSkip = StorageOptions.SIMULATION_DATA_NONE; - for (Simulation s : doc.getSimulations()) { - if (s.getStatus() == Simulation.Status.EXTERNAL || - s.getStatus() == Simulation.Status.NOT_SIMULATED) - continue; - if (s.getSimulatedData() == null) - continue; - if (s.getSimulatedData().getBranchCount() == 0) - continue; - FlightDataBranch branch = s.getSimulatedData().getBranch(0); - if (branch == null) - continue; - List list = branch.get(FlightDataType.TYPE_TIME); - if (list == null) - continue; - - double previousTime = Double.NaN; - for (double time : list) { - if (time - previousTime < timeSkip) - timeSkip = time - previousTime; - previousTime = time; - } - } - // Round value - timeSkip = Math.rint(timeSkip * 100) / 100; - - doc.getDefaultStorageOptions().setSimulationTimeSkip(timeSkip); - doc.getDefaultStorageOptions().setCompressionEnabled(false); // Set by caller if compressed - doc.getDefaultStorageOptions().setExplicitlySet(false); - - doc.clearUndo(); - log.info("Loading done"); - return doc; - } - -} - - - -class DocumentConfig { - - /* Remember to update OpenRocketSaver as well! */ - public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4", "1.5" }; - - /** - * Divisor used in converting an integer version to the point-represented version. - * The integer version divided by this value is the major version and the remainder is - * the minor version. For example 101 corresponds to file version "1.1". - */ - public static final int FILE_VERSION_DIVISOR = 100; - - - //////// Component constructors - static final HashMap> constructors = new HashMap>(); - static { - try { - // External components - constructors.put("bodytube", BodyTube.class.getConstructor(new Class[0])); - constructors.put("transition", Transition.class.getConstructor(new Class[0])); - constructors.put("nosecone", NoseCone.class.getConstructor(new Class[0])); - constructors.put("trapezoidfinset", TrapezoidFinSet.class.getConstructor(new Class[0])); - constructors.put("ellipticalfinset", EllipticalFinSet.class.getConstructor(new Class[0])); - constructors.put("freeformfinset", FreeformFinSet.class.getConstructor(new Class[0])); - constructors.put("launchlug", LaunchLug.class.getConstructor(new Class[0])); - - // Internal components - constructors.put("engineblock", EngineBlock.class.getConstructor(new Class[0])); - constructors.put("innertube", InnerTube.class.getConstructor(new Class[0])); - constructors.put("tubecoupler", TubeCoupler.class.getConstructor(new Class[0])); - constructors.put("bulkhead", Bulkhead.class.getConstructor(new Class[0])); - constructors.put("centeringring", CenteringRing.class.getConstructor(new Class[0])); - - constructors.put("masscomponent", MassComponent.class.getConstructor(new Class[0])); - constructors.put("shockcord", ShockCord.class.getConstructor(new Class[0])); - constructors.put("parachute", Parachute.class.getConstructor(new Class[0])); - constructors.put("streamer", Streamer.class.getConstructor(new Class[0])); - - // Other - constructors.put("stage", Stage.class.getConstructor(new Class[0])); - - } catch (NoSuchMethodException e) { - throw new BugException( - "Error in constructing the 'constructors' HashMap."); - } - } - - - //////// Parameter setters - /* - * The keys are of the form Class:param, where Class is the class name and param - * the element name. Setters are searched for in descending class order. - * A setter of null means setting the parameter is not allowed. - */ - static final HashMap setters = new HashMap(); - static { - // RocketComponent - setters.put("RocketComponent:name", new StringSetter( - Reflection.findMethod(RocketComponent.class, "setName", String.class))); - setters.put("RocketComponent:color", new ColorSetter( - Reflection.findMethod(RocketComponent.class, "setColor", Color.class))); - setters.put("RocketComponent:linestyle", new EnumSetter( - Reflection.findMethod(RocketComponent.class, "setLineStyle", LineStyle.class), - LineStyle.class)); - setters.put("RocketComponent:position", new PositionSetter()); - setters.put("RocketComponent:overridemass", new OverrideSetter( - Reflection.findMethod(RocketComponent.class, "setOverrideMass", double.class), - Reflection.findMethod(RocketComponent.class, "setMassOverridden", boolean.class))); - setters.put("RocketComponent:overridecg", new OverrideSetter( - Reflection.findMethod(RocketComponent.class, "setOverrideCGX", double.class), - Reflection.findMethod(RocketComponent.class, "setCGOverridden", boolean.class))); - setters.put("RocketComponent:overridesubcomponents", new BooleanSetter( - Reflection.findMethod(RocketComponent.class, "setOverrideSubcomponents", boolean.class))); - setters.put("RocketComponent:comment", new StringSetter( - Reflection.findMethod(RocketComponent.class, "setComment", String.class))); - setters.put("RocketComponent:preset", new ComponentPresetSetter( - Reflection.findMethod(RocketComponent.class, "loadPreset", ComponentPreset.class))); - - // ExternalComponent - setters.put("ExternalComponent:finish", new EnumSetter( - Reflection.findMethod(ExternalComponent.class, "setFinish", Finish.class), - Finish.class)); - setters.put("ExternalComponent:material", new MaterialSetter( - Reflection.findMethod(ExternalComponent.class, "setMaterial", Material.class), - Material.Type.BULK)); - - // BodyComponent - setters.put("BodyComponent:length", new DoubleSetter( - Reflection.findMethod(BodyComponent.class, "setLength", double.class))); - - // SymmetricComponent - setters.put("SymmetricComponent:thickness", new DoubleSetter( - Reflection.findMethod(SymmetricComponent.class, "setThickness", double.class), - "filled", - Reflection.findMethod(SymmetricComponent.class, "setFilled", boolean.class))); - - // BodyTube - setters.put("BodyTube:radius", new DoubleSetter( - Reflection.findMethod(BodyTube.class, "setOuterRadius", double.class), - "auto", - Reflection.findMethod(BodyTube.class, "setOuterRadiusAutomatic", boolean.class))); - - // Transition - setters.put("Transition:shape", new EnumSetter( - Reflection.findMethod(Transition.class, "setType", Transition.Shape.class), - Transition.Shape.class)); - setters.put("Transition:shapeclipped", new BooleanSetter( - Reflection.findMethod(Transition.class, "setClipped", boolean.class))); - setters.put("Transition:shapeparameter", new DoubleSetter( - Reflection.findMethod(Transition.class, "setShapeParameter", double.class))); - - setters.put("Transition:foreradius", new DoubleSetter( - Reflection.findMethod(Transition.class, "setForeRadius", double.class), - "auto", - Reflection.findMethod(Transition.class, "setForeRadiusAutomatic", boolean.class))); - setters.put("Transition:aftradius", new DoubleSetter( - Reflection.findMethod(Transition.class, "setAftRadius", double.class), - "auto", - Reflection.findMethod(Transition.class, "setAftRadiusAutomatic", boolean.class))); - - setters.put("Transition:foreshoulderradius", new DoubleSetter( - Reflection.findMethod(Transition.class, "setForeShoulderRadius", double.class))); - setters.put("Transition:foreshoulderlength", new DoubleSetter( - Reflection.findMethod(Transition.class, "setForeShoulderLength", double.class))); - setters.put("Transition:foreshoulderthickness", new DoubleSetter( - Reflection.findMethod(Transition.class, "setForeShoulderThickness", double.class))); - setters.put("Transition:foreshouldercapped", new BooleanSetter( - Reflection.findMethod(Transition.class, "setForeShoulderCapped", boolean.class))); - - setters.put("Transition:aftshoulderradius", new DoubleSetter( - Reflection.findMethod(Transition.class, "setAftShoulderRadius", double.class))); - setters.put("Transition:aftshoulderlength", new DoubleSetter( - Reflection.findMethod(Transition.class, "setAftShoulderLength", double.class))); - setters.put("Transition:aftshoulderthickness", new DoubleSetter( - Reflection.findMethod(Transition.class, "setAftShoulderThickness", double.class))); - setters.put("Transition:aftshouldercapped", new BooleanSetter( - Reflection.findMethod(Transition.class, "setAftShoulderCapped", boolean.class))); - - // NoseCone - disable disallowed elements - setters.put("NoseCone:foreradius", null); - setters.put("NoseCone:foreshoulderradius", null); - setters.put("NoseCone:foreshoulderlength", null); - setters.put("NoseCone:foreshoulderthickness", null); - setters.put("NoseCone:foreshouldercapped", null); - - // FinSet - setters.put("FinSet:fincount", new IntSetter( - Reflection.findMethod(FinSet.class, "setFinCount", int.class))); - setters.put("FinSet:rotation", new DoubleSetter( - Reflection.findMethod(FinSet.class, "setBaseRotation", double.class), Math.PI / 180.0)); - setters.put("FinSet:thickness", new DoubleSetter( - Reflection.findMethod(FinSet.class, "setThickness", double.class))); - setters.put("FinSet:crosssection", new EnumSetter( - Reflection.findMethod(FinSet.class, "setCrossSection", FinSet.CrossSection.class), - FinSet.CrossSection.class)); - setters.put("FinSet:cant", new DoubleSetter( - Reflection.findMethod(FinSet.class, "setCantAngle", double.class), Math.PI / 180.0)); - setters.put("FinSet:tabheight", new DoubleSetter( - Reflection.findMethod(FinSet.class, "setTabHeight", double.class))); - setters.put("FinSet:tablength", new DoubleSetter( - Reflection.findMethod(FinSet.class, "setTabLength", double.class))); - setters.put("FinSet:tabposition", new FinTabPositionSetter()); - - // TrapezoidFinSet - setters.put("TrapezoidFinSet:rootchord", new DoubleSetter( - Reflection.findMethod(TrapezoidFinSet.class, "setRootChord", double.class))); - setters.put("TrapezoidFinSet:tipchord", new DoubleSetter( - Reflection.findMethod(TrapezoidFinSet.class, "setTipChord", double.class))); - setters.put("TrapezoidFinSet:sweeplength", new DoubleSetter( - Reflection.findMethod(TrapezoidFinSet.class, "setSweep", double.class))); - setters.put("TrapezoidFinSet:height", new DoubleSetter( - Reflection.findMethod(TrapezoidFinSet.class, "setHeight", double.class))); - - // EllipticalFinSet - setters.put("EllipticalFinSet:rootchord", new DoubleSetter( - Reflection.findMethod(EllipticalFinSet.class, "setLength", double.class))); - setters.put("EllipticalFinSet:height", new DoubleSetter( - Reflection.findMethod(EllipticalFinSet.class, "setHeight", double.class))); - - // FreeformFinSet points handled as a special handler - - // LaunchLug - setters.put("LaunchLug:radius", new DoubleSetter( - Reflection.findMethod(LaunchLug.class, "setOuterRadius", double.class))); - setters.put("LaunchLug:length", new DoubleSetter( - Reflection.findMethod(LaunchLug.class, "setLength", double.class))); - setters.put("LaunchLug:thickness", new DoubleSetter( - Reflection.findMethod(LaunchLug.class, "setThickness", double.class))); - setters.put("LaunchLug:radialdirection", new DoubleSetter( - Reflection.findMethod(LaunchLug.class, "setRadialDirection", double.class), - Math.PI / 180.0)); - - // InternalComponent - nothing - - // StructuralComponent - setters.put("StructuralComponent:material", new MaterialSetter( - Reflection.findMethod(StructuralComponent.class, "setMaterial", Material.class), - Material.Type.BULK)); - - // RingComponent - setters.put("RingComponent:length", new DoubleSetter( - Reflection.findMethod(RingComponent.class, "setLength", double.class))); - setters.put("RingComponent:radialposition", new DoubleSetter( - Reflection.findMethod(RingComponent.class, "setRadialPosition", double.class))); - setters.put("RingComponent:radialdirection", new DoubleSetter( - Reflection.findMethod(RingComponent.class, "setRadialDirection", double.class), - Math.PI / 180.0)); - - // ThicknessRingComponent - radius on separate components due to differing automatics - setters.put("ThicknessRingComponent:thickness", new DoubleSetter( - Reflection.findMethod(ThicknessRingComponent.class, "setThickness", double.class))); - - // EngineBlock - setters.put("EngineBlock:outerradius", new DoubleSetter( - Reflection.findMethod(EngineBlock.class, "setOuterRadius", double.class), - "auto", - Reflection.findMethod(EngineBlock.class, "setOuterRadiusAutomatic", boolean.class))); - - // TubeCoupler - setters.put("TubeCoupler:outerradius", new DoubleSetter( - Reflection.findMethod(TubeCoupler.class, "setOuterRadius", double.class), - "auto", - Reflection.findMethod(TubeCoupler.class, "setOuterRadiusAutomatic", boolean.class))); - - // InnerTube - setters.put("InnerTube:outerradius", new DoubleSetter( - Reflection.findMethod(InnerTube.class, "setOuterRadius", double.class))); - setters.put("InnerTube:clusterconfiguration", new ClusterConfigurationSetter()); - setters.put("InnerTube:clusterscale", new DoubleSetter( - Reflection.findMethod(InnerTube.class, "setClusterScale", double.class))); - setters.put("InnerTube:clusterrotation", new DoubleSetter( - Reflection.findMethod(InnerTube.class, "setClusterRotation", double.class), - Math.PI / 180.0)); - - // RadiusRingComponent - - // Bulkhead - setters.put("RadiusRingComponent:innerradius", new DoubleSetter( - Reflection.findMethod(RadiusRingComponent.class, "setInnerRadius", double.class))); - setters.put("Bulkhead:outerradius", new DoubleSetter( - Reflection.findMethod(Bulkhead.class, "setOuterRadius", double.class), - "auto", - Reflection.findMethod(Bulkhead.class, "setOuterRadiusAutomatic", boolean.class))); - - // CenteringRing - setters.put("CenteringRing:innerradius", new DoubleSetter( - Reflection.findMethod(CenteringRing.class, "setInnerRadius", double.class), - "auto", - Reflection.findMethod(CenteringRing.class, "setInnerRadiusAutomatic", boolean.class))); - setters.put("CenteringRing:outerradius", new DoubleSetter( - Reflection.findMethod(CenteringRing.class, "setOuterRadius", double.class), - "auto", - Reflection.findMethod(CenteringRing.class, "setOuterRadiusAutomatic", boolean.class))); - - - // MassObject - setters.put("MassObject:packedlength", new DoubleSetter( - Reflection.findMethod(MassObject.class, "setLength", double.class))); - setters.put("MassObject:packedradius", new DoubleSetter( - Reflection.findMethod(MassObject.class, "setRadius", double.class))); - setters.put("MassObject:radialposition", new DoubleSetter( - Reflection.findMethod(MassObject.class, "setRadialPosition", double.class))); - setters.put("MassObject:radialdirection", new DoubleSetter( - Reflection.findMethod(MassObject.class, "setRadialDirection", double.class), - Math.PI / 180.0)); - - // MassComponent - setters.put("MassComponent:mass", new DoubleSetter( - Reflection.findMethod(MassComponent.class, "setComponentMass", double.class))); - - // ShockCord - setters.put("ShockCord:cordlength", new DoubleSetter( - Reflection.findMethod(ShockCord.class, "setCordLength", double.class))); - setters.put("ShockCord:material", new MaterialSetter( - Reflection.findMethod(ShockCord.class, "setMaterial", Material.class), - Material.Type.LINE)); - - // RecoveryDevice - setters.put("RecoveryDevice:cd", new DoubleSetter( - Reflection.findMethod(RecoveryDevice.class, "setCD", double.class), - "auto", - Reflection.findMethod(RecoveryDevice.class, "setCDAutomatic", boolean.class))); - setters.put("RecoveryDevice:deployevent", new EnumSetter( - Reflection.findMethod(RecoveryDevice.class, "setDeployEvent", RecoveryDevice.DeployEvent.class), - RecoveryDevice.DeployEvent.class)); - setters.put("RecoveryDevice:deployaltitude", new DoubleSetter( - Reflection.findMethod(RecoveryDevice.class, "setDeployAltitude", double.class))); - setters.put("RecoveryDevice:deploydelay", new DoubleSetter( - Reflection.findMethod(RecoveryDevice.class, "setDeployDelay", double.class))); - setters.put("RecoveryDevice:material", new MaterialSetter( - Reflection.findMethod(RecoveryDevice.class, "setMaterial", Material.class), - Material.Type.SURFACE)); - - // Parachute - setters.put("Parachute:diameter", new DoubleSetter( - Reflection.findMethod(Parachute.class, "setDiameter", double.class))); - setters.put("Parachute:linecount", new IntSetter( - Reflection.findMethod(Parachute.class, "setLineCount", int.class))); - setters.put("Parachute:linelength", new DoubleSetter( - Reflection.findMethod(Parachute.class, "setLineLength", double.class))); - setters.put("Parachute:linematerial", new MaterialSetter( - Reflection.findMethod(Parachute.class, "setLineMaterial", Material.class), - Material.Type.LINE)); - - // Streamer - setters.put("Streamer:striplength", new DoubleSetter( - Reflection.findMethod(Streamer.class, "setStripLength", double.class))); - setters.put("Streamer:stripwidth", new DoubleSetter( - Reflection.findMethod(Streamer.class, "setStripWidth", double.class))); - - // Rocket - // handled by separate handler - setters.put("Rocket:referencetype", new EnumSetter( - Reflection.findMethod(Rocket.class, "setReferenceType", ReferenceType.class), - ReferenceType.class)); - setters.put("Rocket:customreference", new DoubleSetter( - Reflection.findMethod(Rocket.class, "setCustomReferenceLength", double.class))); - setters.put("Rocket:designer", new StringSetter( - Reflection.findMethod(Rocket.class, "setDesigner", String.class))); - setters.put("Rocket:revision", new StringSetter( - Reflection.findMethod(Rocket.class, "setRevision", String.class))); - - // Stage - setters.put("Stage:separationevent", new EnumSetter( - Reflection.findMethod(Stage.class, "setSeparationEvent", Stage.SeparationEvent.class), - Stage.SeparationEvent.class)); - setters.put("Stage:separationdelay", new DoubleSetter( - Reflection.findMethod(Stage.class, "setSeparationDelay", double.class))); - - } - - - /** - * Search for a enum value that has the corresponding name as an XML value. The current - * conversion from enum name to XML value is to lowercase the name and strip out all - * underscore characters. This method returns a match to these criteria, or null - * if no such enum exists. - * - * @param then enum type. - * @param name the XML value, null ok. - * @param enumClass the class of the enum. - * @return the found enum value, or null. - */ - public static > Enum findEnum(String name, - Class> enumClass) { - - if (name == null) - return null; - name = name.trim(); - for (Enum e : enumClass.getEnumConstants()) { - if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) { - return e; - } - } - return null; - } - - - /** - * Convert a string to a double including formatting specifications of the OpenRocket - * file format. This accepts all formatting that is valid for - * Double.parseDouble(s) and a few others as well ("Inf", "-Inf"). - * - * @param s the string to parse. - * @return the numerical value. - * @throws NumberFormatException the the string cannot be parsed. - */ - public static double stringToDouble(String s) throws NumberFormatException { - if (s == null) - throw new NumberFormatException("null string"); - if (s.equalsIgnoreCase("NaN")) - return Double.NaN; - if (s.equalsIgnoreCase("Inf")) - return Double.POSITIVE_INFINITY; - if (s.equalsIgnoreCase("-Inf")) - return Double.NEGATIVE_INFINITY; - return Double.parseDouble(s); - } -} - - - - - -/** - * The starting point of the handlers. Accepts a single element and hands - * the contents to be read by a OpenRocketContentsHandler. - */ -class OpenRocketHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private OpenRocketContentHandler handler = null; - - public OpenRocketHandler(DocumentLoadingContext context) { - this.context = context; - } - - /** - * Return the OpenRocketDocument read from the file, or null if a document - * has not been read yet. - * - * @return the document read, or null. - */ - public OpenRocketDocument getDocument() { - return handler.getDocument(); - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - // Check for unknown elements - if (!element.equals("openrocket")) { - warnings.add(Warning.fromString("Unknown element " + element + ", ignoring.")); - return null; - } - - // Check for first call - if (handler != null) { - warnings.add(Warning.fromString("Multiple document elements found, ignoring later " - + "ones.")); - return null; - } - - // Check version number - String version = null; - String creator = attributes.remove("creator"); - String docVersion = attributes.remove("version"); - for (String v : DocumentConfig.SUPPORTED_VERSIONS) { - if (v.equals(docVersion)) { - version = v; - break; - } - } - if (version == null) { - String str = "Unsupported document version"; - if (docVersion != null) - str += " " + docVersion; - if (creator != null && !creator.trim().equals("")) - str += " (written using '" + creator.trim() + "')"; - str += ", attempting to read file anyway."; - warnings.add(str); - } - - context.setFileVersion(parseVersion(docVersion)); - - handler = new OpenRocketContentHandler(context); - return handler; - } - - - private int parseVersion(String docVersion) { - if (docVersion == null) - return 0; - - Matcher m = Pattern.compile("^([0-9]+)\\.([0-9]+)$").matcher(docVersion); - if (m.matches()) { - int major = Integer.parseInt(m.group(1)); - int minor = Integer.parseInt(m.group(2)); - return major * DocumentConfig.FILE_VERSION_DIVISOR + minor; - } else { - return 0; - } - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - attributes.remove("version"); - attributes.remove("creator"); - super.closeElement(element, attributes, content, warnings); - } - - -} - - -/** - * Handles the content of the tag. - */ -class OpenRocketContentHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final OpenRocketDocument doc; - private final Rocket rocket; - - private boolean rocketDefined = false; - private boolean simulationsDefined = false; - private boolean datatypesDefined = false; - - public OpenRocketContentHandler(DocumentLoadingContext context) { - this.context = context; - this.rocket = new Rocket(); - this.doc = new OpenRocketDocument(rocket); - } - - public OpenRocketDocument getDocument() { - if (!rocketDefined) - return null; - return doc; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (element.equals("rocket")) { - if (rocketDefined) { - warnings.add(Warning - .fromString("Multiple rocket designs within one document, " - + "ignoring later ones.")); - return null; - } - rocketDefined = true; - return new ComponentParameterHandler(rocket, context); - } - - if (element.equals("datatypes")) { - if (datatypesDefined) { - warnings.add(Warning.fromString("Multiple datatype blocks. Ignoring later ones.")); - return null; - } - datatypesDefined = true; - return new DatatypeHandler(this, context); - } - - if (element.equals("simulations")) { - if (simulationsDefined) { - warnings.add(Warning - .fromString("Multiple simulation definitions within one document, " - + "ignoring later ones.")); - return null; - } - simulationsDefined = true; - return new SimulationsHandler(doc, context); - } - - warnings.add(Warning.fromString("Unknown element " + element + ", ignoring.")); - - return null; - } -} - -class DatatypeHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final OpenRocketContentHandler contentHandler; - private CustomExpressionHandler customExpressionHandler = null; - - public DatatypeHandler(OpenRocketContentHandler contentHandler, DocumentLoadingContext context) { - this.context = context; - this.contentHandler = contentHandler; - } - - @Override - public ElementHandler openElement(String element, - HashMap attributes, WarningSet warnings) - throws SAXException { - - if (element.equals("type") && attributes.get("source").equals("customexpression")) { - customExpressionHandler = new CustomExpressionHandler(contentHandler, context); - return customExpressionHandler; - } - else { - warnings.add(Warning.fromString("Unknown datatype " + element + " defined, ignoring")); - } - - return this; - } - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) throws SAXException { - attributes.remove("source"); - super.closeElement(element, attributes, content, warnings); - - if (customExpressionHandler != null) { - contentHandler.getDocument().addCustomExpression(customExpressionHandler.currentExpression); - } - - } - -} - -class CustomExpressionHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final OpenRocketContentHandler contentHandler; - public CustomExpression currentExpression; - - public CustomExpressionHandler(OpenRocketContentHandler contentHandler, DocumentLoadingContext context) { - this.context = context; - this.contentHandler = contentHandler; - currentExpression = new CustomExpression(contentHandler.getDocument()); - - } - - @Override - public ElementHandler openElement(String element, - HashMap attributes, WarningSet warnings) - throws SAXException { - - return this; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - if (element.equals("type")) { - contentHandler.getDocument().addCustomExpression(currentExpression); - } - - if (element.equals("name")) { - currentExpression.setName(content); - } - - if (element.equals("symbol")) { - currentExpression.setSymbol(content); - } - - if (element.equals("unit") && attributes.get("unittype").equals("auto")) { - currentExpression.setUnit(content); - } - - if (element.equals("expression")) { - currentExpression.setExpression(content); - } - } -} - -/** - * A handler that creates components from the corresponding elements. The control of the - * contents is passed on to ComponentParameterHandler. - */ -class ComponentHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final RocketComponent parent; - - public ComponentHandler(RocketComponent parent, DocumentLoadingContext context) { - this.parent = parent; - this.context = context; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - // Attempt to construct new component - Constructor constructor = DocumentConfig.constructors - .get(element); - if (constructor == null) { - warnings.add(Warning.fromString("Unknown element " + element + ", ignoring.")); - return null; - } - - RocketComponent c; - try { - c = constructor.newInstance(); - } catch (InstantiationException e) { - throw new BugException("Error constructing component.", e); - } catch (IllegalAccessException e) { - throw new BugException("Error constructing component.", e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - - parent.addChild(c); - - return new ComponentParameterHandler(c, context); - } -} - - -/** - * A handler that populates the parameters of a previously constructed rocket component. - * This uses the setters, or delegates the handling to another handler for specific - * elements. - */ -class ComponentParameterHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final RocketComponent component; - - public ComponentParameterHandler(RocketComponent c, DocumentLoadingContext context) { - this.component = c; - this.context = context; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - // Check for specific elements that contain other elements - if (element.equals("subcomponents")) { - return new ComponentHandler(component, context); - } - if (element.equals("motormount")) { - if (!(component instanceof MotorMount)) { - warnings.add(Warning.fromString("Illegal component defined as motor mount.")); - return null; - } - return new MotorMountHandler((MotorMount) component, context); - } - if (element.equals("finpoints")) { - if (!(component instanceof FreeformFinSet)) { - warnings.add(Warning.fromString("Illegal component defined for fin points.")); - return null; - } - return new FinSetPointHandler((FreeformFinSet) component, context); - } - if (element.equals("motorconfiguration")) { - if (!(component instanceof Rocket)) { - warnings.add(Warning.fromString("Illegal component defined for motor configuration.")); - return null; - } - return new MotorConfigurationHandler((Rocket) component, context); - } - - - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - - if (element.equals("subcomponents") || element.equals("motormount") || - element.equals("finpoints") || element.equals("motorconfiguration")) { - return; - } - - // Search for the correct setter class - - Class c; - for (c = component.getClass(); c != null; c = c.getSuperclass()) { - String setterKey = c.getSimpleName() + ":" + element; - Setter s = DocumentConfig.setters.get(setterKey); - if (s != null) { - // Setter found - s.set(component, content, attributes, warnings); - break; - } - if (DocumentConfig.setters.containsKey(setterKey)) { - // Key exists but is null -> invalid parameter - c = null; - break; - } - } - if (c == null) { - warnings.add(Warning.fromString("Unknown parameter type '" + element + "' for " - + component.getComponentName() + ", ignoring.")); - } - } -} - - -/** - * A handler that reads the specifications within the freeformfinset's - * elements. - */ -class FinSetPointHandler extends AbstractElementHandler { - @SuppressWarnings("unused") - private final DocumentLoadingContext context; - private final FreeformFinSet finset; - private final ArrayList coordinates = new ArrayList(); - - public FinSetPointHandler(FreeformFinSet finset, DocumentLoadingContext context) { - this.finset = finset; - this.context = context; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - String strx = attributes.remove("x"); - String stry = attributes.remove("y"); - if (strx == null || stry == null) { - warnings.add(Warning.fromString("Illegal fin points specification, ignoring.")); - return; - } - try { - double x = Double.parseDouble(strx); - double y = Double.parseDouble(stry); - coordinates.add(new Coordinate(x, y)); - } catch (NumberFormatException e) { - warnings.add(Warning.fromString("Illegal fin points specification, ignoring.")); - return; - } - - super.closeElement(element, attributes, content, warnings); - } - - @Override - public void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) { - try { - finset.setPoints(coordinates.toArray(new Coordinate[0])); - } catch (IllegalFinPointException e) { - warnings.add(Warning.fromString("Freeform fin set point definitions illegal, ignoring.")); - } - } -} - - -class MotorMountHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final MotorMount mount; - private MotorHandler motorHandler; - - public MotorMountHandler(MotorMount mount, DocumentLoadingContext context) { - this.mount = mount; - this.context = context; - mount.setMotorMount(true); - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (element.equals("motor")) { - motorHandler = new MotorHandler(context); - return motorHandler; - } - - if (element.equals("ignitionevent") || - element.equals("ignitiondelay") || - element.equals("overhang")) { - return PlainTextHandler.INSTANCE; - } - - warnings.add(Warning.fromString("Unknown element '" + element + "' encountered, ignoring.")); - return null; - } - - - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - if (element.equals("motor")) { - String id = attributes.get("configid"); - if (id == null || id.equals("")) { - warnings.add(Warning.fromString("Illegal motor specification, ignoring.")); - return; - } - - Motor motor = motorHandler.getMotor(warnings); - mount.setMotor(id, motor); - mount.setMotorDelay(id, motorHandler.getDelay(warnings)); - return; - } - - if (element.equals("ignitionevent")) { - MotorMount.IgnitionEvent event = null; - for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) { - if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) { - event = e; - break; - } - } - if (event == null) { - warnings.add(Warning.fromString("Unknown ignition event type '" + content + "', ignoring.")); - return; - } - mount.setIgnitionEvent(event); - return; - } - - if (element.equals("ignitiondelay")) { - double d; - try { - d = Double.parseDouble(content); - } catch (NumberFormatException nfe) { - warnings.add(Warning.fromString("Illegal ignition delay specified, ignoring.")); - return; - } - mount.setIgnitionDelay(d); - return; - } - - if (element.equals("overhang")) { - double d; - try { - d = Double.parseDouble(content); - } catch (NumberFormatException nfe) { - warnings.add(Warning.fromString("Illegal overhang specified, ignoring.")); - return; - } - mount.setMotorOverhang(d); - return; - } - - super.closeElement(element, attributes, content, warnings); - } -} - - - - -class MotorConfigurationHandler extends AbstractElementHandler { - @SuppressWarnings("unused") - private final DocumentLoadingContext context; - private final Rocket rocket; - private String name = null; - private boolean inNameElement = false; - - public MotorConfigurationHandler(Rocket rocket, DocumentLoadingContext context) { - this.rocket = rocket; - this.context = context; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (inNameElement || !element.equals("name")) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return null; - } - inNameElement = true; - - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - name = content; - } - - @Override - public void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - String configid = attributes.remove("configid"); - if (configid == null || configid.equals("")) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - if (!rocket.addMotorConfigurationID(configid)) { - warnings.add("Duplicate motor configuration ID used."); - return; - } - - if (name != null && name.trim().length() > 0) { - rocket.setMotorConfigurationName(configid, name); - } - - if ("true".equals(attributes.remove("default"))) { - rocket.getDefaultConfiguration().setMotorConfigurationID(configid); - } - - super.closeElement(element, attributes, content, warnings); - } -} - - -class MotorHandler extends AbstractElementHandler { - /** File version where latest digest format was introduced */ - private static final int MOTOR_DIGEST_VERSION = 104; - - private final DocumentLoadingContext context; - private Motor.Type type = null; - private String manufacturer = null; - private String designation = null; - private String digest = null; - private double diameter = Double.NaN; - private double length = Double.NaN; - private double delay = Double.NaN; - - public MotorHandler(DocumentLoadingContext context) { - this.context = context; - } - - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - - /** - * Return the motor to use, or null. - */ - public Motor getMotor(WarningSet warnings) { - return context.getMotorFinder().findMotor(type, manufacturer, designation, diameter, length, digest, warnings); - } - - /** - * Return the delay to use for the motor. - */ - public double getDelay(WarningSet warnings) { - if (Double.isNaN(delay)) { - warnings.add(Warning.fromString("Motor delay not specified, assuming no ejection charge.")); - return Motor.PLUGGED; - } - return delay; - } - - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - content = content.trim(); - - if (element.equals("type")) { - - // Motor type - type = null; - for (Motor.Type t : Motor.Type.values()) { - if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) { - type = t; - break; - } - } - if (type == null) { - warnings.add(Warning.fromString("Unknown motor type '" + content + "', ignoring.")); - } - - } else if (element.equals("manufacturer")) { - - // Manufacturer - manufacturer = content.trim(); - - } else if (element.equals("designation")) { - - // Designation - designation = content.trim(); - - } else if (element.equals("digest")) { - - // Digest is used only for file versions saved using the same digest algorithm - if (context.getFileVersion() >= MOTOR_DIGEST_VERSION) { - digest = content.trim(); - } - - } else if (element.equals("diameter")) { - - // Diameter - diameter = Double.NaN; - try { - diameter = Double.parseDouble(content.trim()); - } catch (NumberFormatException e) { - // Ignore - } - if (Double.isNaN(diameter)) { - warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring.")); - } - - } else if (element.equals("length")) { - - // Length - length = Double.NaN; - try { - length = Double.parseDouble(content.trim()); - } catch (NumberFormatException ignore) { - } - - if (Double.isNaN(length)) { - warnings.add(Warning.fromString("Illegal motor diameter specified, ignoring.")); - } - - } else if (element.equals("delay")) { - - // Delay - delay = Double.NaN; - if (content.equals("none")) { - delay = Motor.PLUGGED; - } else { - try { - delay = Double.parseDouble(content.trim()); - } catch (NumberFormatException ignore) { - } - - if (Double.isNaN(delay)) { - warnings.add(Warning.fromString("Illegal motor delay specified, ignoring.")); - } - - } - - } else { - super.closeElement(element, attributes, content, warnings); - } - } - -} - - - -class SimulationsHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private final OpenRocketDocument doc; - private SingleSimulationHandler handler; - - public SimulationsHandler(OpenRocketDocument doc, DocumentLoadingContext context) { - this.doc = doc; - this.context = context; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (!element.equals("simulation")) { - warnings.add("Unknown element '" + element + "', ignoring."); - return null; - } - - handler = new SingleSimulationHandler(doc, context); - return handler; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - attributes.remove("status"); - - //Finished loading. Rebuilding custom expressions in case something has changed such as listener variable come available. - for (CustomExpression exp : doc.getCustomExpressions()){ - exp.setExpression(exp.getExpressionString()); - } - - super.closeElement(element, attributes, content, warnings); - } -} - -class SingleSimulationHandler extends AbstractElementHandler { - - private final DocumentLoadingContext context; - - private final OpenRocketDocument doc; - - private String name; - - private SimulationConditionsHandler conditionHandler; - private FlightDataHandler dataHandler; - - private final List listeners = new ArrayList(); - - public SingleSimulationHandler(OpenRocketDocument doc, DocumentLoadingContext context) { - this.doc = doc; - this.context = context; - } - - public OpenRocketDocument getDocument() { - return doc; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (element.equals("name") || element.equals("simulator") || - element.equals("calculator") || element.equals("listener")) { - return PlainTextHandler.INSTANCE; - } else if (element.equals("conditions")) { - conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context); - return conditionHandler; - } else if (element.equals("flightdata")) { - dataHandler = new FlightDataHandler(this, context); - return dataHandler; - } else { - warnings.add("Unknown element '" + element + "', ignoring."); - return null; - } - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - - if (element.equals("name")) { - name = content; - } else if (element.equals("simulator")) { - if (!content.trim().equals("RK4Simulator")) { - warnings.add("Unknown simulator '" + content.trim() + "' specified, ignoring."); - } - } else if (element.equals("calculator")) { - if (!content.trim().equals("BarrowmanCalculator")) { - warnings.add("Unknown calculator '" + content.trim() + "' specified, ignoring."); - } - } else if (element.equals("listener") && content.trim().length() > 0) { - listeners.add(content.trim()); - } - - } - - @Override - public void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) { - - String s = attributes.get("status"); - Simulation.Status status = (Status) DocumentConfig.findEnum(s, Simulation.Status.class); - if (status == null) { - warnings.add("Simulation status unknown, assuming outdated."); - status = Simulation.Status.OUTDATED; - } - - SimulationOptions conditions; - if (conditionHandler != null) { - conditions = conditionHandler.getConditions(); - } else { - warnings.add("Simulation conditions not defined, using defaults."); - conditions = new SimulationOptions(doc.getRocket()); - } - - if (name == null) - name = "Simulation"; - - FlightData data; - if (dataHandler == null) - data = null; - else - data = dataHandler.getFlightData(); - - Simulation simulation = new Simulation(doc.getRocket(), status, name, - conditions, listeners, data); - - doc.addSimulation(simulation); - } -} - -class SimulationConditionsHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - private SimulationOptions conditions; - private AtmosphereHandler atmosphereHandler; - - public SimulationConditionsHandler(Rocket rocket, DocumentLoadingContext context) { - this.context = context; - conditions = new SimulationOptions(rocket); - // Set up default loading settings (which may differ from the new defaults) - conditions.setGeodeticComputation(GeodeticComputationStrategy.FLAT); - } - - public SimulationOptions getConditions() { - return conditions; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - if (element.equals("atmosphere")) { - atmosphereHandler = new AtmosphereHandler(attributes.get("model"), context); - return atmosphereHandler; - } - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - - double d = Double.NaN; - try { - d = Double.parseDouble(content); - } catch (NumberFormatException ignore) { - } - - - if (element.equals("configid")) { - if (content.equals("")) { - conditions.setMotorConfigurationID(null); - } else { - conditions.setMotorConfigurationID(content); - } - } else if (element.equals("launchrodlength")) { - if (Double.isNaN(d)) { - warnings.add("Illegal launch rod length defined, ignoring."); - } else { - conditions.setLaunchRodLength(d); - } - } else if (element.equals("launchrodangle")) { - if (Double.isNaN(d)) { - warnings.add("Illegal launch rod angle defined, ignoring."); - } else { - conditions.setLaunchRodAngle(d * Math.PI / 180); - } - } else if (element.equals("launchroddirection")) { - if (Double.isNaN(d)) { - warnings.add("Illegal launch rod direction defined, ignoring."); - } else { - conditions.setLaunchRodDirection(d * Math.PI / 180); - } - } else if (element.equals("windaverage")) { - if (Double.isNaN(d)) { - warnings.add("Illegal average windspeed defined, ignoring."); - } else { - conditions.setWindSpeedAverage(d); - } - } else if (element.equals("windturbulence")) { - if (Double.isNaN(d)) { - warnings.add("Illegal wind turbulence intensity defined, ignoring."); - } else { - conditions.setWindTurbulenceIntensity(d); - } - } else if (element.equals("launchaltitude")) { - if (Double.isNaN(d)) { - warnings.add("Illegal launch altitude defined, ignoring."); - } else { - conditions.setLaunchAltitude(d); - } - } else if (element.equals("launchlatitude")) { - if (Double.isNaN(d)) { - warnings.add("Illegal launch latitude defined, ignoring."); - } else { - conditions.setLaunchLatitude(d); - } - } else if (element.equals("launchlongitude")) { - if (Double.isNaN(d)) { - warnings.add("Illegal launch longitude."); - } else { - conditions.setLaunchLongitude(d); - } - } else if (element.equals("geodeticmethod")) { - GeodeticComputationStrategy gcs = - (GeodeticComputationStrategy) DocumentConfig.findEnum(content, GeodeticComputationStrategy.class); - if (gcs != null) { - conditions.setGeodeticComputation(gcs); - } else { - warnings.add("Unknown geodetic computation method '" + content + "'"); - } - } else if (element.equals("atmosphere")) { - atmosphereHandler.storeSettings(conditions, warnings); - } else if (element.equals("timestep")) { - if (Double.isNaN(d)) { - warnings.add("Illegal time step defined, ignoring."); - } else { - conditions.setTimeStep(d); - } - } - } -} - - -class AtmosphereHandler extends AbstractElementHandler { - @SuppressWarnings("unused") - private final DocumentLoadingContext context; - private final String model; - private double temperature = Double.NaN; - private double pressure = Double.NaN; - - public AtmosphereHandler(String model, DocumentLoadingContext context) { - this.model = model; - this.context = context; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - double d = Double.NaN; - try { - d = Double.parseDouble(content); - } catch (NumberFormatException ignore) { - } - - if (element.equals("basetemperature")) { - if (Double.isNaN(d)) { - warnings.add("Illegal base temperature specified, ignoring."); - } - temperature = d; - } else if (element.equals("basepressure")) { - if (Double.isNaN(d)) { - warnings.add("Illegal base pressure specified, ignoring."); - } - pressure = d; - } else { - super.closeElement(element, attributes, content, warnings); - } - } - - - public void storeSettings(SimulationOptions cond, WarningSet warnings) { - if (!Double.isNaN(pressure)) { - cond.setLaunchPressure(pressure); - } - if (!Double.isNaN(temperature)) { - cond.setLaunchTemperature(temperature); - } - - if ("isa".equals(model)) { - cond.setISAAtmosphere(true); - } else if ("extendedisa".equals(model)) { - cond.setISAAtmosphere(false); - } else { - cond.setISAAtmosphere(true); - warnings.add("Unknown atmospheric model, using ISA."); - } - } - -} - - -class FlightDataHandler extends AbstractElementHandler { - private final DocumentLoadingContext context; - - private FlightDataBranchHandler dataHandler; - private WarningSet warningSet = new WarningSet(); - private List branches = new ArrayList(); - - private SingleSimulationHandler simHandler; - private FlightData data; - - - public FlightDataHandler(SingleSimulationHandler simHandler, DocumentLoadingContext context) { - this.context = context; - this.simHandler = simHandler; - } - - public FlightData getFlightData() { - return data; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (element.equals("warning")) { - return PlainTextHandler.INSTANCE; - } - if (element.equals("databranch")) { - if (attributes.get("name") == null || attributes.get("types") == null) { - warnings.add("Illegal flight data definition, ignoring."); - return null; - } - dataHandler = new FlightDataBranchHandler(attributes.get("name"), - attributes.get("types"), - simHandler, context); - return dataHandler; - } - - warnings.add("Unknown element '" + element + "' encountered, ignoring."); - return null; - } - - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - - if (element.equals("databranch")) { - FlightDataBranch branch = dataHandler.getBranch(); - if (branch.getLength() > 0) { - branches.add(branch); - } - } else if (element.equals("warning")) { - warningSet.add(Warning.fromString(content)); - } - } - - - @Override - public void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) { - - if (branches.size() > 0) { - data = new FlightData(branches.toArray(new FlightDataBranch[0])); - } else { - double maxAltitude = Double.NaN; - double maxVelocity = Double.NaN; - double maxAcceleration = Double.NaN; - double maxMach = Double.NaN; - double timeToApogee = Double.NaN; - double flightTime = Double.NaN; - double groundHitVelocity = Double.NaN; - double launchRodVelocity = Double.NaN; - double deploymentVelocity = Double.NaN; - - try { - maxAltitude = DocumentConfig.stringToDouble(attributes.get("maxaltitude")); - } catch (NumberFormatException ignore) { - } - try { - maxVelocity = DocumentConfig.stringToDouble(attributes.get("maxvelocity")); - } catch (NumberFormatException ignore) { - } - try { - maxAcceleration = DocumentConfig.stringToDouble(attributes.get("maxacceleration")); - } catch (NumberFormatException ignore) { - } - try { - maxMach = DocumentConfig.stringToDouble(attributes.get("maxmach")); - } catch (NumberFormatException ignore) { - } - try { - timeToApogee = DocumentConfig.stringToDouble(attributes.get("timetoapogee")); - } catch (NumberFormatException ignore) { - } - try { - flightTime = DocumentConfig.stringToDouble(attributes.get("flighttime")); - } catch (NumberFormatException ignore) { - } - try { - groundHitVelocity = - DocumentConfig.stringToDouble(attributes.get("groundhitvelocity")); - } catch (NumberFormatException ignore) { - } - try { - launchRodVelocity = DocumentConfig.stringToDouble(attributes.get("launchrodvelocity")); - } catch (NumberFormatException ignore) { - } - try { - deploymentVelocity = DocumentConfig.stringToDouble(attributes.get("deploymentvelocity")); - } catch (NumberFormatException ignore) { - } - - data = new FlightData(maxAltitude, maxVelocity, maxAcceleration, maxMach, - timeToApogee, flightTime, groundHitVelocity, launchRodVelocity, deploymentVelocity); - } - - data.getWarningSet().addAll(warningSet); - data.immute(); - } - - -} - - -class FlightDataBranchHandler extends AbstractElementHandler { - @SuppressWarnings("unused") - private final DocumentLoadingContext context; - private final FlightDataType[] types; - private final FlightDataBranch branch; - - private static final LogHelper log = Application.getLogger(); - private final SingleSimulationHandler simHandler; - - public FlightDataBranchHandler(String name, String typeList, SingleSimulationHandler simHandler, DocumentLoadingContext context) { - this.simHandler = simHandler; - this.context = context; - String[] split = typeList.split(","); - types = new FlightDataType[split.length]; - for (int i = 0; i < split.length; i++) { - String typeName = split[i]; - FlightDataType matching = findFlightDataType(typeName); - types[i] = matching; - //types[i] = FlightDataType.getType(typeName, matching.getSymbol(), matching.getUnitGroup()); - } - - // TODO: LOW: May throw an IllegalArgumentException - branch = new FlightDataBranch(name, types); - } - - // Find the full flight data type given name only - // Note: this way of doing it requires that custom expressions always come before flight data in the file, - // not the nicest but this is always the case anyway. - private FlightDataType findFlightDataType(String name) { - - // Kevins version with lookup by key. Not using right now - /* - if ( key != null ) { - for (FlightDataType t : FlightDataType.ALL_TYPES){ - if (t.getKey().equals(key) ){ - return t; - } - } - } - */ - - // Look in built in types - for (FlightDataType t : FlightDataType.ALL_TYPES) { - if (t.getName().equals(name)) { - return t; - } - } - - // Look in custom expressions - for (CustomExpression exp : simHandler.getDocument().getCustomExpressions()) { - if (exp.getName().equals(name)) { - return exp.getType(); - } - } - - log.warn("Could not find the flight data type '" + name + "' used in the XML file. Substituted type with unknown symbol and units."); - return FlightDataType.getType(name, "Unknown", UnitGroup.UNITS_NONE); - } - - public FlightDataBranch getBranch() { - branch.immute(); - return branch; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - if (element.equals("datapoint")) - return PlainTextHandler.INSTANCE; - if (element.equals("event")) - return PlainTextHandler.INSTANCE; - - warnings.add("Unknown element '" + element + "' encountered, ignoring."); - return null; - } - - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - - if (element.equals("event")) { - double time; - FlightEvent.Type type; - - try { - time = DocumentConfig.stringToDouble(attributes.get("time")); - } catch (NumberFormatException e) { - warnings.add("Illegal event specification, ignoring."); - return; - } - - type = (Type) DocumentConfig.findEnum(attributes.get("type"), FlightEvent.Type.class); - if (type == null) { - warnings.add("Illegal event specification, ignoring."); - return; - } - - branch.addEvent(new FlightEvent(type, time)); - return; - } - - if (!element.equals("datapoint")) { - warnings.add("Unknown element '" + element + "' encountered, ignoring."); - return; - } - - // element == "datapoint" - - - // Check line format - String[] split = content.split(","); - if (split.length != types.length) { - warnings.add("Data point did not contain correct amount of values, ignoring point."); - return; - } - - // Parse the doubles - double[] values = new double[split.length]; - for (int i = 0; i < values.length; i++) { - try { - values[i] = DocumentConfig.stringToDouble(split[i]); - } catch (NumberFormatException e) { - warnings.add("Data point format error, ignoring point."); - return; - } - } - - // Add point to branch - branch.addPoint(); - for (int i = 0; i < types.length; i++) { - branch.setValue(types[i], values[i]); - } - } -} - - - - - -///////////////// Setters implementation - - -//// Interface -interface Setter { - /** - * Set the specified value to the given component. - * - * @param component the component to which to set. - * @param value the value within the element. - * @param attributes attributes for the element. - * @param warnings the warning set to use. - */ - public void set(RocketComponent component, String value, - HashMap attributes, WarningSet warnings); -} - - -//// StringSetter - sets the value to the contained String -class StringSetter implements Setter { - private final Reflection.Method setMethod; - - public StringSetter(Reflection.Method set) { - setMethod = set; - } - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - setMethod.invoke(c, s); - } -} - -//// IntSetter - set an integer value -class IntSetter implements Setter { - private final Reflection.Method setMethod; - - public IntSetter(Reflection.Method set) { - setMethod = set; - } - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - try { - int n = Integer.parseInt(s); - setMethod.invoke(c, n); - } catch (NumberFormatException e) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - } - } -} - - -//// BooleanSetter - set a boolean value -class BooleanSetter implements Setter { - private final Reflection.Method setMethod; - - public BooleanSetter(Reflection.Method set) { - setMethod = set; - } - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - - s = s.trim(); - if (s.equalsIgnoreCase("true")) { - setMethod.invoke(c, true); - } else if (s.equalsIgnoreCase("false")) { - setMethod.invoke(c, false); - } else { - warnings.add(Warning.FILE_INVALID_PARAMETER); - } - } -} - - - -//// DoubleSetter - sets a double value or (alternatively) if a specific string is encountered -//// calls a setXXX(boolean) method. -class DoubleSetter implements Setter { - private final Reflection.Method setMethod; - private final String specialString; - private final Reflection.Method specialMethod; - private final double multiplier; - - /** - * Set only the double value. - * @param set set method for the double value. - */ - public DoubleSetter(Reflection.Method set) { - this.setMethod = set; - this.specialString = null; - this.specialMethod = null; - this.multiplier = 1.0; - } - - /** - * Multiply with the given multiplier and set the double value. - * @param set set method for the double value. - * @param mul multiplier. - */ - public DoubleSetter(Reflection.Method set, double mul) { - this.setMethod = set; - this.specialString = null; - this.specialMethod = null; - this.multiplier = mul; - } - - /** - * Set the double value, or if the value equals the special string, use the - * special setter and set it to true. - * - * @param set double setter. - * @param special special string - * @param specialMethod boolean setter. - */ - public DoubleSetter(Reflection.Method set, String special, - Reflection.Method specialMethod) { - this.setMethod = set; - this.specialString = special; - this.specialMethod = specialMethod; - this.multiplier = 1.0; - } - - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - - s = s.trim(); - - // Check for special case - if (specialMethod != null && s.equalsIgnoreCase(specialString)) { - specialMethod.invoke(c, true); - return; - } - - // Normal case - try { - double d = Double.parseDouble(s); - setMethod.invoke(c, d * multiplier); - } catch (NumberFormatException e) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - } - } -} - - -class OverrideSetter implements Setter { - private final Reflection.Method setMethod; - private final Reflection.Method enabledMethod; - - public OverrideSetter(Reflection.Method set, Reflection.Method enabledMethod) { - this.setMethod = set; - this.enabledMethod = enabledMethod; - } - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - - try { - double d = Double.parseDouble(s); - setMethod.invoke(c, d); - enabledMethod.invoke(c, true); - } catch (NumberFormatException e) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - } - } -} - -//// EnumSetter - sets a generic enum type -class EnumSetter> implements Setter { - private final Reflection.Method setter; - private final Class enumClass; - - public EnumSetter(Reflection.Method set, Class enumClass) { - this.setter = set; - this.enumClass = enumClass; - } - - @Override - public void set(RocketComponent c, String name, HashMap attributes, - WarningSet warnings) { - - Enum setEnum = DocumentConfig.findEnum(name, enumClass); - if (setEnum == null) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - setter.invoke(c, setEnum); - } -} - - -//// ColorSetter - sets a Color value -class ColorSetter implements Setter { - private final Reflection.Method setMethod; - - public ColorSetter(Reflection.Method set) { - setMethod = set; - } - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - - String red = attributes.get("red"); - String green = attributes.get("green"); - String blue = attributes.get("blue"); - - if (red == null || green == null || blue == null) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - int r, g, b; - try { - r = Integer.parseInt(red); - g = Integer.parseInt(green); - b = Integer.parseInt(blue); - } catch (NumberFormatException e) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - if (r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - Color color = new Color(r, g, b); - setMethod.invoke(c, color); - - if (!s.trim().equals("")) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - } - } -} - -////ComponentPresetSetter - sets a ComponentPreset value -class ComponentPresetSetter implements Setter { - private final Reflection.Method setMethod; - - public ComponentPresetSetter(Reflection.Method set) { - this.setMethod = set; - } - - @Override - public void set(RocketComponent c, String name, HashMap attributes, - WarningSet warnings) { - String manufacturerName = attributes.get("manufacturer"); - if (manufacturerName == null) { - warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no manufacturer specified. Ignored")); - return; - } - - String productNo = attributes.get("partno"); - if (productNo == null) { - warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no partno specified. Ignored")); - return; - } - - String digest = attributes.get("digest"); - if (digest == null) { - warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no digest specified.")); - } - - String type = attributes.get("type"); - if (type == null) { - warnings.add(Warning.fromString("Invalid ComponentPreset for component " + c.getName() + ", no type specified.")); - } - - List presets = Application.getComponentPresetDao().find(manufacturerName, productNo); - - ComponentPreset matchingPreset = null; - - for (ComponentPreset preset : presets) { - if (digest != null && preset.getDigest().equals(digest)) { - // Found one with matching digest. Take it. - matchingPreset = preset; - break; - } - if (type != null && preset.getType().name().equals(type) && matchingPreset != null) { - // Found the first one with matching type. - matchingPreset = preset; - } - } - - // Was any found? - if (matchingPreset == null) { - warnings.add(Warning.fromString("No matching ComponentPreset for component " + c.getName() + " found matching " + manufacturerName + " " + productNo)); - return; - } - - if (digest != null && !matchingPreset.getDigest().equals(digest)) { - warnings.add(Warning.fromString("ComponentPreset for component " + c.getName() + " has wrong digest")); - } - - setMethod.invoke(c, matchingPreset); - } -} - - -////MaterialSetter - sets a Material value -class MaterialSetter implements Setter { - private final Reflection.Method setMethod; - private final Material.Type type; - - public MaterialSetter(Reflection.Method set, Material.Type type) { - this.setMethod = set; - this.type = type; - } - - @Override - public void set(RocketComponent c, String name, HashMap attributes, - WarningSet warnings) { - - Material mat; - - // Check name != "" - name = name.trim(); - if (name.equals("")) { - warnings.add(Warning.fromString("Illegal material specification, ignoring.")); - return; - } - - // Parse density - double density; - String str; - str = attributes.remove("density"); - if (str == null) { - warnings.add(Warning.fromString("Illegal material specification, ignoring.")); - return; - } - try { - density = Double.parseDouble(str); - } catch (NumberFormatException e) { - warnings.add(Warning.fromString("Illegal material specification, ignoring.")); - return; - } - - // Parse thickness - // double thickness = 0; - // str = attributes.remove("thickness"); - // try { - // if (str != null) - // thickness = Double.parseDouble(str); - // } catch (NumberFormatException e){ - // warnings.add(Warning.fromString("Illegal material specification, ignoring.")); - // return; - // } - - // Check type if specified - str = attributes.remove("type"); - if (str != null && !type.name().toLowerCase(Locale.ENGLISH).equals(str)) { - warnings.add(Warning.fromString("Illegal material type specified, ignoring.")); - return; - } - - mat = Databases.findMaterial(type, name, density); - - setMethod.invoke(c, mat); - } -} - - - - - -class PositionSetter implements Setter { - - @Override - public void set(RocketComponent c, String value, HashMap attributes, - WarningSet warnings) { - - RocketComponent.Position type = (Position) DocumentConfig.findEnum(attributes.get("type"), - RocketComponent.Position.class); - if (type == null) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - double pos; - try { - pos = Double.parseDouble(value); - } catch (NumberFormatException e) { - warnings.add(Warning.FILE_INVALID_PARAMETER); - return; - } - - if (c instanceof FinSet) { - ((FinSet) c).setRelativePosition(type); - c.setPositionValue(pos); - } else if (c instanceof LaunchLug) { - ((LaunchLug) c).setRelativePosition(type); - c.setPositionValue(pos); - } else if (c instanceof InternalComponent) { - ((InternalComponent) c).setRelativePosition(type); - c.setPositionValue(pos); - } else { - warnings.add(Warning.FILE_INVALID_PARAMETER); - } - - } -} - - -class FinTabPositionSetter extends DoubleSetter { - - public FinTabPositionSetter() { - super(Reflection.findMethod(FinSet.class, "setTabShift", double.class)); - } - - @Override - public void set(RocketComponent c, String s, HashMap attributes, - WarningSet warnings) { - - if (!(c instanceof FinSet)) { - throw new IllegalStateException("FinTabPositionSetter called for component " + c); - } - - String relative = attributes.get("relativeto"); - FinSet.TabRelativePosition position = - (TabRelativePosition) DocumentConfig.findEnum(relative, - FinSet.TabRelativePosition.class); - - if (position != null) { - - ((FinSet) c).setTabRelativePosition(position); - - } else { - if (relative == null) { - warnings.add("Required attribute 'relativeto' not found for fin tab position."); - } else { - warnings.add("Illegal attribute value '" + relative + "' encountered."); - } - } - - super.set(c, s, attributes, warnings); - } - - -} - - -class ClusterConfigurationSetter implements Setter { - - @Override - public void set(RocketComponent component, String value, HashMap attributes, - WarningSet warnings) { - - if (!(component instanceof Clusterable)) { - warnings.add("Illegal component defined as cluster."); - return; - } - - ClusterConfiguration config = null; - for (ClusterConfiguration c : ClusterConfiguration.CONFIGURATIONS) { - if (c.getXMLName().equals(value)) { - config = c; - break; - } - } - - if (config == null) { - warnings.add("Illegal cluster configuration specified."); - return; - } - - ((Clusterable) component).setClusterConfiguration(config); - } -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/BodyComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/BodyComponentSaver.java deleted file mode 100644 index 1a65676b..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/BodyComponentSaver.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -public class BodyComponentSaver extends ExternalComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - // Body components have a natural length, store it now - elements.add(""+((net.sf.openrocket.rocketcomponent.BodyComponent)c).getLength()+""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/BodyTubeSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/BodyTubeSaver.java deleted file mode 100644 index 8b1ef6a5..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/BodyTubeSaver.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class BodyTubeSaver extends SymmetricComponentSaver { - - private static final BodyTubeSaver instance = new BodyTubeSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - net.sf.openrocket.rocketcomponent.BodyTube tube = (net.sf.openrocket.rocketcomponent.BodyTube) c; - - if (tube.isOuterRadiusAutomatic()) - elements.add("auto"); - else - elements.add("" + tube.getOuterRadius() + ""); - - if (tube.isMotorMount()) { - elements.addAll(motorMountParams(tube)); - } - } - - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/BulkheadSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/BulkheadSaver.java deleted file mode 100644 index 9c0ef2d8..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/BulkheadSaver.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class BulkheadSaver extends RadiusRingComponentSaver { - - private static final BulkheadSaver instance = new BulkheadSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/CenteringRingSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/CenteringRingSaver.java deleted file mode 100644 index bb428a3d..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/CenteringRingSaver.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class CenteringRingSaver extends RadiusRingComponentSaver { - - private static final CenteringRingSaver instance = new CenteringRingSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/ComponentAssemblySaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/ComponentAssemblySaver.java deleted file mode 100644 index 9e9d609d..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/ComponentAssemblySaver.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -public class ComponentAssemblySaver extends RocketComponentSaver { - - // No-op - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/EllipticalFinSetSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/EllipticalFinSetSaver.java deleted file mode 100644 index 31b9dfb0..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/EllipticalFinSetSaver.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class EllipticalFinSetSaver extends FinSetSaver { - - private static final EllipticalFinSetSaver instance = new EllipticalFinSetSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c,list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - net.sf.openrocket.rocketcomponent.EllipticalFinSet fins = (net.sf.openrocket.rocketcomponent.EllipticalFinSet)c; - elements.add(""+fins.getLength()+""); - elements.add(""+fins.getHeight()+""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/EngineBlockSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/EngineBlockSaver.java deleted file mode 100644 index 921ddde5..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/EngineBlockSaver.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class EngineBlockSaver extends ThicknessRingComponentSaver { - - private static final EngineBlockSaver instance = new EngineBlockSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java deleted file mode 100644 index 5415832a..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.rocketcomponent.ExternalComponent; - - -public class ExternalComponentSaver extends RocketComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - ExternalComponent ext = (ExternalComponent) c; - - // Finish enum names are currently the same except for case - elements.add("" + ext.getFinish().name().toLowerCase(Locale.ENGLISH) + ""); - - // Material - elements.add(materialParam(ext.getMaterial())); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/FinSetSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/FinSetSaver.java deleted file mode 100644 index 7eaffc69..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/FinSetSaver.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.util.MathUtil; - -public class FinSetSaver extends ExternalComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - net.sf.openrocket.rocketcomponent.FinSet fins = (net.sf.openrocket.rocketcomponent.FinSet) c; - elements.add("" + fins.getFinCount() + ""); - elements.add("" + (fins.getBaseRotation() * 180.0 / Math.PI) + ""); - elements.add("" + fins.getThickness() + ""); - elements.add("" + fins.getCrossSection().name().toLowerCase(Locale.ENGLISH) - + ""); - elements.add("" + (fins.getCantAngle() * 180.0 / Math.PI) + ""); - - // Save fin tabs only if they exist (compatibility with file version < 1.1) - if (!MathUtil.equals(fins.getTabHeight(), 0) && - !MathUtil.equals(fins.getTabLength(), 0)) { - - elements.add("" + fins.getTabHeight() + ""); - elements.add("" + fins.getTabLength() + ""); - elements.add("" + - fins.getTabShift() + ""); - - } - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/FreeformFinSetSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/FreeformFinSetSaver.java deleted file mode 100644 index c310e4d9..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/FreeformFinSetSaver.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.util.Coordinate; - - -public class FreeformFinSetSaver extends FinSetSaver { - - private static final FreeformFinSetSaver instance = new FreeformFinSetSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c,list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - FreeformFinSet fins = (FreeformFinSet)c; - elements.add(""); - for (Coordinate p: fins.getFinPoints()) { - elements.add(" "); - } - elements.add(""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/InnerTubeSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/InnerTubeSaver.java deleted file mode 100644 index 7eb0a538..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/InnerTubeSaver.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.rocketcomponent.InnerTube; - - -public class InnerTubeSaver extends ThicknessRingComponentSaver { - - private static final InnerTubeSaver instance = new InnerTubeSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - InnerTube tube = (InnerTube) c; - - elements.add("" + tube.getClusterConfiguration().getXMLName() - + ""); - elements.add("" + tube.getClusterScale() + ""); - elements.add("" + (tube.getClusterRotation() * 180.0 / Math.PI) - + ""); - - if (tube.isMotorMount()) { - elements.addAll(motorMountParams(tube)); - } - - - } - - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/InternalComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/InternalComponentSaver.java deleted file mode 100644 index 0a2dbe72..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/InternalComponentSaver.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -public class InternalComponentSaver extends RocketComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - // Nothing to save - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/LaunchLugSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/LaunchLugSaver.java deleted file mode 100644 index 1598bc41..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/LaunchLugSaver.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import net.sf.openrocket.rocketcomponent.LaunchLug; - -import java.util.ArrayList; -import java.util.List; - - -public class LaunchLugSaver extends ExternalComponentSaver { - - private static final LaunchLugSaver instance = new LaunchLugSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - LaunchLug lug = (LaunchLug) c; - - elements.add("" + lug.getOuterRadius() + ""); - elements.add("" + lug.getLength() + ""); - elements.add("" + lug.getThickness() + ""); - elements.add("" + (lug.getRadialDirection()*180.0/Math.PI) + ""); - } - - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/MassComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/MassComponentSaver.java deleted file mode 100644 index 093303c2..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/MassComponentSaver.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.rocketcomponent.MassComponent; - - -public class MassComponentSaver extends MassObjectSaver { - - private static final MassComponentSaver instance = new MassComponentSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - MassComponent mass = (MassComponent) c; - - elements.add("" + mass.getMass() + ""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/MassObjectSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/MassObjectSaver.java deleted file mode 100644 index 298cb263..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/MassObjectSaver.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -import net.sf.openrocket.rocketcomponent.MassObject; - - -public class MassObjectSaver extends InternalComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - MassObject mass = (MassObject) c; - - elements.add("" + mass.getLength() + ""); - elements.add("" + mass.getRadius() + ""); - elements.add("" + mass.getRadialPosition() + ""); - elements.add("" + (mass.getRadialDirection() * 180.0 / Math.PI) - + ""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/NoseConeSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/NoseConeSaver.java deleted file mode 100644 index 9733254f..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/NoseConeSaver.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class NoseConeSaver extends TransitionSaver { - - private static final NoseConeSaver instance = new NoseConeSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c,list); - list.add(""); - - return list; - } - - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - // Transition handles nose cone saving as well - } -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/ParachuteSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/ParachuteSaver.java deleted file mode 100644 index 7d906e67..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/ParachuteSaver.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.rocketcomponent.Parachute; - - -public class ParachuteSaver extends RecoveryDeviceSaver { - - private static final ParachuteSaver instance = new ParachuteSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - Parachute para = (Parachute) c; - - elements.add("" + para.getDiameter() + ""); - elements.add("" + para.getLineCount() + ""); - elements.add("" + para.getLineLength() + ""); - elements.add(materialParam("linematerial", para.getLineMaterial())); - } - - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RadiusRingComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RadiusRingComponentSaver.java deleted file mode 100644 index c1b90204..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RadiusRingComponentSaver.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.RadiusRingComponent; - - -public class RadiusRingComponentSaver extends RingComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - RadiusRingComponent comp = (RadiusRingComponent)c; - if (comp.isOuterRadiusAutomatic()) - elements.add("auto"); - else - elements.add("" + comp.getOuterRadius() + ""); - if (!(comp instanceof Bulkhead)) { - if (comp.isInnerRadiusAutomatic()) - elements.add("auto"); - else - elements.add("" + comp.getInnerRadius() + ""); - } - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java deleted file mode 100644 index a73d8fd6..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.rocketcomponent.RecoveryDevice; - - -public class RecoveryDeviceSaver extends MassObjectSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - RecoveryDevice dev = (RecoveryDevice) c; - - if (dev.isCDAutomatic()) - elements.add("auto"); - else - elements.add("" + dev.getCD() + ""); - - elements.add("" + dev.getDeployEvent().name().toLowerCase(Locale.ENGLISH).replace("_", "") + ""); - elements.add("" + dev.getDeployAltitude() + ""); - elements.add("" + dev.getDeployDelay() + ""); - elements.add(materialParam(dev.getMaterial())); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RingComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RingComponentSaver.java deleted file mode 100644 index c1999fba..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RingComponentSaver.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -import net.sf.openrocket.rocketcomponent.RingComponent; - - -public class RingComponentSaver extends StructuralComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - RingComponent ring = (RingComponent) c; - - elements.add("" + ring.getLength() + ""); - elements.add("" + ring.getRadialPosition() + ""); - elements.add("" + (ring.getRadialDirection() * 180.0 / Math.PI) - + ""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RocketComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RocketComponentSaver.java deleted file mode 100644 index a4892902..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RocketComponentSaver.java +++ /dev/null @@ -1,172 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.ComponentAssembly; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Color; -import net.sf.openrocket.util.LineStyle; - - -public class RocketComponentSaver { - private static final Translator trans = Application.getTranslator(); - - protected RocketComponentSaver() { - // Prevent instantiation from outside the package - } - - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - elements.add("" + RocketSaver.escapeXML(c.getName()) + ""); - - ComponentPreset preset = c.getPresetComponent(); - if (preset != null) { - elements.add(""); - } - - - // Save color and line style if significant - if (!(c instanceof Rocket || c instanceof ComponentAssembly)) { - Color color = c.getColor(); - if (color != null) { - elements.add(""); - } - - LineStyle style = c.getLineStyle(); - if (style != null) { - // Type names currently equivalent to the enum names except for case. - elements.add("" + style.name().toLowerCase(Locale.ENGLISH) + ""); - } - } - - - // Save position unless "AFTER" - if (c.getRelativePosition() != RocketComponent.Position.AFTER) { - // The type names are currently equivalent to the enum names except for case. - String type = c.getRelativePosition().name().toLowerCase(Locale.ENGLISH); - elements.add("" + c.getPositionValue() + ""); - } - - - // Overrides - boolean overridden = false; - if (c.isMassOverridden()) { - elements.add("" + c.getOverrideMass() + ""); - overridden = true; - } - if (c.isCGOverridden()) { - elements.add("" + c.getOverrideCGX() + ""); - overridden = true; - } - if (overridden) { - elements.add("" + c.getOverrideSubcomponents() - + ""); - } - - - // Comment - if (c.getComment().length() > 0) { - elements.add("" + RocketSaver.escapeXML(c.getComment()) + ""); - } - - } - - - - - protected final String materialParam(Material mat) { - return materialParam("material", mat); - } - - - protected final String materialParam(String tag, Material mat) { - String str = "<" + tag; - - switch (mat.getType()) { - case LINE: - str += " type=\"line\""; - break; - case SURFACE: - str += " type=\"surface\""; - break; - case BULK: - str += " type=\"bulk\""; - break; - default: - throw new BugException("Unknown material type: " + mat.getType()); - } - - String baseName = trans.getBaseText("material", mat.getName()); - - return str + " density=\"" + mat.getDensity() + "\">" + RocketSaver.escapeXML(baseName) + ""; - } - - - protected final List motorMountParams(MotorMount mount) { - if (!mount.isMotorMount()) - return Collections.emptyList(); - - String[] motorConfigIDs = ((RocketComponent) mount).getRocket().getMotorConfigurationIDs(); - List elements = new ArrayList(); - - elements.add(""); - - for (String id : motorConfigIDs) { - Motor motor = mount.getMotor(id); - - // Nothing is stored if no motor loaded - if (motor == null) - continue; - - elements.add(" "); - if (motor.getMotorType() != Motor.Type.UNKNOWN) { - elements.add(" " + motor.getMotorType().name().toLowerCase(Locale.ENGLISH) + ""); - } - if (motor instanceof ThrustCurveMotor) { - ThrustCurveMotor m = (ThrustCurveMotor) motor; - elements.add(" " + RocketSaver.escapeXML(m.getManufacturer().getSimpleName()) + - ""); - elements.add(" " + m.getDigest() + ""); - } - elements.add(" " + RocketSaver.escapeXML(motor.getDesignation()) + ""); - elements.add(" " + motor.getDiameter() + ""); - elements.add(" " + motor.getLength() + ""); - - // Motor delay - if (mount.getMotorDelay(id) == Motor.PLUGGED) { - elements.add(" none"); - } else { - elements.add(" " + mount.getMotorDelay(id) + ""); - } - - elements.add(" "); - } - - elements.add(" " - + mount.getIgnitionEvent().name().toLowerCase(Locale.ENGLISH).replace("_", "") - + ""); - - elements.add(" " + mount.getIgnitionDelay() + ""); - elements.add(" " + mount.getMotorOverhang() + ""); - - elements.add(""); - - return elements; - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java deleted file mode 100644 index be7c52af..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.rocketcomponent.ReferenceType; -import net.sf.openrocket.rocketcomponent.Rocket; - -public class RocketSaver extends RocketComponentSaver { - - private static final RocketSaver instance = new RocketSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - Rocket rocket = (Rocket) c; - - if (rocket.getDesigner().length() > 0) { - elements.add("" - + net.sf.openrocket.file.RocketSaver.escapeXML(rocket.getDesigner()) - + ""); - } - if (rocket.getRevision().length() > 0) { - elements.add("" - + net.sf.openrocket.file.RocketSaver.escapeXML(rocket.getRevision()) - + ""); - } - - - // Motor configurations - String defId = rocket.getDefaultConfiguration().getMotorConfigurationID(); - for (String id : rocket.getMotorConfigurationIDs()) { - if (id == null) - continue; - - String str = ""; - } - elements.add(str); - } - - // Reference diameter - elements.add("" + rocket.getReferenceType().name().toLowerCase(Locale.ENGLISH) - + ""); - if (rocket.getReferenceType() == ReferenceType.CUSTOM) { - elements.add("" + rocket.getCustomReferenceLength() - + ""); - } - - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/ShockCordSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/ShockCordSaver.java deleted file mode 100644 index 8b8ae01f..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/ShockCordSaver.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.rocketcomponent.ShockCord; - - -public class ShockCordSaver extends MassObjectSaver { - - private static final ShockCordSaver instance = new ShockCordSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - ShockCord mass = (ShockCord) c; - - elements.add("" + mass.getCordLength() + ""); - elements.add(materialParam(mass.getMaterial())); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/StageSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/StageSaver.java deleted file mode 100644 index 23f591f3..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/StageSaver.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; - -public class StageSaver extends ComponentAssemblySaver { - - private static final StageSaver instance = new StageSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(RocketComponent c, List elements) { - super.addParams(c, elements); - Stage stage = (Stage) c; - - if (stage.getStageNumber() > 0) { - elements.add("" - + stage.getSeparationEvent().name().toLowerCase(Locale.ENGLISH).replace("_", "") - + ""); - elements.add("" + stage.getSeparationDelay() + ""); - } - } -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/StreamerSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/StreamerSaver.java deleted file mode 100644 index 5b92852e..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/StreamerSaver.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.rocketcomponent.Streamer; - - -public class StreamerSaver extends RecoveryDeviceSaver { - - private static final StreamerSaver instance = new StreamerSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - Streamer st = (Streamer) c; - - elements.add("" + st.getStripLength() + ""); - elements.add("" + st.getStripWidth() + ""); - } - - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/StructuralComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/StructuralComponentSaver.java deleted file mode 100644 index 5cf5ce70..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/StructuralComponentSaver.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -import net.sf.openrocket.rocketcomponent.StructuralComponent; - - -public class StructuralComponentSaver extends InternalComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - StructuralComponent comp = (StructuralComponent)c; - elements.add(materialParam(comp.getMaterial())); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/SymmetricComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/SymmetricComponentSaver.java deleted file mode 100644 index bab5eccb..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/SymmetricComponentSaver.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -public class SymmetricComponentSaver extends BodyComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - net.sf.openrocket.rocketcomponent.SymmetricComponent comp = (net.sf.openrocket.rocketcomponent.SymmetricComponent)c; - if (comp.isFilled()) - elements.add("filled"); - else - elements.add(""+comp.getThickness()+""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/ThicknessRingComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/ThicknessRingComponentSaver.java deleted file mode 100644 index d5a3c1b3..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/ThicknessRingComponentSaver.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.List; - -import net.sf.openrocket.rocketcomponent.ThicknessRingComponent; - - -public class ThicknessRingComponentSaver extends RingComponentSaver { - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - ThicknessRingComponent comp = (ThicknessRingComponent)c; - if (comp.isOuterRadiusAutomatic()) - elements.add("auto"); - else - elements.add("" + comp.getOuterRadius() + ""); - elements.add("" + comp.getThickness() + ""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java deleted file mode 100644 index 0a4169f9..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Transition; - - -public class TransitionSaver extends SymmetricComponentSaver { - - private static final TransitionSaver instance = new TransitionSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - - - /* - * Note: This method must be capable of handling nose cones as well. - */ - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - net.sf.openrocket.rocketcomponent.Transition trans = (net.sf.openrocket.rocketcomponent.Transition) c; - boolean nosecone = (trans instanceof NoseCone); - - - Transition.Shape shape = trans.getType(); - elements.add("" + shape.name().toLowerCase(Locale.ENGLISH) + ""); - if (shape.isClippable()) { - elements.add("" + trans.isClipped() + ""); - } - if (shape.usesParameter()) { - elements.add("" + trans.getShapeParameter() + ""); - } - - - if (!nosecone) { - if (trans.isForeRadiusAutomatic()) - elements.add("auto"); - else - elements.add("" + trans.getForeRadius() + ""); - } - - if (trans.isAftRadiusAutomatic()) - elements.add("auto"); - else - elements.add("" + trans.getAftRadius() + ""); - - - if (!nosecone) { - elements.add("" + trans.getForeShoulderRadius() - + ""); - elements.add("" + trans.getForeShoulderLength() - + ""); - elements.add("" + trans.getForeShoulderThickness() - + ""); - elements.add("" + trans.isForeShoulderCapped() - + ""); - } - - elements.add("" + trans.getAftShoulderRadius() - + ""); - elements.add("" + trans.getAftShoulderLength() - + ""); - elements.add("" + trans.getAftShoulderThickness() - + ""); - elements.add("" + trans.isAftShoulderCapped() - + ""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/TrapezoidFinSetSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/TrapezoidFinSetSaver.java deleted file mode 100644 index 21ac2aa8..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/TrapezoidFinSetSaver.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class TrapezoidFinSetSaver extends FinSetSaver { - - private static final TrapezoidFinSetSaver instance = new TrapezoidFinSetSaver(); - - public static ArrayList getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - ArrayList list = new ArrayList(); - - list.add(""); - instance.addParams(c,list); - list.add(""); - - return list; - } - - @Override - protected void addParams(net.sf.openrocket.rocketcomponent.RocketComponent c, List elements) { - super.addParams(c, elements); - - net.sf.openrocket.rocketcomponent.TrapezoidFinSet fins = (net.sf.openrocket.rocketcomponent.TrapezoidFinSet)c; - elements.add(""+fins.getRootChord()+""); - elements.add(""+fins.getTipChord()+""); - elements.add(""+fins.getSweep()+""); - elements.add(""+fins.getHeight()+""); - } - -} diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/TubeCouplerSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/TubeCouplerSaver.java deleted file mode 100644 index 0e19fd8d..00000000 --- a/core/src/net/sf/openrocket/file/openrocket/savers/TubeCouplerSaver.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.file.openrocket.savers; - -import java.util.ArrayList; -import java.util.List; - -public class TubeCouplerSaver extends ThicknessRingComponentSaver { - - private static final TubeCouplerSaver instance = new TubeCouplerSaver(); - - public static List getElements(net.sf.openrocket.rocketcomponent.RocketComponent c) { - List list = new ArrayList(); - - list.add(""); - instance.addParams(c, list); - list.add(""); - - return list; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java b/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java deleted file mode 100644 index 431db265..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.sf.openrocket.file.rocksim; - -/** - */ -public class RocksimCommonConstants { - - public static final String SHAPE_CODE = "ShapeCode"; - public static final String CONSTRUCTION_TYPE = "ConstructionType"; - public static final String WALL_THICKNESS = "WallThickness"; - public static final String SHAPE_PARAMETER = "ShapeParameter"; - public static final String ATTACHED_PARTS = "AttachedParts"; - public static final String BODY_TUBE = "BodyTube"; - public static final String FIN_SET = "FinSet"; - public static final String CUSTOM_FIN_SET = "CustomFinSet"; - public static final String RING = "Ring"; - public static final String STREAMER = "Streamer"; - public static final String PARACHUTE = "Parachute"; - public static final String MASS_OBJECT = "MassObject"; - public static final String KNOWN_MASS = "KnownMass"; - public static final String DENSITY = "Density"; - public static final String MATERIAL = "Material"; - public static final String NAME = "Name"; - public static final String KNOWN_CG = "KnownCG"; - public static final String USE_KNOWN_CG = "UseKnownCG"; - public static final String XB = "Xb"; - public static final String CALC_MASS = "CalcMass"; - public static final String CALC_CG = "CalcCG"; - public static final String DENSITY_TYPE = "DensityType"; - public static final String RADIAL_LOC = "RadialLoc"; - public static final String RADIAL_ANGLE = "RadialAngle"; - public static final String LOCATION_MODE = "LocationMode"; - public static final String FINISH_CODE = "FinishCode"; - public static final String SERIAL_NUMBER = "SerialNo"; - public static final String LEN = "Len"; - public static final String OD = "OD"; - public static final String ID = "ID"; - public static final String IS_MOTOR_MOUNT = "IsMotorMount"; - public static final String MOTOR_DIA = "MotorDia"; - public static final String ENGINE_OVERHANG = "EngineOverhang"; - public static final String IS_INSIDE_TUBE = "IsInsideTube"; - public static final String LAUNCH_LUG = "LaunchLug"; - public static final String USAGE_CODE = "UsageCode"; - public static final String AUTO_SIZE = "AutoSize"; - public static final String POINT_LIST = "PointList"; - public static final String FIN_COUNT = "FinCount"; - public static final String ROOT_CHORD = "RootChord"; - public static final String TIP_CHORD = "TipChord"; - public static final String SEMI_SPAN = "SemiSpan"; - public static final String SWEEP_DISTANCE = "SweepDistance"; - public static final String THICKNESS = "Thickness"; - public static final String TIP_SHAPE_CODE = "TipShapeCode"; - public static final String TAB_LENGTH = "TabLength"; - public static final String TAB_DEPTH = "TabDepth"; - public static final String TAB_OFFSET = "TabOffset"; - public static final String SWEEP_MODE = "SweepMode"; - public static final String CANT_ANGLE = "CantAngle"; - public static final String TYPE_CODE = "TypeCode"; - public static final String NOSE_CONE = "NoseCone"; - public static final String BASE_DIA = "BaseDia"; - public static final String SHOULDER_LEN = "ShoulderLen"; - public static final String SHOULDER_OD = "ShoulderOD"; - public static final String DIAMETER = "Dia"; - public static final String SPILL_HOLE_DIA = "SpillHoleDia"; - public static final String SHROUD_LINE_COUNT = "ShroudLineCount"; - public static final String SHROUD_LINE_LEN = "ShroudLineLen"; - public static final String CHUTE_COUNT = "ChuteCount"; - public static final String SHROUD_LINE_MASS_PER_MM = "ShroudLineMassPerMM"; - public static final String SHROUD_LINE_MATERIAL = "ShroudLineMaterial"; - public static final String DRAG_COEFFICIENT = "DragCoefficient"; - public static final String ROCKET_DESIGN = "RocketDesign"; - public static final String TRANSITION = "Transition"; - public static final String WIDTH = "Width"; - public static final String FRONT_SHOULDER_LEN = "FrontShoulderLen"; - public static final String REAR_SHOULDER_LEN = "RearShoulderLen"; - public static final String FRONT_SHOULDER_DIA = "FrontShoulderDia"; - public static final String REAR_SHOULDER_DIA = "RearShoulderDia"; - public static final String FRONT_DIA = "FrontDia"; - public static final String REAR_DIA = "RearDia"; - public static final String ROCK_SIM_DOCUMENT = "RockSimDocument"; - public static final String FILE_VERSION = "FileVersion"; - public static final String DESIGN_INFORMATION = "DesignInformation"; - public static final String TUBE_FIN_SET = "TubeFinSet"; - public static final String RING_TAIL = "RingTail"; - public static final String EXTERNAL_POD = "ExternalPod"; - - /** - * Length conversion. Rocksim is in millimeters, OpenRocket in meters. - */ - public static final int ROCKSIM_TO_OPENROCKET_LENGTH = 1000; - /** - * Mass conversion. Rocksim is in grams, OpenRocket in kilograms. - */ - public static final int ROCKSIM_TO_OPENROCKET_MASS = 1000; - /** - * Bulk Density conversion. Rocksim is in kilograms/cubic meter, OpenRocket in kilograms/cubic meter. - */ - public static final int ROCKSIM_TO_OPENROCKET_BULK_DENSITY = 1; - /** - * Surface Density conversion. Rocksim is in grams/sq centimeter, OpenRocket in kilograms/sq meter. 1000/(100*100) = 1/10 - */ - public static final double ROCKSIM_TO_OPENROCKET_SURFACE_DENSITY = 1/10d; - /** - * Line Density conversion. Rocksim is in kilograms/meter, OpenRocket in kilograms/meter. - */ - public static final int ROCKSIM_TO_OPENROCKET_LINE_DENSITY = 1; - /** - * Radius conversion. Rocksim is always in diameters, OpenRocket mostly in radius. - */ - public static final int ROCKSIM_TO_OPENROCKET_RADIUS = 2 * ROCKSIM_TO_OPENROCKET_LENGTH; -} diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimDensityType.java b/core/src/net/sf/openrocket/file/rocksim/RocksimDensityType.java deleted file mode 100644 index 2e8d54c1..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimDensityType.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * RocksimDensityType.java - */ -package net.sf.openrocket.file.rocksim; - -import net.sf.openrocket.material.Material; - -/** - * Models the nose cone shape of a rocket. Maps from Rocksim's notion to OpenRocket's. - */ -public enum RocksimDensityType { - ROCKSIM_BULK (0, RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_BULK_DENSITY), - ROCKSIM_SURFACE(1, RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_SURFACE_DENSITY), - ROCKSIM_LINE (2, RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LINE_DENSITY); - - /** The Rocksim enumeration value. Sent in XML. */ - private final int ordinal; - - /** The corresponding OpenRocket shape. */ - private final double conversion; - - /** - * Constructor. - * - * @param idx the Rocksim shape code - * @param theConversion the numerical conversion ratio to OpenRocket - */ - private RocksimDensityType(int idx, double theConversion) { - ordinal = idx; - conversion = theConversion; - } - - /** - * Get the OpenRocket shape that corresponds to the Rocksim value. - * - * @return a conversion - */ - public double asOpenRocket() { - return conversion; - } - - /** - * Lookup an instance of this enum based upon the Rocksim code. - * - * @param rocksimDensityType the Rocksim code (from XML) - * @return an instance of this enum - */ - public static RocksimDensityType fromCode(int rocksimDensityType) { - RocksimDensityType[] values = values(); - for (RocksimDensityType value : values) { - if (value.ordinal == rocksimDensityType) { - return value; - } - } - return ROCKSIM_BULK; //Default - } - - /** - * Get the ordinal code. - * - * @param type the OR type - * - * @return the Rocksim XML value - */ - public static int toCode(Material.Type type) { - if (type.equals(Material.Type.BULK)) { - return ROCKSIM_BULK.ordinal; - } - if (type.equals(Material.Type.LINE)) { - return ROCKSIM_LINE.ordinal; - } - if (type.equals(Material.Type.SURFACE)) { - return ROCKSIM_SURFACE.ordinal; - } - return ROCKSIM_BULK.ordinal; - } -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimFinishCode.java b/core/src/net/sf/openrocket/file/rocksim/RocksimFinishCode.java deleted file mode 100644 index ba14ab41..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimFinishCode.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * RocksimFinishCode.java - */ -package net.sf.openrocket.file.rocksim; - -import net.sf.openrocket.rocketcomponent.ExternalComponent; - -/** - * Models the finish of a component. - */ -public enum RocksimFinishCode { - POLISHED(0, ExternalComponent.Finish.POLISHED), - GLOSS(1, ExternalComponent.Finish.SMOOTH), - MATT(2, ExternalComponent.Finish.NORMAL), - UNFINISHED(3, ExternalComponent.Finish.UNFINISHED); - - /** The Rocksim code (from XML). */ - private final int ordinal; - - /** The corresponding OpenRocket finish. */ - private final ExternalComponent.Finish finish; - - /** - * Constructor. - * - * @param idx the Rocksim enum value - * @param theFinish the OpenRocket finish - */ - private RocksimFinishCode(int idx, ExternalComponent.Finish theFinish) { - ordinal = idx; - finish = theFinish; - } - - /** - * Get the OpenRocket finish. - * - * @return a Finish instance - */ - public ExternalComponent.Finish asOpenRocket() { - return finish; - } - - /** - * Lookup an instance of this enum from a Rocksim value. - * - * @param rocksimFinishCode the Rocksim value - * - * @return an instance of this enum; Defaults to MATT - */ - public static RocksimFinishCode fromCode(int rocksimFinishCode) { - RocksimFinishCode[] values = values(); - for (RocksimFinishCode value : values) { - if (value.ordinal == rocksimFinishCode) { - return value; - } - } - return MATT; //Default - } - - /** - * Get the ordinal code. - * - * @param type the OR type - * - * @return the Rocksim XML value - */ - public static int toCode(ExternalComponent.Finish type) { - if (type.equals(ExternalComponent.Finish.UNFINISHED)) { - return UNFINISHED.ordinal; - } - if (type.equals(ExternalComponent.Finish.POLISHED)) { - return POLISHED.ordinal; - } - if (type.equals(ExternalComponent.Finish.SMOOTH)) { - return GLOSS.ordinal; - } - return MATT.ordinal; - } - -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimLocationMode.java b/core/src/net/sf/openrocket/file/rocksim/RocksimLocationMode.java deleted file mode 100644 index e16c97e1..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimLocationMode.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * RocksimLocationMode.java - */ -package net.sf.openrocket.file.rocksim; - -import net.sf.openrocket.rocketcomponent.RocketComponent; - -/** - * Models the relative position of parts on a rocket. Maps from Rocksim's notion to OpenRocket's. - */ -public enum RocksimLocationMode { - FRONT_OF_OWNING_PART (0, RocketComponent.Position.TOP), - FROM_TIP_OF_NOSE (1, RocketComponent.Position.ABSOLUTE), - BACK_OF_OWNING_PART (2, RocketComponent.Position.BOTTOM); - - /** The value Rocksim uses internally (and in the XML file). */ - private final int ordinal; - - /** The OpenRocket position equivalent. */ - private final RocketComponent.Position position; - - /** - * Constructor. - * - * @param idx the rocksim enum value - * @param theOpenRocketPosition the corresponding OpenRocket position - */ - RocksimLocationMode(int idx, RocketComponent.Position theOpenRocketPosition) { - ordinal = idx; - position = theOpenRocketPosition; - } - - /** - * Get the OpenRocket position. - * - * @return the position instance - */ - public RocketComponent.Position asOpenRocket() { - return position; - } - - /** - * Lookup an instance of this class from a rocksim enum value. - * - * @param rocksimCode the rocksim enum value - * - * @return an instance of this enum - */ - public static RocksimLocationMode fromCode(int rocksimCode) { - RocksimLocationMode[] values = values(); - for (RocksimLocationMode value : values) { - if (value.ordinal == rocksimCode) { - return value; - } - } - return FRONT_OF_OWNING_PART; - } - - public static int toCode(RocketComponent.Position position) { - if (RocketComponent.Position.TOP.equals(position)) { - return 0; - } - if (RocketComponent.Position.ABSOLUTE.equals(position)) { - return 1; - } - if (RocketComponent.Position.BOTTOM.equals(position)) { - return 2; - } - return 0; - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java b/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java deleted file mode 100644 index 8d24e244..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * RocksimNoseConeCode.java - */ -package net.sf.openrocket.file.rocksim; - -import net.sf.openrocket.rocketcomponent.Transition; - -import java.util.HashSet; -import java.util.Set; - -/** - * Models the nose cone shape of a rocket. Maps from Rocksim's notion to OpenRocket's. - */ -public enum RocksimNoseConeCode { - CONICAL(0, Transition.Shape.CONICAL, "Conic", "Cone"), - OGIVE(1, Transition.Shape.OGIVE), - PARABOLIC(2, Transition.Shape.ELLIPSOID), //Rocksim' PARABOLIC most closely resembles an ELLIPSOID in OpenRocket - ELLIPTICAL(3, Transition.Shape.ELLIPSOID), - POWER_SERIES(4, Transition.Shape.POWER), - PARABOLIC_SERIES(5, Transition.Shape.PARABOLIC), - HAACK(6, Transition.Shape.HAACK); - - /** - * The Rocksim enumeration value. Sent in XML. - */ - private final int ordinal; - - /** - * The corresponding OpenRocket shape. - */ - private final Transition.Shape shape; - - /** - * Names of the shape that are sometimes found in NCDATA.CSV - */ - private Set shapeNames = new HashSet(); - - /** - * Constructor. - * - * @param idx the Rocksim shape code - * @param aShape the corresponding OpenRocket shape - * @param theShapeNames an array of alternate names - */ - private RocksimNoseConeCode(int idx, Transition.Shape aShape, String... theShapeNames) { - ordinal = idx; - shape = aShape; - shapeNames.add(this.name().toLowerCase()); - if (theShapeNames != null) { - for (String theShapeName : theShapeNames) { - shapeNames.add(theShapeName.toLowerCase()); - } - } - } - - /** - * Get the OpenRocket shape that corresponds to the Rocksim shape. - * - * @return a shape - */ - public Transition.Shape asOpenRocket() { - return shape; - } - - /** - * Lookup an instance of this enum based upon the Rocksim code. - * - * @param rocksimShapeCode the Rocksim code (from XML) - * @return an instance of this enum - */ - public static RocksimNoseConeCode fromCode(int rocksimShapeCode) { - RocksimNoseConeCode[] values = values(); - for (RocksimNoseConeCode value : values) { - if (value.ordinal == rocksimShapeCode) { - return value; - } - } - return PARABOLIC; //Default - } - - /** - * Lookup an ordinal value for the Rocksim code. - * - * @param type the OR Shape - * @return the Rocksim code - */ - public static int toCode(Transition.Shape type) { - RocksimNoseConeCode[] values = values(); - for (RocksimNoseConeCode value : values) { - if (value.shape.equals(type)) { - if (value.ordinal == 2) { - return 3; - } - return value.ordinal; - } - } - return ELLIPTICAL.ordinal; //Default - } - - /** - * Given the name of a shape, map it into an instance of this enum. - * - * @param theName the name of the shape; case does not matter - * @return the corresponding enum instance; defaults to PARABOLIC if not found. - */ - public static RocksimNoseConeCode fromShapeName(String theName) { - RocksimNoseConeCode[] values = values(); - for (RocksimNoseConeCode value : values) { - if (value.shapeNames.contains(theName.toLowerCase())) { - return value; - } - } - return PARABOLIC; //Default - } - - /** - * Convenience method that determines if the parameter is an integer that refers to a shape code, or the name - * of the shape itself. This basically combines fromCode and fromShapeName into one method. - * - * @param nameOrOrdinalString the shape number or shape name - * @return an instance of this enum; defaults to PARABOLIC if not found - */ - public static RocksimNoseConeCode fromShapeNameOrCode(String nameOrOrdinalString) { - try { - return fromCode(Integer.parseInt(nameOrOrdinalString)); - } - catch (NumberFormatException nfe) { - return fromShapeName(nameOrOrdinalString); - } - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/AbstractTransitionDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/AbstractTransitionDTO.java deleted file mode 100644 index 987bc203..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/AbstractTransitionDTO.java +++ /dev/null @@ -1,149 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimNoseConeCode; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TubeCoupler; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlElementWrapper; -import java.util.ArrayList; -import java.util.List; - -/** - * A common ancestor class for nose cones and transitions. This class is responsible for adapting an OpenRocket - * Transition to a Rocksim Transition. - */ -@XmlAccessorType(XmlAccessType.FIELD) -public class AbstractTransitionDTO extends BasePartDTO implements AttachableParts { - - @XmlElement(name = RocksimCommonConstants.SHAPE_CODE) - private int shapeCode = 1; - @XmlElement(name = RocksimCommonConstants.CONSTRUCTION_TYPE) - private int constructionType = 1; - @XmlElement(name = RocksimCommonConstants.WALL_THICKNESS) - private double wallThickness = 0d; - @XmlElement(name = RocksimCommonConstants.SHAPE_PARAMETER) - private double shapeParameter = 0d; - - @XmlElementWrapper(name = RocksimCommonConstants.ATTACHED_PARTS) - @XmlElementRefs({ - @XmlElementRef(name = RocksimCommonConstants.BODY_TUBE, type = BodyTubeDTO.class), - @XmlElementRef(name = RocksimCommonConstants.BODY_TUBE, type = InnerBodyTubeDTO.class), - @XmlElementRef(name = RocksimCommonConstants.FIN_SET, type = FinSetDTO.class), - @XmlElementRef(name = RocksimCommonConstants.CUSTOM_FIN_SET, type = CustomFinSetDTO.class), - @XmlElementRef(name = RocksimCommonConstants.RING, type = CenteringRingDTO.class), - @XmlElementRef(name = RocksimCommonConstants.STREAMER, type = StreamerDTO.class), - @XmlElementRef(name = RocksimCommonConstants.PARACHUTE, type = ParachuteDTO.class), - @XmlElementRef(name = RocksimCommonConstants.MASS_OBJECT, type = MassObjectDTO.class)}) - List attachedParts = new ArrayList(); - - /** - * Default constructor. - */ - protected AbstractTransitionDTO() { - } - - /** - * Conversion constructor. - * - * @param nc the OpenRocket component to convert - */ - protected AbstractTransitionDTO(Transition nc) { - super(nc); - setConstructionType(nc.isFilled() ? 0 : 1); - setShapeCode(RocksimNoseConeCode.toCode(nc.getType())); - - if (Transition.Shape.POWER.equals(nc.getType()) || - Transition.Shape.HAACK.equals(nc.getType()) || - Transition.Shape.PARABOLIC.equals(nc.getType())) { - setShapeParameter(nc.getShapeParameter()); - } - - setWallThickness(nc.getThickness() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - - List children = nc.getChildren(); - for (int i = 0; i < children.size(); i++) { - RocketComponent rocketComponents = children.get(i); - if (rocketComponents instanceof InnerTube) { - attachedParts.add(new InnerBodyTubeDTO((InnerTube) rocketComponents, this)); - } else if (rocketComponents instanceof BodyTube) { - attachedParts.add(new BodyTubeDTO((BodyTube) rocketComponents)); - } else if (rocketComponents instanceof Transition) { - attachedParts.add(new TransitionDTO((Transition) rocketComponents)); - } else if (rocketComponents instanceof EngineBlock) { - attachedParts.add(new EngineBlockDTO((EngineBlock) rocketComponents)); - } else if (rocketComponents instanceof TubeCoupler) { - attachedParts.add(new TubeCouplerDTO((TubeCoupler) rocketComponents)); - } else if (rocketComponents instanceof CenteringRing) { - attachedParts.add(new CenteringRingDTO((CenteringRing) rocketComponents)); - } else if (rocketComponents instanceof Bulkhead) { - attachedParts.add(new BulkheadDTO((Bulkhead) rocketComponents)); - } else if (rocketComponents instanceof Parachute) { - attachedParts.add(new ParachuteDTO((Parachute) rocketComponents)); - } else if (rocketComponents instanceof MassObject) { - attachedParts.add(new MassObjectDTO((MassObject) rocketComponents)); - } else if (rocketComponents instanceof FreeformFinSet) { - attachedParts.add(new CustomFinSetDTO((FreeformFinSet) rocketComponents)); - } else if (rocketComponents instanceof FinSet) { - attachedParts.add(new FinSetDTO((FinSet) rocketComponents)); - } - } - } - - public int getShapeCode() { - return shapeCode; - } - - public void setShapeCode(int theShapeCode) { - shapeCode = theShapeCode; - } - - public int getConstructionType() { - return constructionType; - } - - public void setConstructionType(int theConstructionType) { - constructionType = theConstructionType; - } - - public double getWallThickness() { - return wallThickness; - } - - public void setWallThickness(double theWallThickness) { - wallThickness = theWallThickness; - } - - public double getShapeParameter() { - return shapeParameter; - } - - public void setShapeParameter(double theShapeParameter) { - shapeParameter = theShapeParameter; - } - - @Override - public void addAttachedPart(BasePartDTO part) { - attachedParts.add(part); - } - - @Override - public void removeAttachedPart(BasePartDTO part) { - attachedParts.remove(part); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/AttachableParts.java b/core/src/net/sf/openrocket/file/rocksim/export/AttachableParts.java deleted file mode 100644 index 61b6f4dd..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/AttachableParts.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -/** - * An interface that defines methods for attaching and detaching child components. Rocksim has a special - * XML element that acts as a container, called

. Implementors of - * this interface are those Rocksim DTO classes that support the attached parts element. - */ -public interface AttachableParts { - /** - * Remove a previously attached part from this component. - * - * @param part the instance to remove - */ - void removeAttachedPart(BasePartDTO part); - - /** - * Attach (associate) a DTO with this component. - * @param part - */ - void addAttachedPart(BasePartDTO part); -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/BasePartDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/BasePartDTO.java deleted file mode 100644 index 102f3643..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/BasePartDTO.java +++ /dev/null @@ -1,280 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimDensityType; -import net.sf.openrocket.file.rocksim.RocksimFinishCode; -import net.sf.openrocket.file.rocksim.RocksimLocationMode; -import net.sf.openrocket.file.rocksim.importt.BaseHandler; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.StructuralComponent; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The base class for all OpenRocket to Rocksim conversions. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -public abstract class BasePartDTO { - - /** - * The very important Rocksim serial number. Each component needs one. This is not multi-thread safe. Trying - * to save multiple files at the same time will have unpredictable results with respect to the serial numbering. - */ - private static int currentSerialNumber = 1; - - @XmlElement(name = RocksimCommonConstants.KNOWN_MASS) - private double knownMass = 0d; - @XmlElement(name = RocksimCommonConstants.DENSITY) - private double density = 0d; - @XmlElement(name = RocksimCommonConstants.MATERIAL) - private String material = ""; - @XmlElement(name = RocksimCommonConstants.NAME) - private String name = ""; - @XmlElement(name = RocksimCommonConstants.KNOWN_CG) - private double knownCG = 0; - @XmlElement(name = RocksimCommonConstants.USE_KNOWN_CG) - private int useKnownCG = 1; - @XmlElement(name = RocksimCommonConstants.XB) - private double xb = 0; - @XmlElement(name = RocksimCommonConstants.CALC_MASS) - private double calcMass = 0d; - @XmlElement(name = RocksimCommonConstants.CALC_CG) - private double calcCG = 0d; - @XmlElement(name = RocksimCommonConstants.DENSITY_TYPE) - private int densityType = 0; - @XmlElement(name = RocksimCommonConstants.RADIAL_LOC) - private double radialLoc = 0; - @XmlElement(name = RocksimCommonConstants.RADIAL_ANGLE) - private double radialAngle = 0; - @XmlElement(name = RocksimCommonConstants.LOCATION_MODE) - private int locationMode = 0; - @XmlElement(name = RocksimCommonConstants.LEN, required = false, nillable = false) - private double len = 0d; - @XmlElement(name = RocksimCommonConstants.FINISH_CODE) - private int finishCode = 0; - @XmlElement(name = RocksimCommonConstants.SERIAL_NUMBER) - private int serialNumber = -1; - - /** - * Default constructor. - */ - protected BasePartDTO() { - serialNumber = currentSerialNumber++; - } - - /** - * Copy constructor of sorts, that performs all common conversions for components. - * - * @param ec - */ - protected BasePartDTO(RocketComponent ec) { - serialNumber = currentSerialNumber++; - setCalcCG(ec.getCG().x * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setCalcMass(ec.getComponentMass() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - setKnownCG(ec.getOverrideCGX() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setKnownMass(ec.getMass() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - - if (! (ec instanceof FinSet)) { - setLen(ec.getLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - setUseKnownCG(ec.isCGOverridden() || ec.isMassOverridden() ? 1 : 0); - setName(ec.getName()); - - setXb(ec.getPositionValue() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - - //When the relative position is BOTTOM, the position location of the bottom edge of the component is + - //to the right of the bottom of the parent, and - to the left. - //But in Rocksim, it's + to the left and - to the right - if (ec.getRelativePosition().equals(RocketComponent.Position.BOTTOM)) { - setXb((-1 * ec.getPositionValue()) * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - else if (ec.getRelativePosition().equals(RocketComponent.Position.MIDDLE)) { - //Mapped to TOP, so adjust accordingly - setXb((ec.getPositionValue() + (ec.getParent().getLength() - ec.getLength()) /2)* RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - - if (ec instanceof ExternalComponent) { - ExternalComponent comp = (ExternalComponent) ec; - setLocationMode(RocksimLocationMode.toCode(comp.getRelativePosition())); - - setDensity(comp.getMaterial().getDensity() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_BULK_DENSITY); - setDensityType(RocksimDensityType.toCode(comp.getMaterial().getType())); - String material = comp.getMaterial().getName(); - if (material.startsWith(BaseHandler.ROCKSIM_MATERIAL_PREFIX)) { - material = material.substring(BaseHandler.ROCKSIM_MATERIAL_PREFIX.length()); - } - setMaterial(material); - - setFinishCode(RocksimFinishCode.toCode(comp.getFinish())); - } - else if (ec instanceof StructuralComponent) { - StructuralComponent comp = (StructuralComponent) ec; - - setLocationMode(RocksimLocationMode.toCode(comp.getRelativePosition())); - setDensity(comp.getMaterial().getDensity() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_BULK_DENSITY); - setDensityType(RocksimDensityType.toCode(comp.getMaterial().getType())); - String material = comp.getMaterial().getName(); - if (material.startsWith(BaseHandler.ROCKSIM_MATERIAL_PREFIX)) { - material = material.substring(BaseHandler.ROCKSIM_MATERIAL_PREFIX.length()); - } - setMaterial(material); - } - else if (ec instanceof RecoveryDevice) { - RecoveryDevice comp = (RecoveryDevice) ec; - - setLocationMode(RocksimLocationMode.toCode(comp.getRelativePosition())); - setDensity(comp.getMaterial().getDensity() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_SURFACE_DENSITY); - setDensityType(RocksimDensityType.toCode(comp.getMaterial().getType())); - String material = comp.getMaterial().getName(); - if (material.startsWith(BaseHandler.ROCKSIM_MATERIAL_PREFIX)) { - material = material.substring(BaseHandler.ROCKSIM_MATERIAL_PREFIX.length()); - } - setMaterial(material); - } - - if (ec instanceof RingComponent) { - RingComponent rc = (RingComponent)ec; - setRadialAngle(rc.getRadialDirection()); - setRadialLoc(rc.getRadialPosition() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - } - - public Double getKnownMass() { - return knownMass; - } - - public void setKnownMass(Double theKnownMass) { - knownMass = theKnownMass; - } - - public double getDensity() { - return density; - } - - public void setDensity(double theDensity) { - density = theDensity; - } - - public String getMaterial() { - return material; - } - - public void setMaterial(String theMaterial) { - material = theMaterial; - } - - public String getName() { - return name; - } - - public void setName(String theName) { - name = theName; - } - - public Double getKnownCG() { - return knownCG; - } - - public void setKnownCG(Double theKnownCG) { - knownCG = theKnownCG; - } - - public int getUseKnownCG() { - return useKnownCG; - } - - public void setUseKnownCG(int theUseKnownCG) { - useKnownCG = theUseKnownCG; - } - - public double getXb() { - return xb; - } - - public void setXb(double theXb) { - xb = theXb; - } - - public double getCalcMass() { - return calcMass; - } - - public void setCalcMass(double theCalcMass) { - calcMass = theCalcMass; - } - - public double getCalcCG() { - return calcCG; - } - - public void setCalcCG(double theCalcCG) { - calcCG = theCalcCG; - } - - public int getDensityType() { - return densityType; - } - - public void setDensityType(int theDensityType) { - densityType = theDensityType; - } - - public double getRadialLoc() { - return radialLoc; - } - - public void setRadialLoc(double theRadialLoc) { - radialLoc = theRadialLoc; - } - - public double getRadialAngle() { - return radialAngle; - } - - public void setRadialAngle(double theRadialAngle) { - radialAngle = theRadialAngle; - } - - public int getLocationMode() { - return locationMode; - } - - public void setLocationMode(int theLocationMode) { - locationMode = theLocationMode; - } - - public double getLen() { - return len; - } - - public void setLen(double theLen) { - len = theLen; - } - - public int getFinishCode() { - return finishCode; - } - - public void setFinishCode(int theFinishCode) { - finishCode = theFinishCode; - } - - public static int getCurrentSerialNumber() { - return currentSerialNumber - 1; - } - - /** - * Reset the serial number, which needs to happen after each file save. - */ - public static void resetCurrentSerialNumber() { - currentSerialNumber = 0; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/BodyTubeDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/BodyTubeDTO.java deleted file mode 100644 index 4f9f708d..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/BodyTubeDTO.java +++ /dev/null @@ -1,206 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TubeCoupler; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.ArrayList; -import java.util.List; - -/** - * Models the XML element for a Rocksim body tube. - */ -@XmlRootElement(name = RocksimCommonConstants.BODY_TUBE) -@XmlAccessorType(XmlAccessType.FIELD) -public class BodyTubeDTO extends BasePartDTO implements AttachableParts { - - @XmlElement(name = RocksimCommonConstants.OD) - private double od = 0d; - @XmlElement(name = RocksimCommonConstants.ID) - private double id = 0d; - @XmlElement(name = RocksimCommonConstants.IS_MOTOR_MOUNT) - private int isMotorMount = 0; - @XmlElement(name = RocksimCommonConstants.MOTOR_DIA) - private double motorDia = 0d; - @XmlElement(name = RocksimCommonConstants.ENGINE_OVERHANG) - private double engineOverhang = 0d; - @XmlElement(name = RocksimCommonConstants.IS_INSIDE_TUBE) - private int isInsideTube = 0; - @XmlElementWrapper(name = RocksimCommonConstants.ATTACHED_PARTS) - @XmlElementRefs({ - @XmlElementRef(name = RocksimCommonConstants.BODY_TUBE, type = BodyTubeDTO.class), - @XmlElementRef(name = RocksimCommonConstants.BODY_TUBE, type = InnerBodyTubeDTO.class), - @XmlElementRef(name = RocksimCommonConstants.RING, type = CenteringRingDTO.class), - @XmlElementRef(name = RocksimCommonConstants.LAUNCH_LUG, type = LaunchLugDTO.class), - @XmlElementRef(name = RocksimCommonConstants.FIN_SET, type = FinSetDTO.class), - @XmlElementRef(name = RocksimCommonConstants.CUSTOM_FIN_SET, type = CustomFinSetDTO.class), - @XmlElementRef(name = RocksimCommonConstants.STREAMER, type = StreamerDTO.class), - @XmlElementRef(name = RocksimCommonConstants.PARACHUTE, type = ParachuteDTO.class), - @XmlElementRef(name = RocksimCommonConstants.MASS_OBJECT, type = MassObjectDTO.class)}) - List attachedParts = new ArrayList(); - - /** - * Constructor. - */ - public BodyTubeDTO() { - } - - /** - * Copy constructor. - * - * @param theORInnerTube an OR inner tube; used by subclasses - */ - protected BodyTubeDTO(InnerTube theORInnerTube) { - super(theORInnerTube); - } - - /** - * Copy constructor. - * - * @param theORBodyTube an OR body tube - */ - protected BodyTubeDTO(BodyTube theORBodyTube) { - super(theORBodyTube); - - setEngineOverhang(theORBodyTube.getMotorOverhang() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setID(theORBodyTube.getInnerRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setOD(theORBodyTube.getOuterRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setMotorDia((theORBodyTube.getMotorMountDiameter() / 2) * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setMotorMount(theORBodyTube.isMotorMount()); - - List children = theORBodyTube.getChildren(); - for (int i = 0; i < children.size(); i++) { - RocketComponent rocketComponents = children.get(i); - if (rocketComponents instanceof InnerTube) { - final InnerTube innerTube = (InnerTube) rocketComponents; - final InnerBodyTubeDTO innerBodyTubeDTO = new InnerBodyTubeDTO(innerTube, this); - //Only add the inner tube if it is NOT a cluster. - if (innerTube.getClusterCount() == 1) { - attachedParts.add(innerBodyTubeDTO); - } - } else if (rocketComponents instanceof BodyTube) { - attachedParts.add(new BodyTubeDTO((BodyTube) rocketComponents)); - } else if (rocketComponents instanceof Transition) { - attachedParts.add(new TransitionDTO((Transition) rocketComponents)); - } else if (rocketComponents instanceof EngineBlock) { - attachedParts.add(new EngineBlockDTO((EngineBlock) rocketComponents)); - } else if (rocketComponents instanceof TubeCoupler) { - attachedParts.add(new TubeCouplerDTO((TubeCoupler) rocketComponents)); - } else if (rocketComponents instanceof CenteringRing) { - attachedParts.add(new CenteringRingDTO((CenteringRing) rocketComponents)); - } else if (rocketComponents instanceof Bulkhead) { - attachedParts.add(new BulkheadDTO((Bulkhead) rocketComponents)); - } else if (rocketComponents instanceof LaunchLug) { - attachedParts.add(new LaunchLugDTO((LaunchLug) rocketComponents)); - } else if (rocketComponents instanceof Streamer) { - attachedParts.add(new StreamerDTO((Streamer) rocketComponents)); - } else if (rocketComponents instanceof Parachute) { - attachedParts.add(new ParachuteDTO((Parachute) rocketComponents)); - } else if (rocketComponents instanceof MassObject) { - attachedParts.add(new MassObjectDTO((MassObject) rocketComponents)); - } else if (rocketComponents instanceof FreeformFinSet) { - attachedParts.add(new CustomFinSetDTO((FreeformFinSet) rocketComponents)); - } else if (rocketComponents instanceof FinSet) { - attachedParts.add(new FinSetDTO((FinSet) rocketComponents)); - } - } - } - - public double getOD() { - return od; - } - - public void setOD(double theOd) { - od = theOd; - } - - public double getID() { - return id; - } - - public void setID(double theId) { - id = theId; - } - - public int getMotorMount() { - return isMotorMount; - } - - public void setMotorMount(boolean motorMount) { - if (motorMount) { - isMotorMount = 1; - } else { - isMotorMount = 0; - } - - } - - public void setMotorMount(int theMotorMount) { - isMotorMount = theMotorMount; - } - - public double getMotorDia() { - return motorDia; - } - - public void setMotorDia(double theMotorDia) { - motorDia = theMotorDia; - } - - public double getEngineOverhang() { - return engineOverhang; - } - - public void setEngineOverhang(double theEngineOverhang) { - engineOverhang = theEngineOverhang; - } - - public int getInsideTube() { - return isInsideTube; - } - - public void setInsideTube(boolean inside) { - if (inside) { - isInsideTube = 1; - } else { - isInsideTube = 0; - } - } - - public void setInsideTube(int theInsideTube) { - isInsideTube = theInsideTube; - } - - public List getAttachedParts() { - return attachedParts; - } - - @Override - public void addAttachedPart(BasePartDTO thePart) { - attachedParts.add(thePart); - } - - @Override - public void removeAttachedPart(BasePartDTO part) { - attachedParts.remove(part); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/file/rocksim/export/BulkheadDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/BulkheadDTO.java deleted file mode 100644 index e8b78e11..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/BulkheadDTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.Bulkhead; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Conversion of an OR Bulkhead to an Rocksim Bulkhead. Bulkheads are represented as Rings in Rocksim. - */ -@XmlRootElement(name = RocksimCommonConstants.RING) -@XmlAccessorType(XmlAccessType.FIELD) -public class BulkheadDTO extends CenteringRingDTO { - - /** - * Constructor. - * - * @param theORBulkhead the OR bulkhead - */ - public BulkheadDTO(Bulkhead theORBulkhead) { - super(theORBulkhead); - setUsageCode(CenteringRingDTO.UsageCode.Bulkhead); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/CenteringRingDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/CenteringRingDTO.java deleted file mode 100644 index e925c10f..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/CenteringRingDTO.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.RadiusRingComponent; -import net.sf.openrocket.rocketcomponent.ThicknessRingComponent; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -/** - * Centering ring conversion from OR to Rocksim. - */ -@XmlRootElement(name = RocksimCommonConstants.RING) -@XmlAccessorType(XmlAccessType.FIELD) -public class CenteringRingDTO extends BasePartDTO { - - @XmlTransient - protected enum UsageCode { - //UsageCode - CenteringRing(0), - Bulkhead(1), - EngineBlock(2), - Sleeve(3), - TubeCoupler(4); - - int ordinal; - - UsageCode(int x) { - ordinal = x; - } - } - - @XmlElement(name = RocksimCommonConstants.OD) - private double od = 0d; - @XmlElement(name = RocksimCommonConstants.ID) - private double id = 0d; - @XmlElement(name = RocksimCommonConstants.USAGE_CODE) - private int usageCode = UsageCode.CenteringRing.ordinal; - @XmlElement(name = RocksimCommonConstants.AUTO_SIZE) - private int autoSize = 0; - - /** - * Default Constructor. - */ - public CenteringRingDTO() { - } - - /** - * Copy constructor. - * - * @param theORRadiusRing - */ - public CenteringRingDTO(RadiusRingComponent theORRadiusRing) { - super(theORRadiusRing); - setId(theORRadiusRing.getInnerRadius()* RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setOd(theORRadiusRing.getOuterRadius()* RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - - /** - * Copy constructor. - * - * @param theORThicknessRing - */ - public CenteringRingDTO(ThicknessRingComponent theORThicknessRing) { - super(theORThicknessRing); - setId(theORThicknessRing.getInnerRadius()* RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setOd(theORThicknessRing.getOuterRadius()* RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - - public double getOd() { - return od; - } - - public void setOd(double theOd) { - od = theOd; - } - - public double getId() { - return id; - } - - public void setId(double theId) { - id = theId; - } - - public int getUsageCode() { - return usageCode; - } - - public void setUsageCode(int theUsageCode) { - usageCode = theUsageCode; - } - - public void setUsageCode(UsageCode theUsageCode) { - usageCode = theUsageCode.ordinal; - } - - public int getAutoSize() { - return autoSize; - } - - public void setAutoSize(int theAutoSize) { - autoSize = theAutoSize; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/CustomFinSetDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/CustomFinSetDTO.java deleted file mode 100644 index c7f95ac2..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/CustomFinSetDTO.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.util.Coordinate; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - */ -@XmlRootElement(name = RocksimCommonConstants.CUSTOM_FIN_SET) -@XmlAccessorType(XmlAccessType.FIELD) -public class CustomFinSetDTO extends FinSetDTO { - - @XmlElement(name = RocksimCommonConstants.POINT_LIST) - private String pointList = ""; - - /** - * Default constructor. - */ - public CustomFinSetDTO() { - } - - /** - * Copy constructor of sorts. - * - * @param ec a free form finset - */ - public CustomFinSetDTO(FreeformFinSet ec) { - super(ec); - setPointList(convertFreeFormPoints(ec.getFinPoints())); - } - - - private String convertFreeFormPoints(Coordinate[] points) { - StringBuilder sb = new StringBuilder(); - - //Reverse the order for Rocksim - for (int i = points.length - 1; i >= 0; i--) { - Coordinate point = points[i]; - sb.append(point.x * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH).append(",") - .append(point.y * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH).append("|"); - } - return sb.toString(); - } - - public String getPointList() { - return pointList; - } - - public void setPointList(String thePointList) { - pointList = thePointList; - } -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/export/EngineBlockDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/EngineBlockDTO.java deleted file mode 100644 index 6a742fb3..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/EngineBlockDTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.rocketcomponent.EngineBlock; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Models a Rocksim XML Element for an EngineBlock. EngineBlocks in Rocksim are treated as rings with a special - * usage code. - */ -@XmlRootElement(name = "Ring") -@XmlAccessorType(XmlAccessType.FIELD) -public class EngineBlockDTO extends CenteringRingDTO{ - - /** - * Copy constructor. - * - * @param theOREngineBlock - */ - public EngineBlockDTO(EngineBlock theOREngineBlock) { - super(theOREngineBlock); - setUsageCode(UsageCode.EngineBlock); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/FinSetDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/FinSetDTO.java deleted file mode 100644 index 0879c3b7..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/FinSetDTO.java +++ /dev/null @@ -1,194 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.TipShapeCode; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class models XML elements for Rocksim finsets. - */ -@XmlRootElement(name = RocksimCommonConstants.FIN_SET) -@XmlAccessorType(XmlAccessType.FIELD) -public class FinSetDTO extends BasePartDTO { - - @XmlElement(name = RocksimCommonConstants.FIN_COUNT) - private int finCount = 0; - @XmlElement(name = RocksimCommonConstants.ROOT_CHORD) - private double rootChord = 0d; - @XmlElement(name = RocksimCommonConstants.TIP_CHORD) - private double tipChord = 0d; - @XmlElement(name = RocksimCommonConstants.SEMI_SPAN) - private double semiSpan = 0d; - @XmlElement(name = RocksimCommonConstants.SWEEP_DISTANCE) - private double sweepDistance = 0d; - @XmlElement(name = RocksimCommonConstants.THICKNESS) - private double thickness = 0d; - @XmlElement(name = RocksimCommonConstants.SHAPE_CODE) - private int shapeCode = 0; - @XmlElement(name = RocksimCommonConstants.TIP_SHAPE_CODE) - private int tipShapeCode = 0; - @XmlElement(name = RocksimCommonConstants.TAB_LENGTH) - private double tabLength = 0d; - @XmlElement(name = RocksimCommonConstants.TAB_DEPTH) - private double tabDepth = 0d; - @XmlElement(name = RocksimCommonConstants.TAB_OFFSET) - private double tabOffset = 0d; - @XmlElement(name = RocksimCommonConstants.SWEEP_MODE) - private int sweepMode = 1; - @XmlElement(name = RocksimCommonConstants.CANT_ANGLE) - private double cantAngle = 0d; - - /** - * Constructor. - */ - public FinSetDTO() { - } - - /** - * Full copy constructor. - * - * @param theORFinSet the OpenRocket finset - */ - public FinSetDTO(FinSet theORFinSet) { - super(theORFinSet); - - setFinCount(theORFinSet.getFinCount()); - setCantAngle(theORFinSet.getCantAngle()); - setTabDepth(theORFinSet.getTabHeight() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setTabLength(theORFinSet.getTabLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setTabOffset(theORFinSet.getTabShift() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setThickness(theORFinSet.getThickness() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - - setRadialAngle(theORFinSet.getBaseRotation()); - setTipShapeCode(TipShapeCode.convertTipShapeCode(theORFinSet.getCrossSection())); - if (theORFinSet instanceof TrapezoidFinSet) { - TrapezoidFinSet tfs = (TrapezoidFinSet) theORFinSet; - setShapeCode(0); - setRootChord(theORFinSet.getLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setSemiSpan(tfs.getHeight() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setTipChord(tfs.getTipChord() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setSweepDistance(tfs.getSweep() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - else if (theORFinSet instanceof EllipticalFinSet) { - EllipticalFinSet efs = (EllipticalFinSet) theORFinSet; - setShapeCode(1); - setRootChord(theORFinSet.getLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setSemiSpan(efs.getHeight() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - else if (theORFinSet instanceof FreeformFinSet) { - setShapeCode(2); - } - } - - public int getFinCount() { - return finCount; - } - - public void setFinCount(int theFinCount) { - finCount = theFinCount; - } - - public double getRootChord() { - return rootChord; - } - - public void setRootChord(double theRootChord) { - rootChord = theRootChord; - } - - public double getTipChord() { - return tipChord; - } - - public void setTipChord(double theTipChord) { - tipChord = theTipChord; - } - - public double getSemiSpan() { - return semiSpan; - } - - public void setSemiSpan(double theSemiSpan) { - semiSpan = theSemiSpan; - } - - public double getSweepDistance() { - return sweepDistance; - } - - public void setSweepDistance(double theSweepDistance) { - sweepDistance = theSweepDistance; - } - - public double getThickness() { - return thickness; - } - - public void setThickness(double theThickness) { - thickness = theThickness; - } - - public int getShapeCode() { - return shapeCode; - } - - public void setShapeCode(int theShapeCode) { - shapeCode = theShapeCode; - } - - public int getTipShapeCode() { - return tipShapeCode; - } - - public void setTipShapeCode(int theTipShapeCode) { - tipShapeCode = theTipShapeCode; - } - - public double getTabLength() { - return tabLength; - } - - public void setTabLength(double theTabLength) { - tabLength = theTabLength; - } - - public double getTabDepth() { - return tabDepth; - } - - public void setTabDepth(double theTabDepth) { - tabDepth = theTabDepth; - } - - public double getTabOffset() { - return tabOffset; - } - - public void setTabOffset(double theTabOffset) { - tabOffset = theTabOffset; - } - - public int getSweepMode() { - return sweepMode; - } - - public void setSweepMode(int theSweepMode) { - sweepMode = theSweepMode; - } - - public double getCantAngle() { - return cantAngle; - } - - public void setCantAngle(double theCantAngle) { - cantAngle = theCantAngle; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/InnerBodyTubeDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/InnerBodyTubeDTO.java deleted file mode 100644 index 8b040395..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/InnerBodyTubeDTO.java +++ /dev/null @@ -1,124 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.gui.configdialog.InnerTubeConfig; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.util.Coordinate; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * This class models the XML element for a Rocksim inside tube. - */ -@XmlRootElement(name = RocksimCommonConstants.BODY_TUBE) -@XmlAccessorType(XmlAccessType.FIELD) -public class InnerBodyTubeDTO extends BodyTubeDTO implements AttachableParts { - - /** - * Constructor. - */ - public InnerBodyTubeDTO() { - super.setInsideTube(true); - } - - /** - * Full copy constructor. - * - * @param bt the corresponding OR inner body tube - * @param parent the attached parts (subcomponents in Rocksim speak) of the InnerTube's parent. This instance - * is a member of those attached parts, as well as all sibling components. This is passed in the - * event that the inner tube is a cluster. In that situation this instance will be removed and - * individual instances for each cluster member will be added. - */ - public InnerBodyTubeDTO(InnerTube bt, AttachableParts parent) { - super(bt); - setEngineOverhang(bt.getMotorOverhang() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setID(bt.getInnerRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setOD(bt.getOuterRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setMotorDia((bt.getMotorMountDiameter() / 2) * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setMotorMount(bt.isMotorMount()); - setInsideTube(true); - setRadialAngle(bt.getRadialDirection()); - setRadialLoc(bt.getRadialPosition() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - - List children = bt.getChildren(); - for (int i = 0; i < children.size(); i++) { - RocketComponent rocketComponents = children.get(i); - if (rocketComponents instanceof InnerTube) { - final InnerTube innerTube = (InnerTube) rocketComponents; - //Only if the inner tube is NOT a cluster, then create the corresponding Rocksim DTO and add it - //to the list of attached parts. If it is a cluster, then it is handled specially outside of this - //loop. - if (innerTube.getClusterCount() == 1) { - attachedParts.add(new InnerBodyTubeDTO(innerTube, this)); - } - } else if (rocketComponents instanceof BodyTube) { - attachedParts.add(new BodyTubeDTO((BodyTube) rocketComponents)); - } else if (rocketComponents instanceof Transition) { - attachedParts.add(new TransitionDTO((Transition) rocketComponents)); - } else if (rocketComponents instanceof EngineBlock) { - attachedParts.add(new EngineBlockDTO((EngineBlock) rocketComponents)); - } else if (rocketComponents instanceof TubeCoupler) { - attachedParts.add(new TubeCouplerDTO((TubeCoupler) rocketComponents)); - } else if (rocketComponents instanceof CenteringRing) { - attachedParts.add(new CenteringRingDTO((CenteringRing) rocketComponents)); - } else if (rocketComponents instanceof Bulkhead) { - attachedParts.add(new BulkheadDTO((Bulkhead) rocketComponents)); - } else if (rocketComponents instanceof Streamer) { - attachedParts.add(new StreamerDTO((Streamer) rocketComponents)); - } else if (rocketComponents instanceof Parachute) { - attachedParts.add(new ParachuteDTO((Parachute) rocketComponents)); - } else if (rocketComponents instanceof MassObject) { - attachedParts.add(new MassObjectDTO((MassObject) rocketComponents)); - } - } - //Do the cluster. For now this splits the cluster into separate tubes, which is how Rocksim represents it. - //The import (from Rocksim to OR) could be augmented to be more intelligent and try to determine if the - //co-located tubes are a cluster. - if (bt.getClusterConfiguration().getClusterCount() > 1) { - handleCluster(bt, parent); - parent.removeAttachedPart(this); - } - } - - - /** - * Handle the inner tube as a cluster. This amounts to splitting it up so that each motor mount in the cluster - * is created individually to support Rocksim's view of clusters. - * - * @param it the clustered tube - * @param p the collection (parent's attached parts really) to which all cluster tubes will be added - */ - private void handleCluster(InnerTube it, AttachableParts p) { - - Coordinate[] coords = {Coordinate.NUL}; - coords = it.shiftCoordinates(coords); - for (int x = 0; x < coords.length; x++) { - InnerTube partialClone = InnerTubeConfig.makeIndividualClusterComponent(coords[x], it.getName() + " #" + (x + 1), it); - p.addAttachedPart(new InnerBodyTubeDTO(partialClone, p)); - } - } - - @Override - public void addAttachedPart(BasePartDTO part) { - attachedParts.add(part); - } - - @Override - public void removeAttachedPart(BasePartDTO part) { - attachedParts.remove(part); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/LaunchLugDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/LaunchLugDTO.java deleted file mode 100644 index 4c287202..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/LaunchLugDTO.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.LaunchLug; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class models an XML element for a Rocksim LaunchLug. - */ -@XmlRootElement(name = RocksimCommonConstants.LAUNCH_LUG) -@XmlAccessorType(XmlAccessType.FIELD) -public class LaunchLugDTO extends BasePartDTO { - - @XmlElement(name = RocksimCommonConstants.OD) - private double od = 0d; - @XmlElement(name = RocksimCommonConstants.ID) - private double id = 0d; - - /** - * Default constructor. - */ - public LaunchLugDTO() { - } - - /** - * Copy constructor. Fully populates this instance with values taken from the OR LaunchLug. - * - * @param theORLaunchLug - */ - public LaunchLugDTO(LaunchLug theORLaunchLug) { - super(theORLaunchLug); - setId(theORLaunchLug.getInnerRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setOd(theORLaunchLug.getOuterRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setRadialAngle(theORLaunchLug.getRadialDirection()); - } - - public double getOd() { - return od; - } - - public void setOd(double theOd) { - od = theOd; - } - - public double getId() { - return id; - } - - public void setId(double theId) { - id = theId; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/MassObjectDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/MassObjectDTO.java deleted file mode 100644 index 85782b27..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/MassObjectDTO.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.MassObject; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Class that models a Rocksim MassObject. - */ -@XmlRootElement(name = RocksimCommonConstants.MASS_OBJECT) -@XmlAccessorType(XmlAccessType.FIELD) -public class MassObjectDTO extends BasePartDTO{ - - @XmlElement(name = RocksimCommonConstants.TYPE_CODE) - private final int typeCode = 0; - - /** - * Default constructor. - */ - public MassObjectDTO() { - } - - /** - * Typed copy constructor. - * - * @param mo OR MassObject - */ - public MassObjectDTO(MassObject mo) { - super(mo); - setRadialAngle(mo.getRadialDirection()); - setRadialLoc(mo.getRadialPosition() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setCalcMass(0d); - setCalcCG(0d); - setKnownCG(getXb()); - setUseKnownCG(1); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/NoseConeDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/NoseConeDTO.java deleted file mode 100644 index 79914c13..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/NoseConeDTO.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.NoseCone; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class models a Rocksim XML Element for a nose cone. - */ -@XmlRootElement(name = RocksimCommonConstants.NOSE_CONE) -@XmlAccessorType(XmlAccessType.FIELD) -public class NoseConeDTO extends AbstractTransitionDTO { - - - @XmlElement(name = RocksimCommonConstants.BASE_DIA) - private double baseDia = 0d; - @XmlElement(name = RocksimCommonConstants.SHOULDER_LEN) - private double shoulderLen = 0d; - @XmlElement(name = RocksimCommonConstants.SHOULDER_OD) - private double shoulderOD = 0d; - - /** - * Default constructor. - */ - public NoseConeDTO() { - } - - /** - * Full copy constructor. Fully populates this instance with values taken from the OR NoseCone instance. - * - * @param nc the OR nose cone - */ - public NoseConeDTO(NoseCone nc) { - super(nc); - setBaseDia(nc.getAftRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setShoulderLen(nc.getAftShoulderLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setShoulderOD(nc.getAftShoulderRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - - public double getBaseDia() { - return baseDia; - } - - public void setBaseDia(double theBaseDia) { - baseDia = theBaseDia; - } - - public double getShoulderLen() { - return shoulderLen; - } - - public void setShoulderLen(double theShoulderLen) { - shoulderLen = theShoulderLen; - } - - public double getShoulderOD() { - return shoulderOD; - } - - public void setShoulderOD(double theShoulderOD) { - shoulderOD = theShoulderOD; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/ParachuteDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/ParachuteDTO.java deleted file mode 100644 index 7f0f2507..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/ParachuteDTO.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.importt.BaseHandler; -import net.sf.openrocket.rocketcomponent.Parachute; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - */ -@XmlRootElement(name = RocksimCommonConstants.PARACHUTE) -@XmlAccessorType(XmlAccessType.FIELD) -public class ParachuteDTO extends BasePartDTO { - - @XmlElement(name = RocksimCommonConstants.DIAMETER) - private double dia = 0d; - @XmlElement(name = RocksimCommonConstants.SHROUD_LINE_COUNT) - private int ShroudLineCount = 0; - @XmlElement(name = RocksimCommonConstants.THICKNESS) - private double thickness = 0d; - @XmlElement(name = RocksimCommonConstants.SHROUD_LINE_LEN) - private double shroudLineLen = 0d; - @XmlElement(name = RocksimCommonConstants.CHUTE_COUNT) - private int chuteCount = 1; - @XmlElement(name = RocksimCommonConstants.SHROUD_LINE_MASS_PER_MM) - private double shroudLineMassPerMM = 0d; - @XmlElement(name = RocksimCommonConstants.SHROUD_LINE_MATERIAL) - private String shroudLineMaterial = ""; - @XmlElement(name = RocksimCommonConstants.DRAG_COEFFICIENT) - private double dragCoefficient = 0.75d; - - /** - * Default constructor. - */ - public ParachuteDTO() { - } - - /** - * Copy constructor. Fully populates this instance with values taken from the corresponding OR Parachute. - * - * @param theORParachute the OR Parachute instance - */ - public ParachuteDTO(Parachute theORParachute) { - super(theORParachute); - - setChuteCount(1); - setDia(theORParachute.getDiameter() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setDragCoefficient(theORParachute.getCD()); - setShroudLineCount(theORParachute.getLineCount()); - setShroudLineLen(theORParachute.getLineLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - - String material = theORParachute.getLineMaterial().getName(); - setShroudLineMassPerMM(theORParachute.getLineMaterial().getDensity() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LINE_DENSITY); - - if (material.startsWith(BaseHandler.ROCKSIM_MATERIAL_PREFIX)) { - material = material.substring(BaseHandler.ROCKSIM_MATERIAL_PREFIX.length()); - } - setShroudLineMaterial(material); - } - - public double getDia() { - return dia; - } - - public void setDia(double theDia) { - dia = theDia; - } - - public int getShroudLineCount() { - return ShroudLineCount; - } - - public void setShroudLineCount(int theShroudLineCount) { - ShroudLineCount = theShroudLineCount; - } - - public double getThickness() { - return thickness; - } - - public void setThickness(double theThickness) { - thickness = theThickness; - } - - public double getShroudLineLen() { - return shroudLineLen; - } - - public void setShroudLineLen(double theShroudLineLen) { - shroudLineLen = theShroudLineLen; - } - - public int getChuteCount() { - return chuteCount; - } - - public void setChuteCount(int theChuteCount) { - chuteCount = theChuteCount; - } - - public double getShroudLineMassPerMM() { - return shroudLineMassPerMM; - } - - public void setShroudLineMassPerMM(double theShroudLineMassPerMM) { - shroudLineMassPerMM = theShroudLineMassPerMM; - } - - public String getShroudLineMaterial() { - return shroudLineMaterial; - } - - public void setShroudLineMaterial(String theShroudLineMaterial) { - shroudLineMaterial = theShroudLineMaterial; - } - - public double getDragCoefficient() { - return dragCoefficient; - } - - public void setDragCoefficient(double theDragCoefficient) { - dragCoefficient = theDragCoefficient; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/RocketDesignDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/RocketDesignDTO.java deleted file mode 100644 index 23adf20f..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/RocketDesignDTO.java +++ /dev/null @@ -1,201 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; - -/** - * This class models a Rocksim XML element for a rocket design container. It's really nothing more than - * a bunch of boilerplate XML that does not change, coupled with the stage DTOs that are part of the rocket design. - */ -@XmlAccessorType(XmlAccessType.FIELD) -public class RocketDesignDTO { - - @XmlElement(name = "Name") - private String name; - @XmlElement(name = "StageCount") - private int stageCount = 1; - @XmlElement(name = "DisplayFlags") - private int displayFlags = 7; - @XmlElement(name = "ViewType") - private int viewType = 0; - @XmlElement(name = "ViewStageCount") - private int viewStageCount = 3; - @XmlElement(name = "ViewTypeEdit") - private int viewTypeEdit = 0; - @XmlElement(name = "ViewStageCountEdit") - private int viewStageCountEdit = 3; - @XmlElement(name = "ZoomFactor") - private double zoomFactor = 0d; - @XmlElement (name = "ZoomFactorEdit") - private double zoomFactorEdit = 0d; - @XmlElement(name = "ScrollPosX") - private int scrollPosX = 0; - @XmlElement(name = "ScrollPosY") - private int scrollPosY = 0; - @XmlElement(name = "ScrollPosXEdit") - private int scrollPosXEdit = 0; - @XmlElement(name = "ScrollPosYEdit") - private int scrollPosYEdit = 0; - @XmlElement(name = "ThreeDFlags") - private int threeDFlags = 0; - @XmlElement(name = "ThreeDFlagsEdit") - private int threeDFlagsEdit = 0; - @XmlElement(name = "LastSerialNumber") - private int lastSerialNumber = -1; - @XmlElement(name = "Stage3Mass") - private double stage3Mass = 0d; - @XmlElement(name = "Stage2Mass") - private double stage2Mass = 0d; - @XmlElement(name = "Stage1Mass") - private double stage1Mass = 0d; - @XmlElement(name = "Stage3CG") - private double stage3CG = 0d; - @XmlElement(name = "Stage2CGAlone") - private double stage2CGAlone = 0d; - @XmlElement(name = "Stage1CGAlone") - private double stage1CGAlone = 0d; - @XmlElement(name = "Stage321CG") - private double stage321CG = 0d; - @XmlElement(name = "Stage32CG") - private double stage32CG = 0d; - - @XmlElement(name = "CPCalcFlags") - private int cpCalcFlags = 1; - @XmlElement(name = "CPSimFlags") - private int cpSimFlags = 1; - @XmlElement(name = "UseKnownMass") - private int useKnownMass = 0; - @XmlElement(name = "Stage3Parts") - private StageDTO stage3 = new StageDTO(); - @XmlElement(name = "Stage2Parts", required = true, nillable = false) - private StageDTO stage2 = new StageDTO(); - @XmlElement(name = "Stage1Parts", required = false, nillable = false) - private StageDTO stage1 = new StageDTO(); - - /** - * Default constructor. - */ - public RocketDesignDTO() { - } - - public String getName() { - return name; - } - - public void setName(String theName) { - name = theName; - } - - public int getStageCount() { - return stageCount; - } - - public void setStageCount(int theStageCount) { - stageCount = theStageCount; - } - - public StageDTO getStage3() { - return stage3; - } - - public void setStage3(StageDTO theStage3) { - stage3 = theStage3; - } - - public StageDTO getStage2() { - return stage2; - } - - public void setStage2(StageDTO theStage2) { - stage2 = theStage2; - } - - public StageDTO getStage1() { - return stage1; - } - - public void setStage1(StageDTO theStage1) { - stage1 = theStage1; - } - - public int getUseKnownMass() { - return useKnownMass; - } - - public void setUseKnownMass(int useKnownMass) { - this.useKnownMass = useKnownMass; - } - - public double getStage3Mass() { - return stage3Mass; - } - - public void setStage3Mass(double stage3Mass) { - this.stage3Mass = stage3Mass; - } - - public double getStage2Mass() { - return stage2Mass; - } - - public void setStage2Mass(double stage2Mass) { - this.stage2Mass = stage2Mass; - } - - public double getStage1Mass() { - return stage1Mass; - } - - public void setStage1Mass(double stage1Mass) { - this.stage1Mass = stage1Mass; - } - - public double getStage3CG() { - return stage3CG; - } - - public void setStage3CG(double stage3CG) { - this.stage3CG = stage3CG; - } - - public double getStage2CGAlone() { - return stage2CGAlone; - } - - public void setStage2CGAlone(double stage2CGAlone) { - this.stage2CGAlone = stage2CGAlone; - } - - public double getStage1CGAlone() { - return stage1CGAlone; - } - - public void setStage1CGAlone(double stage1CGAlone) { - this.stage1CGAlone = stage1CGAlone; - } - - public double getStage321CG() { - return stage321CG; - } - - public void setStage321CG(double stage321CG) { - this.stage321CG = stage321CG; - } - - public double getStage32CG() { - return stage32CG; - } - - public void setStage32CG(double stage32CG) { - this.stage32CG = stage32CG; - } - - public int getLastSerialNumber() { - return lastSerialNumber; - } - - public void setLastSerialNumber(int lastSerialNumber) { - this.lastSerialNumber = lastSerialNumber; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/RocksimDesignDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/RocksimDesignDTO.java deleted file mode 100644 index 3dfffe81..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/RocksimDesignDTO.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; - -/** - * High-level placeholder element for Rocksim. - */ -@XmlAccessorType(XmlAccessType.FIELD) -public class RocksimDesignDTO { - - @XmlElement(name = RocksimCommonConstants.ROCKET_DESIGN) - private RocketDesignDTO design; - - /** - * Constructor. - */ - public RocksimDesignDTO() { - } - - /** - * Get the DTO. - * - * @return the DTO - */ - public RocketDesignDTO getDesign() { - return design; - } - - /** - * Set the DTO. - * - * @param theDesign the DTO - */ - public void setDesign(RocketDesignDTO theDesign) { - design = theDesign; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/RocksimDocumentDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/RocksimDocumentDTO.java deleted file mode 100644 index 99e65ca3..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/RocksimDocumentDTO.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The top level Rocksim document. - */ -@XmlRootElement(name = RocksimCommonConstants.ROCK_SIM_DOCUMENT) -@XmlAccessorType(XmlAccessType.FIELD) -public class RocksimDocumentDTO { - - @XmlElement(name = RocksimCommonConstants.FILE_VERSION) - private final String version = "4"; - - @XmlElement(name = RocksimCommonConstants.DESIGN_INFORMATION) - private RocksimDesignDTO design; - - /** - * Constructor. - */ - public RocksimDocumentDTO() { - } - - /** - * Get the subordinate design DTO. - * - * @return the RocksimDesignDTO - */ - public RocksimDesignDTO getDesign() { - return design; - } - - /** - * Setter. - * - * @param theDesign - */ - public void setDesign(RocksimDesignDTO theDesign) { - this.design = theDesign; - } - - /** - * Getter. - * - * @return - */ - public String getVersion() { - return version; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/RocksimSaver.java b/core/src/net/sf/openrocket/file/rocksim/export/RocksimSaver.java deleted file mode 100644 index 9d601efb..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/RocksimSaver.java +++ /dev/null @@ -1,129 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.StorageOptions; -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.startup.Application; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.StringWriter; - -/** - * This class is responsible for converting an OpenRocket design to a Rocksim design. - */ -public class RocksimSaver extends RocketSaver { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * This method marshals an OpenRocketDocument (OR design) to Rocksim-compliant XML. - * - * @param doc the OR design - * @return Rocksim-compliant XML - */ - public String marshalToRocksim(OpenRocketDocument doc) { - - try { - JAXBContext binder = JAXBContext.newInstance(RocksimDocumentDTO.class); - Marshaller marshaller = binder.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - StringWriter sw = new StringWriter(); - - marshaller.marshal(toRocksimDocumentDTO(doc), sw); - return sw.toString(); - } catch (Exception e) { - log.error("Could not marshall a design to Rocksim format. " + e.getMessage()); - } - - return null; - } - - @Override - public void save(OutputStream dest, OpenRocketDocument doc, StorageOptions options) throws IOException { - log.info("Saving .rkt file"); - - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(dest, "UTF-8")); - writer.write(marshalToRocksim(doc)); - writer.flush(); - writer.close(); - } - - @Override - public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) { - return marshalToRocksim(doc).length(); - } - - /** - * Root conversion method. It iterates over all subcomponents. - * - * @param doc the OR design - * @return a corresponding Rocksim representation - */ - private RocksimDocumentDTO toRocksimDocumentDTO(OpenRocketDocument doc) { - RocksimDocumentDTO rsd = new RocksimDocumentDTO(); - - rsd.setDesign(toRocksimDesignDTO(doc.getRocket())); - - return rsd; - } - - private RocksimDesignDTO toRocksimDesignDTO(Rocket rocket) { - RocksimDesignDTO result = new RocksimDesignDTO(); - result.setDesign(toRocketDesignDTO(rocket)); - return result; - } - - private RocketDesignDTO toRocketDesignDTO(Rocket rocket) { - RocketDesignDTO result = new RocketDesignDTO(); - - MassCalculator massCalc = new BasicMassCalculator(); - - final double cg = massCalc.getCG(new Configuration(rocket), MassCalculator.MassCalcType.NO_MOTORS).x * - RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - int stageCount = rocket.getStageCount(); - if (stageCount == 3) { - result.setStage321CG(cg); - } else if (stageCount == 2) { - result.setStage32CG(cg); - } else { - result.setStage3CG(cg); - } - - result.setName(rocket.getName()); - result.setStageCount(stageCount); - if (stageCount > 0) { - result.setStage3(toStageDTO(rocket.getChild(0).getStage(), result, 3)); - } - if (stageCount > 1) { - result.setStage2(toStageDTO(rocket.getChild(1).getStage(), result, 2)); - } - if (stageCount > 2) { - result.setStage1(toStageDTO(rocket.getChild(2).getStage(), result, 1)); - } - //Set the last serial number element and reset it. - result.setLastSerialNumber(BasePartDTO.getCurrentSerialNumber()); - BasePartDTO.resetCurrentSerialNumber(); - return result; - } - - private StageDTO toStageDTO(Stage stage, RocketDesignDTO designDTO, int stageNumber) { - return new StageDTO(stage, designDTO, stageNumber); - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/StageDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/StageDTO.java deleted file mode 100644 index e0303e7f..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/StageDTO.java +++ /dev/null @@ -1,107 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.ArrayList; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import java.util.List; - -/** - * Placeholder for a Rocksim Stage. - */ -@XmlAccessorType(XmlAccessType.FIELD) -public class StageDTO { - - @XmlElementRefs({ - @XmlElementRef(name = RocksimCommonConstants.BODY_TUBE, type = BodyTubeDTO.class), - @XmlElementRef(name = RocksimCommonConstants.NOSE_CONE, type = NoseConeDTO.class), - @XmlElementRef(name = RocksimCommonConstants.TRANSITION, type = TransitionDTO.class) - }) - private List externalPart = new ArrayList(); - - /** - * Default constructor. - */ - public StageDTO() { - } - - /** - * Copy constructor. - * - * @param theORStage the OR stage - * @param design the encompassing container DTO - * @param stageNumber the stage number (3 is always at the top, even if it's the only one) - */ - public StageDTO(Stage theORStage, RocketDesignDTO design, int stageNumber) { - - if (stageNumber == 3) { - if (theORStage.isMassOverridden()) { - design.setStage3Mass(theORStage.getMass() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - design.setUseKnownMass(1); - } - if (theORStage.isCGOverridden()) { - design.setStage3CG(theORStage.getOverrideCGX() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - } - - if (stageNumber == 2) { - if (theORStage.isMassOverridden()) { - design.setStage2Mass(theORStage.getMass() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - design.setUseKnownMass(1); - } - if (theORStage.isCGOverridden()) { - design.setStage2CGAlone(theORStage.getOverrideCGX() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - } - - if (stageNumber == 1) { - if (theORStage.isMassOverridden()) { - design.setStage1Mass(theORStage.getMass() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - design.setUseKnownMass(1); - } - if (theORStage.isCGOverridden()) { - design.setStage1CGAlone(theORStage.getOverrideCGX() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - } - - List children = theORStage.getChildren(); - for (int i = 0; i < children.size(); i++) { - RocketComponent rocketComponents = children.get(i); - if (rocketComponents instanceof NoseCone) { - addExternalPart(toNoseConeDTO((NoseCone) rocketComponents)); - } else if (rocketComponents instanceof BodyTube) { - addExternalPart(toBodyTubeDTO((BodyTube) rocketComponents)); - } else if (rocketComponents instanceof Transition) { - addExternalPart(toTransitionDTO((Transition) rocketComponents)); - } - } - } - - public List getExternalPart() { - return externalPart; - } - - public void addExternalPart(BasePartDTO theExternalPartDTO) { - externalPart.add(theExternalPartDTO); - } - - private NoseConeDTO toNoseConeDTO(NoseCone nc) { - return new NoseConeDTO(nc); - } - - private BodyTubeDTO toBodyTubeDTO(BodyTube bt) { - return new BodyTubeDTO(bt); - } - - private TransitionDTO toTransitionDTO(Transition tran) { - return new TransitionDTO(tran); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/StreamerDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/StreamerDTO.java deleted file mode 100644 index c959ce54..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/StreamerDTO.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.Streamer; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class models a Rocksim XML element for a streamer. - */ -@XmlRootElement(name = RocksimCommonConstants.STREAMER) -@XmlAccessorType(XmlAccessType.FIELD) -public class StreamerDTO extends BasePartDTO { - - @XmlElement(name = RocksimCommonConstants.WIDTH) - private double width = 0d; - @XmlElement(name = RocksimCommonConstants.DRAG_COEFFICIENT) - private double dragCoefficient = 0.75d; - - /** - * The default constructor. - */ - public StreamerDTO() { - } - - /** - * Copy constructor. This constructor fully populates this instance with values taken from the OR component. - * - * @param theORStreamer the OR streamer component - */ - public StreamerDTO(Streamer theORStreamer) { - super(theORStreamer); - setWidth(theORStreamer.getStripWidth() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setDragCoefficient(theORStreamer.getCD()); - } - - public double getWidth() { - return width; - } - - public void setWidth(double theWidth) { - width = theWidth; - } - - public double getDragCoefficient() { - return dragCoefficient; - } - - public void setDragCoefficient(double theDragCoefficient) { - dragCoefficient = theDragCoefficient; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/TransitionDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/TransitionDTO.java deleted file mode 100644 index 56360560..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/TransitionDTO.java +++ /dev/null @@ -1,102 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.Transition; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class models a transition XML element in Rocksim file format. - */ -@XmlRootElement(name = RocksimCommonConstants.TRANSITION) -@XmlAccessorType(XmlAccessType.FIELD) -public class TransitionDTO extends AbstractTransitionDTO { - - - @XmlElement(name = RocksimCommonConstants.FRONT_SHOULDER_LEN) - private double frontShoulderLen = 0d; - @XmlElement(name = RocksimCommonConstants.REAR_SHOULDER_LEN) - private double rearShoulderLen = 0d; - @XmlElement(name = RocksimCommonConstants.FRONT_SHOULDER_DIA) - private double frontShoulderDia = 0d; - @XmlElement(name = RocksimCommonConstants.REAR_SHOULDER_DIA) - private double rearShoulderDia = 0d; - @XmlElement(name = RocksimCommonConstants.FRONT_DIA) - private double frontDia = 0d; - @XmlElement(name = RocksimCommonConstants.REAR_DIA) - private double rearDia = 0d; - - /** - * Default constructor. - */ - public TransitionDTO() { - } - - /** - * Copy constructor. This TransitionDTO instance will be as equivalent as possible to the OR tran - * once the constructor returns. No further modification (invoking setters) is necessary. - * - * @param theORTransition the OR transition - */ - public TransitionDTO(Transition theORTransition) { - super(theORTransition); - setFrontDia(theORTransition.getForeRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setRearDia(theORTransition.getAftRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setFrontShoulderDia(theORTransition.getForeShoulderRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setFrontShoulderLen(theORTransition.getForeShoulderLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - setRearShoulderDia(theORTransition.getAftShoulderRadius() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - setRearShoulderLen(theORTransition.getAftShoulderLength() * RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - - - } - public double getFrontShoulderLen() { - return frontShoulderLen; - } - - public void setFrontShoulderLen(double theFrontShoulderLen) { - frontShoulderLen = theFrontShoulderLen; - } - - public double getRearShoulderLen() { - return rearShoulderLen; - } - - public void setRearShoulderLen(double theRearShoulderLen) { - rearShoulderLen = theRearShoulderLen; - } - - public double getFrontShoulderDia() { - return frontShoulderDia; - } - - public void setFrontShoulderDia(double theFrontShoulderDia) { - frontShoulderDia = theFrontShoulderDia; - } - - public double getRearShoulderDia() { - return rearShoulderDia; - } - - public void setRearShoulderDia(double theRearShoulderDia) { - rearShoulderDia = theRearShoulderDia; - } - - public double getFrontDia() { - return frontDia; - } - - public void setFrontDia(double theFrontDia) { - frontDia = theFrontDia; - } - - public double getRearDia() { - return rearDia; - } - - public void setRearDia(double theRearDia) { - rearDia = theRearDia; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/export/TubeCouplerDTO.java b/core/src/net/sf/openrocket/file/rocksim/export/TubeCouplerDTO.java deleted file mode 100644 index 8debc947..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/export/TubeCouplerDTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.rocketcomponent.TubeCoupler; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Conversion DTO for a TubeCoupler. TubeCoupler's are represented as Rings in Rocksim. - */ -@XmlRootElement(name = RocksimCommonConstants.RING) -@XmlAccessorType(XmlAccessType.FIELD) -public class TubeCouplerDTO extends CenteringRingDTO { - - /** - * Constructor. - * - * @param tc an OR TubeCoupler - */ - public TubeCouplerDTO(TubeCoupler tc) { - super(tc); - setUsageCode(UsageCode.TubeCoupler); - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/AttachedPartsHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/AttachedPartsHandler.java deleted file mode 100644 index cb019fa3..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/AttachedPartsHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * AttachedPartsHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.AbstractElementHandler; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.rocketcomponent.RocketComponent; - -import java.util.HashMap; - -/** - * A SAX handler for the Rocksim AttachedParts XML type. - */ -class AttachedPartsHandler extends AbstractElementHandler { - /** The parent component. */ - private final RocketComponent component; - - /** - * Constructor. - * - * @param c the parent - * - * @throws IllegalArgumentException thrown if c is null - */ - public AttachedPartsHandler(RocketComponent c) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of any attached part may not be null."); - } - component = c; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - if (RocksimCommonConstants.FIN_SET.equals(element)) { - return new FinSetHandler(component); - } - if (RocksimCommonConstants.CUSTOM_FIN_SET.equals(element)) { - return new FinSetHandler(component); - } - if (RocksimCommonConstants.LAUNCH_LUG.equals(element)) { - return new LaunchLugHandler(component, warnings); - } - if (RocksimCommonConstants.PARACHUTE.equals(element)) { - return new ParachuteHandler(component, warnings); - } - if (RocksimCommonConstants.STREAMER.equals(element)) { - return new StreamerHandler(component, warnings); - } - if (RocksimCommonConstants.MASS_OBJECT.equals(element)) { - return new MassObjectHandler(component, warnings); - } - if (RocksimCommonConstants.RING.equals(element)) { - return new RingHandler(component, warnings); - } - if (RocksimCommonConstants.BODY_TUBE.equals(element)) { - return new InnerBodyTubeHandler(component, warnings); - } - if (RocksimCommonConstants.TRANSITION.equals(element)) { - return new TransitionHandler(component, warnings); - } - if (RocksimCommonConstants.TUBE_FIN_SET.equals(element)) { - warnings.add("Tube fins are not currently supported. Ignoring."); - } - if (RocksimCommonConstants.RING_TAIL.equals(element)) { - warnings.add("Ring tails are not currently supported. Ignoring."); - } - if (RocksimCommonConstants.EXTERNAL_POD.equals(element)) { - warnings.add("Pods are not currently supported. Ignoring."); - } - return null; - } -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/BaseHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/BaseHandler.java deleted file mode 100644 index 35296d41..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/BaseHandler.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * BaseHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimDensityType; -import net.sf.openrocket.file.simplesax.AbstractElementHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.RocketComponent; - -import org.xml.sax.SAXException; - -/** - * An abstract base class that handles common parsing. All Rocksim component handlers are subclassed from here. - * - * @param the specific RocketComponent subtype for which the concrete handler can create - */ -public abstract class BaseHandler extends AbstractElementHandler { - - /** - * Prepend rocksim materials. - */ - public static final String ROCKSIM_MATERIAL_PREFIX = "RS: "; - /** - * The overridden mass. - */ - private Double mass = 0d; - /** - * The overridden Cg. - */ - private Double cg = 0d; - /** - * The density of the material in the component. - */ - private Double density = 0d; - /** - * The internal Rocksim density type. - */ - private RocksimDensityType densityType = RocksimDensityType.ROCKSIM_BULK; - - /** - * The material name. - */ - private String materialName = ""; - - /** - * The SAX method called when the closing element tag is reached. - * - * @param element the element name. - * @param attributes attributes of the element. - * @param content the textual content of the element. - * @param warnings the warning set to store warnings in. - * - * @throws SAXException - */ - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - final C component = getComponent(); - try { - if (RocksimCommonConstants.NAME.equals(element)) { - component.setName(content); - } - if (RocksimCommonConstants.KNOWN_MASS.equals(element)) { - mass = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - } - if (RocksimCommonConstants.DENSITY.equals(element)) { - density = Math.max(0d, Double.parseDouble(content)); - } - if (RocksimCommonConstants.KNOWN_CG.equals(element)) { - cg = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.USE_KNOWN_CG.equals(element)) { //Rocksim sets UseKnownCG to true to control the override of both cg and mass - boolean override = "1".equals(content); - setOverride(component, override, mass, cg); - } - if (RocksimCommonConstants.DENSITY_TYPE.equals(element)) { - densityType = RocksimDensityType.fromCode(Integer.parseInt(content)); - } - } catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void endHandler(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - /* Because of the order of XML elements in Rocksim, not all information is known at the time it really needs - to be acted upon. So we keep temporary instance variables to be used here at the end of the parsing. - */ - density = computeDensity(densityType, density); - RocketComponent component = getComponent(); - updateComponentMaterial(component, materialName, getMaterialType(), density); - } - - /** - * Compute the density. Rocksim does strange things with densities. For some streamer material it's in cubic, - * rather than square, units. In those cases it needs to be converted to an appropriate SURFACE material density. - * Some G10 fiberglass materials are in cubic units, other G10 fiberglass is in square units. And due to a Rocksim - * bug, some densities are 0 when they clearly should not be. - *

- * This may be overridden for specific component density computations. - * - * @param type the rocksim density - * @param rawDensity the density as specified in the Rocksim design file - * - * @return a value in OpenRocket SURFACE density units - */ - protected double computeDensity(RocksimDensityType type, double rawDensity) { - return rawDensity / type.asOpenRocket(); - } - - /** - * If the Rocksim component does not override the mass, then create a Material based upon the density defined for - * that component. This *should* result in a consistent representation of Cg between Rocksim and OpenRocket. - * - * @param component the component - * @param type the type of the material - * @param density the density in g/cm^3 - * @param definedMaterial the material that is currently defined on the component; used only to get the name as it - * appears in Rocksim - */ - public static void updateComponentMaterial(RocketComponent component, String definedMaterial, Material.Type type, - double density) { - if (definedMaterial != null) { - Material custom = createCustomMaterial(type, definedMaterial, density); - setMaterial(component, custom); - } - } - - /** - * Override the mass and Cg of the component. - * - * @param component the component - * @param override true if any override should happen - * @param mass the override mass - * @param cg the override cg - */ - public static void setOverride(RocketComponent component, boolean override, double mass, double cg) { - if (override) { - component.setCGOverridden(override); - component.setMassOverridden(override); - component.setOverrideSubcomponents(false); //Rocksim does not support this type of override - component.setOverrideMass(mass); - component.setOverrideCGX(cg); - } - } - - /** - * Get the component this handler is working upon. - * - * @return a component - */ - protected abstract C getComponent(); - - /** - * Get the required type of material for this component. - * - * @return the required material type - */ - protected abstract Material.Type getMaterialType(); - - /** - * Some CG positions in Rocksim do not correspond to the CG position reference in OpenRocket. - * - * @param theCG the CG value to really use when overriding CG on the OpenRocket component - */ - protected void setCG(double theCG) { - cg = theCG; - } - - /** - * Set the material name as specified in the Rocksim design file. - * - * @param content the material name - */ - protected void setMaterialName(String content) { - materialName = content; - } - - /** - * Get the Rocksim enum of the component's density type. - * - * @return a Rocksim density type - */ - protected RocksimDensityType getDensityType() { - return densityType; - } - - /** - * Add child to parent only if the child is compatible. Otherwise add to warning set. - * - * @param parent the parent component - * @param child the child component - * @param warnings the warning set - * - * @return true if the child is compatible with parent - */ - protected static boolean isCompatible(RocketComponent parent, Class child, WarningSet warnings) { - return isCompatible(parent, child, warnings, false); - } - - /** - * Add child to parent only if the child is compatible. Otherwise add to warning set. - * - * @param parent the parent component - * @param child the child component - * @param warnings the warning set - * @param suppressWarnings suppress warnings, just return the boolean - * - * @return true if the child is compatible with parent - */ - protected static boolean isCompatible(RocketComponent parent, Class child, - WarningSet warnings, - boolean suppressWarnings) { - if (!parent.isCompatible(child)) { - if (!suppressWarnings) { - warnings.add(child.getName() + " can not be attached to " - + parent.getComponentName() + ", ignoring component."); - } - return false; - } - else { - return true; - } - } - - /** - * Create a custom material based on the density. - * - * @param type the type of the material - * @param name the name of the component - * @param density the density - * - * @return a Material instance - */ - public static Material createCustomMaterial(Material.Type type, String name, double density) { - return Databases.findMaterial(type, name, density); - } - - /** - * Set the material onto an instance of RocketComponent. This is done because only some subtypes of RocketComponent - * have the setMaterial method. Unfortunately the supertype cannot be used. - * - * @param component the component who's material is to be set - * @param material the material to be set on the component (defined by getComponent()) - */ - private static void setMaterial(RocketComponent component, Material material) { - try { - final Method method = getMethod(component, "setMaterial", new Class[] { Material.class }); - if (method != null) { - method.invoke(component, material); - } - } catch (IllegalAccessException ignored) { - } catch (InvocationTargetException ignored) { - } - } - - /** - * Find a method by name and argument list. - * - * @param component the component who's material is to be set - * @param name the method name - * @param args the class types of the parameters - * - * @return the Method instance, or null - */ - private static Method getMethod(RocketComponent component, String name, Class[] args) { - Method method = null; - try { - method = component.getClass().getMethod(name, args); - } catch (NoSuchMethodException ignored) { - } - return method; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/BodyTubeHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/BodyTubeHandler.java deleted file mode 100644 index a528f8d1..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/BodyTubeHandler.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * BodyTubeHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimFinishCode; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A SAX handler for Rocksim Body Tubes. - */ -class BodyTubeHandler extends BaseHandler { - /** - * The OpenRocket BodyTube. - */ - private final BodyTube bodyTube; - - /** - * Constructor. - * - * @param c parent component - * @param warnings the warning set - * @throws IllegalArgumentException thrown if c is null - */ - public BodyTubeHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of a body tube may not be null."); - } - bodyTube = new BodyTube(); - if (isCompatible(c, BodyTube.class, warnings)) { - c.addChild(bodyTube); - } - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - if (RocksimCommonConstants.ATTACHED_PARTS.equals(element)) { - return new AttachedPartsHandler(bodyTube); - } - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.OD.equals(element)) { - bodyTube.setOuterRadius(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - if (RocksimCommonConstants.ID.equals(element)) { - final double r = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS; - bodyTube.setInnerRadius(r); - } - if (RocksimCommonConstants.LEN.equals(element)) { - bodyTube.setLength(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.FINISH_CODE.equals(element)) { - bodyTube.setFinish(RocksimFinishCode.fromCode(Integer.parseInt(content)).asOpenRocket()); - } - if (RocksimCommonConstants.IS_MOTOR_MOUNT.equals(element)) { - bodyTube.setMotorMount("1".equals(content)); - } - if (RocksimCommonConstants.ENGINE_OVERHANG.equals(element)) { - bodyTube.setMotorOverhang(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * Get the component this handler is working upon. - * - * @return a component - */ - @Override - public BodyTube getComponent() { - return bodyTube; - } - - /** - * Get the required type of material for this component. - * - * @return BULK - */ - public Material.Type getMaterialType() { - return Material.Type.BULK; - } -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/FinSetHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/FinSetHandler.java deleted file mode 100644 index 01b49030..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/FinSetHandler.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * FinSetHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimFinishCode; -import net.sf.openrocket.file.rocksim.RocksimLocationMode; -import net.sf.openrocket.file.simplesax.AbstractElementHandler; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.IllegalFinPointException; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.util.Coordinate; -import org.xml.sax.SAXException; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -/** - * A SAX handler for Rocksim fin sets. Because the type of fin may not be known first (in Rocksim file format, the fin - * shape type is in the middle of the XML structure), and because we're using SAX not DOM, all of the fin - * characteristics are kept here until the closing FinSet tag. At that point, asOpenRocket method is called - * to construct the corresponding OpenRocket FinSet. - */ -class FinSetHandler extends AbstractElementHandler { - /** - * The parent component. - */ - private final RocketComponent component; - - /** - * The name of the fin. - */ - private String name; - /** - * The Rocksim fin shape code. - */ - private int shapeCode; - /** - * The location of the fin on its parent. - */ - private double location = 0.0d; - /** - * The OpenRocket Position which gives the absolute/relative positioning for location. - */ - private RocketComponent.Position position; - /** - * The number of fins in this fin set. - */ - private int finCount; - /** - * The length of the root chord. - */ - private double rootChord = 0.0d; - /** - * The length of the tip chord. - */ - private double tipChord = 0.0d; - /** - * The length of the mid-chord (aka height). - */ - private double midChordLen = 0.0d; - /** - * The distance of the leading edge from root to top. - */ - private double sweepDistance = 0.0d; - /** - * The angle the fins have been rotated from the y-axis, if looking down the tube, in radians. - */ - private double radialAngle = 0.0d; - /** - * The thickness of the fins. - */ - private double thickness; - /** - * The finish of the fins. - */ - private ExternalComponent.Finish finish; - /** - * The shape of the tip. - */ - private int tipShapeCode; - /** - * The length of the TTW tab. - */ - private double tabLength = 0.0d; - /** - * The depth of the TTW tab. - */ - private double tabDepth = 0.0d; - /** - * The offset of the tab, from the front of the fin. - */ - private double taboffset = 0.0d; - /** - * The elliptical semi-span (height). - */ - private double semiSpan; - /** - * The list of custom points. - */ - private String pointList; - /** - * Override the Cg and mass. - */ - private boolean override = false; - /** - * The overridden mass. - */ - private Double mass = 0d; - /** - * The overridden Cg. - */ - private Double cg = 0d; - /** - * The density of the material in the component. - */ - private Double density = 0d; - /** - * The material name. - */ - private String materialName = ""; - /** - * The Rocksim calculated mass. - */ - private Double calcMass = 0d; - /** - * The Rocksim calculated cg. - */ - private Double calcCg = 0d; - - - /** - * Constructor. - * - * @param c the parent - * - * @throws IllegalArgumentException thrown if c is null - */ - public FinSetHandler (RocketComponent c) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of a fin set may not be null."); - } - component = c; - } - - @Override - public ElementHandler openElement (String element, HashMap attributes, WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement (String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - try { - if (RocksimCommonConstants.NAME.equals(element)) { - name = content; - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - materialName = content; - } - if (RocksimCommonConstants.FINISH_CODE.equals(element)) { - finish = RocksimFinishCode.fromCode(Integer.parseInt(content)).asOpenRocket(); - } - if (RocksimCommonConstants.XB.equals(element)) { - location = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.LOCATION_MODE.equals(element)) { - position = RocksimLocationMode.fromCode(Integer.parseInt(content)).asOpenRocket(); - } - if (RocksimCommonConstants.FIN_COUNT.equals(element)) { - finCount = Integer.parseInt(content); - } - if (RocksimCommonConstants.ROOT_CHORD.equals(element)) { - rootChord = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.TIP_CHORD.equals(element)) { - tipChord = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.SEMI_SPAN.equals(element)) { - semiSpan = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if ("MidChordLen".equals(element)) { - midChordLen = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.SWEEP_DISTANCE.equals(element)) { - sweepDistance = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.THICKNESS.equals(element)) { - thickness = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.TIP_SHAPE_CODE.equals(element)) { - tipShapeCode = Integer.parseInt(content); - } - if (RocksimCommonConstants.TAB_LENGTH.equals(element)) { - tabLength = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.TAB_DEPTH.equals(element)) { - tabDepth = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.TAB_OFFSET.equals(element)) { - taboffset = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.RADIAL_ANGLE.equals(element)) { - radialAngle = Double.parseDouble(content); - } - if (RocksimCommonConstants.SHAPE_CODE.equals(element)) { - shapeCode = Integer.parseInt(content); - } - if (RocksimCommonConstants.POINT_LIST.equals(element)) { - pointList = content; - } - if (RocksimCommonConstants.KNOWN_MASS.equals(element)) { - mass = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - } - if (RocksimCommonConstants.DENSITY.equals(element)) { - density = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_BULK_DENSITY); - } - if (RocksimCommonConstants.KNOWN_CG.equals(element)) { - cg = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - } - if (RocksimCommonConstants.USE_KNOWN_CG.equals(element)) { - override = "1".equals(content); - } - if (RocksimCommonConstants.CALC_MASS.equals(element)) { - calcMass = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS; - } - if (RocksimCommonConstants.CALC_CG.equals(element)) { - calcCg = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - @Override - public void endHandler (String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - //Create the fin set and correct for overrides and actual material densities - final FinSet finSet = asOpenRocket(warnings); - if (component.isCompatible(finSet)) { - BaseHandler.setOverride(finSet, override, mass, cg); - if (!override && finSet.getCrossSection().equals(FinSet.CrossSection.AIRFOIL)) { - //Override mass anyway. This is done only for AIRFOIL because Rocksim does not compute different - //mass/cg for different cross sections, but OpenRocket does. This can lead to drastic differences - //in mass. To counteract that, the cross section value is retained but the mass/cg is overridden - //with the calculated values from Rocksim. This will best approximate the Rocksim design in OpenRocket. - BaseHandler.setOverride(finSet, true, calcMass, calcCg); - } - BaseHandler.updateComponentMaterial(finSet, materialName, Material.Type.BULK, density); - component.addChild(finSet); - } - else { - warnings.add(finSet.getComponentName() + " can not be attached to " - + component.getComponentName() + ", ignoring component."); - } - } - - - /** - * Convert the parsed Rocksim data values in this object to an instance of OpenRocket's FinSet. - * - * @param warnings the warning set to convey incompatibilities to the user - * - * @return a FinSet instance - */ - public FinSet asOpenRocket (WarningSet warnings) { - FinSet result; - - if (shapeCode == 0) { - //Trapezoidal - result = new TrapezoidFinSet(); - ((TrapezoidFinSet) result).setFinShape(rootChord, tipChord, sweepDistance, semiSpan, thickness); - } - else if (shapeCode == 1) { - //Elliptical - result = new EllipticalFinSet(); - ((EllipticalFinSet) result).setHeight(semiSpan); - ((EllipticalFinSet) result).setLength(rootChord); - } - else if (shapeCode == 2) { - - result = new FreeformFinSet(); - try { - ((FreeformFinSet) result).setPoints(toCoordinates(pointList, warnings)); - } - catch (IllegalFinPointException e) { - warnings.add("Illegal fin point set. " + e.getMessage() + " Ignoring."); - } - } - else { - return null; - } - result.setThickness(thickness); - result.setName(name); - result.setFinCount(finCount); - result.setFinish(finish); - //All TTW tabs in Rocksim are relative to the front of the fin. - result.setTabRelativePosition(FinSet.TabRelativePosition.FRONT); - result.setTabHeight(tabDepth); - result.setTabLength(tabLength); - result.setTabShift(taboffset); - result.setBaseRotation(radialAngle); - result.setCrossSection(convertTipShapeCode(tipShapeCode)); - result.setRelativePosition(position); - PositionDependentHandler.setLocation(result, position, location); - return result; - - } - - /** - * Convert a Rocksim string that represents fin plan points into an array of OpenRocket coordinates. - * - * @param pointList a comma and pipe delimited string of X,Y coordinates from Rocksim. This is of the format: - *

x0,y0|x1,y1|x2,y2|... 
- * @param warnings the warning set to convey incompatibilities to the user - * - * @return an array of OpenRocket Coordinates - */ - private Coordinate[] toCoordinates (String pointList, WarningSet warnings) { - List result = new ArrayList(); - if (pointList != null && pointList.length() > 0) { - String[] points = pointList.split("\\Q|\\E"); - for (String point : points) { - String[] aPoint = point.split(","); - try { - if (aPoint.length > 1) { - Coordinate c = new Coordinate( - Double.parseDouble(aPoint[0]) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, - Double.parseDouble(aPoint[1]) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - result.add(c); - } - else { - warnings.add("Invalid fin point pair."); - } - } - catch (NumberFormatException nfe) { - warnings.add("Fin point not in numeric format."); - } - } - if (!result.isEmpty()) { - //OpenRocket requires fin plan points be ordered from leading root chord to trailing root chord in the - //Coordinate array. - Coordinate last = result.get(result.size() - 1); - if (last.x == 0 && last.y == 0) { - Collections.reverse(result); - } - } - } - final Coordinate[] coords = new Coordinate[result.size()]; - return result.toArray(coords); - } - - - /** - * Convert a Rocksim tip shape to an OpenRocket CrossSection. - * - * @param tipShape the tip shape code from Rocksim - * - * @return a CrossSection instance - */ - public static FinSet.CrossSection convertTipShapeCode (int tipShape) { - switch (tipShape) { - case 0: - return FinSet.CrossSection.SQUARE; - case 1: - return FinSet.CrossSection.ROUNDED; - case 2: - return FinSet.CrossSection.AIRFOIL; - default: - return FinSet.CrossSection.SQUARE; - } - } - - public static int convertTipShapeCode (FinSet.CrossSection cs) { - if (FinSet.CrossSection.ROUNDED.equals(cs)) { - return 1; - } - if (FinSet.CrossSection.AIRFOIL.equals(cs)) { - return 2; - } - return 0; - } - -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/InnerBodyTubeHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/InnerBodyTubeHandler.java deleted file mode 100644 index 0d264fe0..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/InnerBodyTubeHandler.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * InnerBodyTubeHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A SAX handler for Rocksim inside tubes. - */ -class InnerBodyTubeHandler extends PositionDependentHandler { - - /** - * The OpenRocket InnerTube instance. - */ - private final InnerTube bodyTube; - - /** - * Constructor. - * - * @param c the parent component - * @param warnings the warning set - * @throws IllegalArgumentException thrown if c is null - */ - public InnerBodyTubeHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of an inner tube may not be null."); - } - bodyTube = new InnerTube(); - if (isCompatible(c, InnerTube.class, warnings)) { - c.addChild(bodyTube); - } - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - if (RocksimCommonConstants.ATTACHED_PARTS.equals(element)) { - return new AttachedPartsHandler(bodyTube); - } - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.OD.equals(element)) { - bodyTube.setOuterRadius(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - if (RocksimCommonConstants.ID.equals(element)) { - final double r = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS; - bodyTube.setInnerRadius(r); - } - if (RocksimCommonConstants.LEN.equals(element)) { - bodyTube.setLength(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.IS_MOTOR_MOUNT.equals(element)) { - bodyTube.setMotorMount("1".equals(content)); - } - if (RocksimCommonConstants.ENGINE_OVERHANG.equals(element)) { - bodyTube.setMotorOverhang(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - if (RocksimCommonConstants.RADIAL_ANGLE.equals(element)) { - bodyTube.setRadialDirection(Double.parseDouble(content)); - } - if (RocksimCommonConstants.RADIAL_LOC.equals(element)) { - bodyTube.setRadialPosition(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * Get the InnerTube component this handler is working upon. - * - * @return an InnerTube component - */ - @Override - public InnerTube getComponent() { - return bodyTube; - } - - /** - * Set the relative position onto the component. This cannot be done directly because setRelativePosition is not - * public in all components. - * - * @param position the OpenRocket position - */ - @Override - public void setRelativePosition(RocketComponent.Position position) { - bodyTube.setRelativePosition(position); - } - - /** - * Get the required type of material for this component. - * - * @return BULK - */ - @Override - public Material.Type getMaterialType() { - return Material.Type.BULK; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/LaunchLugHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/LaunchLugHandler.java deleted file mode 100644 index 33fd62d6..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/LaunchLugHandler.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * LaunchLugHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimFinishCode; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * The SAX handler for Rocksim Launch Lugs. - */ -class LaunchLugHandler extends PositionDependentHandler { - - /** - * The OpenRocket LaunchLug instance. - */ - private final LaunchLug lug; - - /** - * Constructor. - * - * @param c the parent - * @param warnings the warning set - * - * @throws IllegalArgumentException thrown if c is null - */ - public LaunchLugHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of a launch lug may not be null."); - } - lug = new LaunchLug(); - if (isCompatible(c, LaunchLug.class, warnings)) { - c.addChild(lug); - } - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.OD.equals(element)) { - lug.setOuterRadius(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if (RocksimCommonConstants.ID.equals(element)) { - lug.setInnerRadius(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if (RocksimCommonConstants.LEN.equals(element)) { - lug.setLength(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - if (RocksimCommonConstants.RADIAL_ANGLE.equals(element)) { - lug.setRadialDirection(Double.parseDouble(content)); - } - if (RocksimCommonConstants.FINISH_CODE.equals(element)) { - lug.setFinish(RocksimFinishCode.fromCode(Integer.parseInt(content)).asOpenRocket()); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * Get the LaunchLug component this handler is working upon. - * - * @return a LaunchLug component - */ - @Override - public LaunchLug getComponent() { - return lug; - } - - /** - * Set the relative position onto the component. This cannot be done directly because setRelativePosition is not - * public in all components. - * - * @param position the OpenRocket position - */ - @Override - public void setRelativePosition(RocketComponent.Position position) { - lug.setRelativePosition(position); - } - - /** - * Get the required type of material for this component. - * - * @return BULK - */ - @Override - public Material.Type getMaterialType() { - return Material.Type.BULK; - } -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java deleted file mode 100644 index 2d918af9..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * MassObjectHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimDensityType; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.Coaxial; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.ShockCord; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A SAX handler for Rocksim's MassObject XML type. - */ -class MassObjectHandler extends PositionDependentHandler { - - /** - * The Rocksim Mass length fudge factor. Rocksim completely exaggerates the length of a mass object to the point - * that it looks ridiculous in OpenRocket. This fudge factor is here merely to get the typical mass object to - * render in the OpenRocket UI with it's bounds mostly inside it's parent. The odd thing about it is that Rocksim - * does not expose the length of a mass object in the UI and actually treats mass objects as point objects - not 3 - * or even 2 dimensional. - */ - public static final int MASS_LEN_FUDGE_FACTOR = 100; - - /** - * The OpenRocket MassComponent - counterpart to the RS MassObject. - */ - private final MassComponent mass; - - /** - * Reference to answer for getComponent(). - */ - private MassObject current; - - /** - * Parent. - */ - private RocketComponent parent; - - /** - * 0 == General, 1 == Shock Cord - */ - private int typeCode = 0; - - /** - * Constructor. l - * - * @param c the parent component - * @param warnings the warning set - * - * @throws IllegalArgumentException thrown if c is null - */ - public MassObjectHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of a mass component may not be null."); - } - mass = new MassComponent(); - current = mass; - parent = c; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - try { - if (RocksimCommonConstants.LEN.equals(element)) { - mass.setLength(Double.parseDouble(content) / (RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.KNOWN_MASS.equals(element)) { - mass.setComponentMass(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - } - if (RocksimCommonConstants.KNOWN_CG.equals(element)) { - //Setting the CG of the Mass Object to 0 is important because of the different ways that Rocksim and - //OpenRocket treat mass objects. Rocksim treats them as points (even though the data file contains a - //length) and because Rocksim sets the CG of the mass object to really be relative to the front of - //the parent. But that value is already assumed in the position and position value for the component. - //Thus it needs to be set to 0 to say that the mass object's CG is at the point of the mass object. - super.setCG(0); - } - if (RocksimCommonConstants.TYPE_CODE.equals(element)) { - typeCode = Integer.parseInt(content); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - @Override - public void endHandler(String element, HashMap attributes, String content, WarningSet warnings) throws - SAXException { - if (inferAsShockCord(typeCode, warnings)) { //Shock Cord - mapMassObjectAsShockCord(element, attributes, content, warnings); - } - else { // typeCode == 0 General Mass Object - if (isCompatible(parent, MassComponent.class, warnings)) { - parent.addChild(mass); - } - super.endHandler(element, attributes, content, warnings); - } - } - - /** - * Rocksim does not have a separate entity for Shock Cords. It has to be inferred. Sometimes the typeCode - * indicates it's a shock cord, but most times it does not. This is due to bugs in the Rocksim Component and - * Material databases. Try to infer a shock cord based on it's length and it's material type. It's somewhat - * arbitrary, but if the mass object's length is more than twice the length of it's parent component and it's a LINE - * material, then assume a shock cord. - * - * @param theTypeCode the code from the RKT XML file - * - * @return true if we think it's a shock cord - */ - private boolean inferAsShockCord(int theTypeCode, WarningSet warnings) { - return (theTypeCode == 1 || (mass.getLength() >= 2 * parent.getLength() && RocksimDensityType.ROCKSIM_LINE - .equals(getDensityType()))) && isCompatible(parent, ShockCord.class, warnings, true); - } - - /** - * If it appears that the mass object is a shock cord, then create an OR shock cord instance. - * - * @param element the element name - * @param attributes the attributes - * @param content the content of the element - * @param warnings the warning set to store warnings in. - * - * @throws org.xml.sax.SAXException not thrown - */ - private void mapMassObjectAsShockCord(final String element, final HashMap attributes, - final String content, final WarningSet warnings) throws SAXException { - ShockCord cord = new ShockCord(); - current = cord; - if (isCompatible(parent, ShockCord.class, warnings)) { - parent.addChild(cord); - } - super.endHandler(element, attributes, content, warnings); - cord.setName(mass.getName()); - - setOverride(cord, mass.isMassOverridden(), mass.getOverrideMass(), mass.getOverrideCGX()); - - cord.setRadialDirection(mass.getRadialDirection()); - cord.setRadialPosition(mass.getRadialPosition()); - cord.setRadius(mass.getRadius()); - - //Rocksim does not distinguish between total length of the cord and the packed length. Fudge the - //packed length and set the real length. - cord.setCordLength(mass.getLength()); - cord.setLength(cord.getCordLength() / MASS_LEN_FUDGE_FACTOR); - if (parent instanceof Coaxial) { - Coaxial parentCoaxial = (Coaxial) parent; - cord.setRadius(parentCoaxial.getInnerRadius()); - } - } - - /** - * Get the component this handler is working upon. This changes depending upon the type of mass object. - * - * @return a component - */ - @Override - public MassObject getComponent() { - return current; - } - - /** - * Set the relative position onto the component. This cannot be done directly because setRelativePosition is not - * public in all components. - * - * @param position the OpenRocket position - */ - public void setRelativePosition(RocketComponent.Position position) { - current.setRelativePosition(position); - } - - /** - * Get the required type of material for this component. Does not apply to MassComponents, but does apply to Shock - * Cords. - * - * @return LINE - */ - @Override - public Material.Type getMaterialType() { - return Material.Type.LINE; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/NoseConeHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/NoseConeHandler.java deleted file mode 100644 index b2f07c12..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/NoseConeHandler.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * NoseConeHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimFinishCode; -import net.sf.openrocket.file.rocksim.RocksimNoseConeCode; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * The SAX nose cone handler for Rocksim NoseCones. - */ -class NoseConeHandler extends BaseHandler { - - /** - * The OpenRocket NoseCone. - */ - private final NoseCone noseCone = new NoseCone(); - - /** - * The wall thickness. Used for hollow nose cones. - */ - private double thickness = 0d; - - /** - * Constructor. - * - * @param c the parent component to the nosecone - * @param warnings the warning set - * - * @throws IllegalArgumentException thrown if c is null - */ - public NoseConeHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent component of a nose cone may not be null."); - } - if (isCompatible(c, NoseCone.class, warnings)) { - c.addChild(noseCone); - noseCone.setAftRadiusAutomatic(false); - } - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - //Nose cones in Rocksim may have attached parts - namely Mass Objects - as children. - if (RocksimCommonConstants.ATTACHED_PARTS.equals(element)) { - return new AttachedPartsHandler(noseCone); - } - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.SHAPE_CODE.equals(element)) { - noseCone.setType(RocksimNoseConeCode.fromCode(Integer.parseInt(content)).asOpenRocket()); - } - if (RocksimCommonConstants.LEN.equals(element)) { - noseCone.setLength(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.BASE_DIA.equals(element)) { - noseCone.setAftRadius(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if (RocksimCommonConstants.WALL_THICKNESS.equals(element)) { - thickness = Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.SHOULDER_OD.equals(element)) { - noseCone.setAftShoulderRadius(Math.max(0, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if (RocksimCommonConstants.SHOULDER_LEN.equals(element)) { - noseCone.setAftShoulderLength(Math.max(0, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.SHAPE_PARAMETER.equals(element)) { - //The Rocksim ShapeParameter only applies to certain shapes, although it is included - //in the design file for all nose cones. Applying it when it should not be causes oddities so - //a check is made for the allowable shapes. - if (Transition.Shape.POWER.equals(noseCone.getType()) || - Transition.Shape.HAACK.equals(noseCone.getType()) || - Transition.Shape.PARABOLIC.equals(noseCone.getType())) { - noseCone.setShapeParameter(Double.parseDouble(content)); - } - } - if (RocksimCommonConstants.CONSTRUCTION_TYPE.equals(element)) { - int typeCode = Integer.parseInt(content); - if (typeCode == 0) { - //SOLID - noseCone.setFilled(true); - } - else if (typeCode == 1) { - //HOLLOW - noseCone.setFilled(false); - } - } - if (RocksimCommonConstants.FINISH_CODE.equals(element)) { - noseCone.setFinish(RocksimFinishCode.fromCode(Integer.parseInt(content)).asOpenRocket()); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - @Override - public void endHandler(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.endHandler(element, attributes, content, warnings); - - if (noseCone.isFilled()) { - noseCone.setAftShoulderThickness(noseCone.getAftShoulderRadius()); - } - else { - noseCone.setThickness(thickness); - noseCone.setAftShoulderThickness(thickness); - } - } - - /** - * Get the nose cone component this handler is working upon. - * - * @return a nose cone component - */ - @Override - public NoseCone getComponent() { - return noseCone; - } - - /** - * Get the required type of material for this component. - * - * @return BULK - */ - public Material.Type getMaterialType() { - return Material.Type.BULK; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/ParachuteHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/ParachuteHandler.java deleted file mode 100644 index cc47e24e..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/ParachuteHandler.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * ParachuteHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A SAX handler for Rocksim's Parachute XML type. - */ -class ParachuteHandler extends RecoveryDeviceHandler { - /** - * The OpenRocket Parachute instance - */ - private final Parachute chute; - /** - * The shroud line density. - */ - private double shroudLineDensity = 0.0d; - - /** - * Constructor. - * - * @param c the parent component - * @param warnings the warning set - * - * @throws IllegalArgumentException thrown if c is null - */ - public ParachuteHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent of a parachute may not be null."); - } - chute = new Parachute(); - if (isCompatible(c, Parachute.class, warnings)) { - c.addChild(chute); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - /** - * {@inheritDoc} - */ - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - try { - if (RocksimCommonConstants.DIAMETER.equals(element)) { - chute.setDiameter(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - /* Rocksim doesn't have a packed parachute radius, so we approximate it. */ - double packed; - RocketComponent parent = chute.getParent(); - if (parent instanceof BodyTube) { - packed = ((BodyTube) parent).getOuterRadius() * 0.9; - } - else if (parent instanceof InnerTube) { - packed = ((InnerTube) parent).getInnerRadius() * 0.9; - } - else { - packed = chute.getDiameter() * 0.025; - } - chute.setRadius(packed); - } - if (RocksimCommonConstants.SHROUD_LINE_COUNT.equals(element)) { - chute.setLineCount(Math.max(0, Integer.parseInt(content))); - } - if (RocksimCommonConstants.SHROUD_LINE_LEN.equals(element)) { - chute.setLineLength(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.SPILL_HOLE_DIA.equals(element)) { - //Not supported in OpenRocket - double spillHoleRadius = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS; - warnings.add("Parachute spill holes are not supported. Ignoring."); - } - if (RocksimCommonConstants.SHROUD_LINE_MASS_PER_MM.equals(element)) { - shroudLineDensity = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LINE_DENSITY; - } - if (RocksimCommonConstants.SHROUD_LINE_MATERIAL.equals(element)) { - chute.setLineMaterial(createCustomMaterial(Material.Type.LINE, content, shroudLineDensity)); - } - if (RocksimCommonConstants.DRAG_COEFFICIENT.equals(element)) { - chute.setCD(Double.parseDouble(content)); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * Get the component this handler is working upon. - * - * @return a component - */ - public Parachute getComponent() { - return chute; - } - -} - diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/PositionDependentHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/PositionDependentHandler.java deleted file mode 100644 index 0d04128a..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/PositionDependentHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * PositionDependentHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimLocationMode; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * An abstract base class that handles position dependencies for all lower level components that - * are position aware. - * - * @param the specific position dependent RocketComponent subtype for which the concrete handler can create - */ -public abstract class PositionDependentHandler extends BaseHandler { - - /** Temporary position value. */ - private Double positionValue = 0d; - - /** Temporary position. */ - private RocketComponent.Position position = RocketComponent.Position.TOP; - - /** - * {@inheritDoc} - */ - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - if (RocksimCommonConstants.XB.equals(element)) { - positionValue = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.LOCATION_MODE.equals(element)) { - position = RocksimLocationMode.fromCode(Integer.parseInt( - content)).asOpenRocket(); - } - } - - /** - * This method sets the position information onto the component. Rocksim splits the location/position - * information into two disparate data elements. Both pieces of data are necessary to map into OpenRocket's - * position model. - * - * @param element the element name - * @param attributes the attributes - * @param content the content of the element - * @param warnings the warning set to store warnings in. - * @throws org.xml.sax.SAXException not thrown - */ - @Override - public void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - super.endHandler(element, attributes, content, warnings); - setRelativePosition(position); - setLocation(getComponent(), position, positionValue); - } - - /** - * Set the relative position onto the component. This cannot be done directly because setRelativePosition is not - * public in all components. - * - * @param position the OpenRocket position - */ - protected abstract void setRelativePosition(RocketComponent.Position position); - - /** - * Set the position of a component. - * - * @param component the component - * @param position the relative position - * @param location the actual position value - */ - public static void setLocation(RocketComponent component, RocketComponent.Position position, double location) { - if (position.equals(RocketComponent.Position.BOTTOM)) { - component.setPositionValue(-1d * location); - } - else { - component.setPositionValue(location); - } - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/RecoveryDeviceHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/RecoveryDeviceHandler.java deleted file mode 100644 index 35aea771..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/RecoveryDeviceHandler.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * RecoveryDeviceHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimDensityType; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A handler specific to streamers and parachutes. This is done because Rocksim allows any type of material to be - * used as a recovery device, which causes oddities with respect to densities. Density computation is overridden - * here to try to correctly compute a material's density in OpenRocket units. - * - * @param either a Streamer or Parachute - */ -public abstract class RecoveryDeviceHandler extends PositionDependentHandler { - - /** - * The thickness. Not used by every component, and some component handlers may parse it for their own purposes. - */ - private double thickness = 0d; - /** - * The Rocksim calculated mass. Used only when not overridden and when Rocksim says density == 0 (Rocksim bug). - */ - private Double calcMass = 0d; - - /** - * {@inheritDoc} - */ - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.THICKNESS.equals(element)) { - thickness = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if (RocksimCommonConstants.CALC_MASS.equals(element)) { - calcMass = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - - /** - * Compute the density. Rocksim does strange things with densities. For some streamer material it's in cubic, - * rather than square, units. In those cases it needs to be converted to an appropriate SURFACE material density. - * - * @param type the rocksim density - * @param rawDensity the density as specified in the Rocksim design file - * @return a value in OpenRocket SURFACE density units - */ - protected double computeDensity(RocksimDensityType type, double rawDensity) { - - double result; - - if (rawDensity > 0d) { - //ROCKSIM_SURFACE is a square area density; compute normally - //ROCKSIM_LINE is a single length dimension (kg/m) but Rocksim ignores thickness for this type and treats - //it like a SURFACE. - if (RocksimDensityType.ROCKSIM_SURFACE.equals(type) || RocksimDensityType.ROCKSIM_LINE.equals(type)) { - result = rawDensity / RocksimDensityType.ROCKSIM_SURFACE.asOpenRocket(); - } - //ROCKSIM_BULK is a cubic area density; multiple by thickness to make per square area; the result, when - //multiplied by the area will then equal Rocksim's computed mass. - else { - result = (rawDensity / type.asOpenRocket()) * thickness; - } - } - else { - result = calcMass / getComponent().getArea(); - //A Rocksim bug on streamers/parachutes results in a 0 density at times. When that is detected, try - //to compute an approximate density from Rocksim's computed mass. - if (RocksimDensityType.ROCKSIM_BULK.equals(type)) { - //ROCKSIM_BULK is a cubic area density; multiple by thickness to make per square area - result *= thickness; - } - } - return result; - } - - /** - * Set the relative position onto the component. This cannot be done directly because setRelativePosition is not - * public in all components. - * - * @param position the OpenRocket position - */ - @Override - public void setRelativePosition(RocketComponent.Position position) { - getComponent().setRelativePosition(position); - } - - /** - * Get the required type of material for this component. This is the OpenRocket type, which does NOT always - * correspond to Rocksim. Some streamer material is defined as BULK in the Rocksim file. In those cases - * it is adjusted in this handler. - * - * @return SURFACE - */ - @Override - public Material.Type getMaterialType() { - return Material.Type.SURFACE; - } - -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/RingHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/RingHandler.java deleted file mode 100644 index 3418718a..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/RingHandler.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * RingHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A SAX handler for centering rings, tube couplers, and bulkheads. - */ -class RingHandler extends PositionDependentHandler { - - /** - * The OpenRocket Ring. - */ - private final CenteringRing ring = new CenteringRing(); - - /** - * The parent component. - */ - private final RocketComponent parent; - - /** - * The parsed Rocksim UsageCode. - */ - private int usageCode = 0; - - /** - * Constructor. - * - * @param theParent the parent component - * @param warnings the warning set - * @throws IllegalArgumentException thrown if c is null - */ - public RingHandler(RocketComponent theParent, WarningSet warnings) throws IllegalArgumentException { - if (theParent == null) { - throw new IllegalArgumentException("The parent of a ring may not be null."); - } - parent = theParent; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.OD.equals(element)) { - ring.setOuterRadius(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - if (RocksimCommonConstants.ID.equals(element)) { - ring.setInnerRadius(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS); - } - if (RocksimCommonConstants.LEN.equals(element)) { - ring.setLength(Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - if (RocksimCommonConstants.USAGE_CODE.equals(element)) { - usageCode = Integer.parseInt(content); - } - } catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * Get the ring component this handler is working upon. - * - * @return a component - */ - @Override - public CenteringRing getComponent() { - return ring; - } - - /** - * This method adds the CenteringRing as a child of the parent rocket component. - * - * @param warnings the warning set - */ - public void asCenteringRing(WarningSet warnings) { - - if (isCompatible(parent, CenteringRing.class, warnings)) { - parent.addChild(ring); - } - } - - /** - * Convert the parsed Rocksim data values in this object to an instance of OpenRocket's Bulkhead. - *

- * Side Effect Warning: This method adds the resulting Bulkhead as a child of the parent rocket component! - * - * @param warnings the warning set - */ - public void asBulkhead(WarningSet warnings) { - - Bulkhead result = new Bulkhead(); - - copyValues(result); - - if (isCompatible(parent, Bulkhead.class, warnings)) { - parent.addChild(result); - } - } - - /** - * Convert the parsed Rocksim data values in this object to an instance of OpenRocket's TubeCoupler. - *

- * Side Effect Warning: This method adds the resulting TubeCoupler as a child of the parent rocket component! - * - * @param warnings the warning set - */ - public void asTubeCoupler(WarningSet warnings) { - - TubeCoupler result = new TubeCoupler(); - - copyValues(result); - - if (isCompatible(parent, TubeCoupler.class, warnings)) { - parent.addChild(result); - } - } - - /** - * Convert the parsed Rocksim data values in this object to an instance of OpenRocket's Engine Block. - *

- * Side Effect Warning: This method adds the resulting EngineBlock as a child of the parent rocket component! - * - * @param warnings the warning set - */ - public void asEngineBlock(WarningSet warnings) { - - EngineBlock result = new EngineBlock(); - - copyValues(result); - - if (isCompatible(parent, EngineBlock.class, warnings)) { - parent.addChild(result); - } - } - - /** - * Copy values from the base ring to the specific component. - * - * @param result the target to which ring values will be copied - */ - private void copyValues(RingComponent result) { - result.setOuterRadius(ring.getOuterRadius()); - result.setInnerRadius(ring.getInnerRadius()); - result.setLength(ring.getLength()); - result.setName(ring.getName()); - setOverride(result, ring.isOverrideSubcomponentsEnabled(), ring.getOverrideMass(), ring.getOverrideCGX()); - result.setRelativePosition(ring.getRelativePosition()); - result.setPositionValue(ring.getPositionValue()); - result.setMaterial(ring.getMaterial()); - result.setThickness(result.getThickness()); - } - - /** - * Set the relative position onto the component. This cannot be done directly because setRelativePosition is not - * public in all components. - * - * @param position the OpenRocket position - */ - @Override - public void setRelativePosition(RocketComponent.Position position) { - ring.setRelativePosition(position); - } - - @Override - public void endHandler(String element, HashMap attributes, String content, WarningSet warnings) throws SAXException { - super.endHandler(element, attributes, content, warnings); - - // The XML element in Rocksim design file is used for many types of components, unfortunately. - // Additional subelements are used to indicate the type of the rocket component. When parsing using SAX - // this poses a problem because we can't "look ahead" to see what type is being represented at the start - // of parsing - something that would be nice to do so that we can instantiate the correct OR component - // at the start, then just call setters for the appropriate data. - - // To overcome that, a CenteringRing is instantiated at the start of parsing, it's mutators are called, - // and then at the end (this method) converts the CenteringRing to a more appropriate type. CenteringRing - // is generic enough to support the representation of all similar types without loss of data. - - //UsageCode - // 0 == Centering Ring - // 1 == Bulkhead - // 2 == Engine Block - // 3 == Sleeve - // 4 == Tube Coupler - - if (usageCode == 1) { - //Bulkhead - asBulkhead(warnings); - } else if (usageCode == 2) { - asEngineBlock(warnings); - } else if (usageCode == 4) { - //TubeCoupler - asTubeCoupler(warnings); - } else { - //Default - asCenteringRing(warnings); - } - } - - /** - * Get the required type of material for this component. - * - * @return BULK - */ - @Override - public Material.Type getMaterialType() { - return Material.Type.BULK; - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/RocksimHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/RocksimHandler.java deleted file mode 100644 index bf41c168..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/RocksimHandler.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * RocksimHandler.java - * - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.AbstractElementHandler; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * This class is a Sax element handler for Rocksim version 9 design files. It parses the Rocksim file (typically - * a .rkt extension) and creates corresponding OpenRocket components. This is a best effort approach and may not - * be an exact replica. - *

- * Limitations: Rocksim flight simulations are not imported; tube fins are not supported; Rocksim 'pods' are not supported. - */ -public class RocksimHandler extends AbstractElementHandler { - - /** - * The main content handler. - */ - private RocksimContentHandler handler = null; - - /** - * Return the OpenRocketDocument read from the file, or null if a document - * has not been read yet. - * - * @return the document read, or null. - */ - public OpenRocketDocument getDocument() { - return handler.getDocument(); - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - - // Check for unknown elements - if (!element.equals("RockSimDocument")) { - warnings.add(Warning.fromString("Unknown element " + element + ", ignoring.")); - return null; - } - - // Check for first call - if (handler != null) { - warnings.add(Warning.fromString("Multiple document elements found, ignoring later " - + "ones.")); - return null; - } - - handler = new RocksimContentHandler(); - return handler; - } - -} - -/** - * Handles the content of the tag. - */ -class RocksimContentHandler extends AbstractElementHandler { - /** - * The OpenRocketDocument that is the container for the rocket. - */ - private final OpenRocketDocument doc; - - /** - * The top-level component, from which all child components are added. - */ - private final Rocket rocket; - - /** - * The rocksim file version. - */ - private String version; - - /** - * Constructor. - */ - public RocksimContentHandler() { - this.rocket = new Rocket(); - this.doc = new OpenRocketDocument(rocket); - } - - /** - * Get the OpenRocket document that has been created from parsing the Rocksim design file. - * - * @return the instantiated OpenRocketDocument - */ - public OpenRocketDocument getDocument() { - return doc; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - if (RocksimCommonConstants.DESIGN_INFORMATION.equals(element)) { - //The next sub-element is "RocketDesign", which is really the only thing that matters. Rather than - //create another handler just for that element, handle it here. - return this; - } - if (RocksimCommonConstants.FILE_VERSION.equals(element)) { - return PlainTextHandler.INSTANCE; - } - if (RocksimCommonConstants.ROCKET_DESIGN.equals(element)) { - return new RocketDesignHandler(rocket); - } - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - /** - * SAX handler for Rocksim file version number. The value is not used currently, but could be used in the future - * for backward/forward compatibility reasons (different lower level handlers could be called via a strategy pattern). - */ - if (RocksimCommonConstants.FILE_VERSION.equals(element)) { - version = content; - } - } - - /** - * Answer the file version. - * - * @return the version of the Rocksim design file - */ - public String getVersion() { - return version; - } -} - - -/** - * A SAX handler for the high level Rocksim design. This structure includes sub-structures for each of the stages. - * Correct functioning of this handler is predicated on the stage count element appearing before the actual stage parts - * structures. If that invariant is not true, then behavior will be unpredictable. - */ -class RocketDesignHandler extends AbstractElementHandler { - /** - * The parent component. - */ - private final RocketComponent component; - /** - * The parsed stage count. Defaults to 1. - */ - private int stageCount = 1; - /** - * The overridden stage 1 mass. - */ - private double stage1Mass = 0d; - /** - * The overridden stage 2 mass. - */ - private double stage2Mass = 0d; - /** - * The overridden stage 3 mass. - */ - private double stage3Mass = 0d; - /** - * The overridden stage 1 Cg. - */ - private double stage1CG = 0d; - /** - * The overridden stage 2 Cg. - */ - private double stage2CG = 0d; - /** - * The overridden stage 3 Cg. - */ - private double stage3CG = 0d; - - /** - * Constructor. - * - * @param c the parent component - */ - public RocketDesignHandler(RocketComponent c) { - component = c; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - /** - * In Rocksim stages are from the top down, so a single stage rocket is actually stage '3'. A 2-stage - * rocket defines stage '2' as the initial booster with stage '3' sitting atop it. And so on. - */ - if ("Stage3Parts".equals(element)) { - final Stage stage = new Stage(); - if (stage3Mass > 0.0d) { - stage.setMassOverridden(true); - stage.setOverrideSubcomponents(true); //Rocksim does not support this type of override - stage.setOverrideMass(stage3Mass); - } - if (stage3CG > 0.0d) { - stage.setCGOverridden(true); - stage.setOverrideSubcomponents(true); //Rocksim does not support this type of override - stage.setOverrideCGX(stage3CG); - } - component.addChild(stage); - return new StageHandler(stage); - } - if ("Stage2Parts".equals(element)) { - if (stageCount >= 2) { - final Stage stage = new Stage(); - if (stage2Mass > 0.0d) { - stage.setMassOverridden(true); - stage.setOverrideSubcomponents(true); //Rocksim does not support this type of override - stage.setOverrideMass(stage2Mass); - } - if (stage2CG > 0.0d) { - stage.setCGOverridden(true); - stage.setOverrideSubcomponents(true); //Rocksim does not support this type of override - stage.setOverrideCGX(stage2CG); - } - component.addChild(stage); - return new StageHandler(stage); - } - } - if ("Stage1Parts".equals(element)) { - if (stageCount == 3) { - final Stage stage = new Stage(); - if (stage1Mass > 0.0d) { - stage.setMassOverridden(true); - stage.setOverrideSubcomponents(true); //Rocksim does not support this type of override - stage.setOverrideMass(stage1Mass); - } - if (stage1CG > 0.0d) { - stage.setCGOverridden(true); - stage.setOverrideSubcomponents(true); //Rocksim does not support this type of override - stage.setOverrideCGX(stage1CG); - } - component.addChild(stage); - return new StageHandler(stage); - } - } - if (RocksimCommonConstants.NAME.equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("StageCount".equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("Stage3Mass".equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("Stage2Mass".equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("Stage1Mass".equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("Stage3CG".equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("Stage2CGAlone".equals(element)) { - return PlainTextHandler.INSTANCE; - } - if ("Stage1CGAlone".equals(element)) { - return PlainTextHandler.INSTANCE; - } - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - try { - if (RocksimCommonConstants.NAME.equals(element)) { - component.setName(content); - } - if ("StageCount".equals(element)) { - stageCount = Integer.parseInt(content); - } - if ("Stage3Mass".equals(element)) { - stage3Mass = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS; - } - if ("Stage2Mass".equals(element)) { - stage2Mass = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS; - } - if ("Stage1Mass".equals(element)) { - stage1Mass = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS; - } - if ("Stage3CG".equals(element)) { - stage3CG = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if ("Stage2CGAlone".equals(element)) { - stage2CG = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - if ("Stage1CGAlone".equals(element)) { - stage1CG = Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH; - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - -} - -/** - * A SAX handler for a Rocksim stage. - */ -class StageHandler extends AbstractElementHandler { - /** - * The parent OpenRocket component. - */ - private final RocketComponent component; - - /** - * Constructor. - * - * @param c the parent component - * @throws IllegalArgumentException thrown if c is null - */ - public StageHandler(RocketComponent c) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The stage component may not be null."); - } - component = c; - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - if (RocksimCommonConstants.NOSE_CONE.equals(element)) { - return new NoseConeHandler(component, warnings); - } - if (RocksimCommonConstants.BODY_TUBE.equals(element)) { - return new BodyTubeHandler(component, warnings); - } - if (RocksimCommonConstants.TRANSITION.equals(element)) { - return new TransitionHandler(component, warnings); - } - return null; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/RocksimLoader.java b/core/src/net/sf/openrocket/file/rocksim/importt/RocksimLoader.java deleted file mode 100644 index 41fdaad4..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/RocksimLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * RocksimLoader.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import java.io.IOException; -import java.io.InputStream; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.AbstractRocketLoader; -import net.sf.openrocket.file.MotorFinder; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.file.simplesax.SimpleSAX; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * This class is the main entry point for Rocksim design file imported to OpenRocket. Currently only Rocksim v9 - * file formats are supported, although it is possible that v8 formats will work for most components. - * - * In the cases of v9 components that exist in Rocksim but have no corollary in OpenRocket a message is added to - * a warning set and presented to the user. In effect, this loading is a 'best-effort' mapping and is not meant to - * be an exact representation of any possible Rocksim design in an OpenRocket format. - * - * Rocksim simulations are not imported. - * - * Wish List: - * Material interface (or at least make them abstract in RocketComponent) - * setMaterial - * getMaterial - */ -public class RocksimLoader extends AbstractRocketLoader { - /** - * This method is called by the default implementations of {@link #load(java.io.File)} - * and {@link #load(java.io.InputStream)} to load the rocket. - * - * @throws net.sf.openrocket.file.RocketLoadException - * if an error occurs during loading. - */ - @Override - protected OpenRocketDocument loadFromStream(InputStream source, MotorFinder motorFinder) throws IOException, RocketLoadException { - - InputSource xmlSource = new InputSource(source); - - RocksimHandler handler = new RocksimHandler(); - - try { - SimpleSAX.readXML(xmlSource, handler, warnings); - } catch (SAXException e) { - throw new RocketLoadException("Malformed XML in input.", e); - } - - final OpenRocketDocument document = handler.getDocument(); - document.setFile(null); - document.clearUndo(); - return document; - } -} diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/StreamerHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/StreamerHandler.java deleted file mode 100644 index cdf87a93..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/StreamerHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * StreamerHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Streamer; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * A SAX handler for Streamer components. - */ -class StreamerHandler extends RecoveryDeviceHandler { - - /** - * The OpenRocket Streamer. - */ - private final Streamer streamer; - - /** - * Constructor. - * - * @param c the parent component - * @param warnings the warning set - * - * @throws IllegalArgumentException thrown if c is null - */ - public StreamerHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent of a streamer may not be null."); - } - streamer = new Streamer(); - if (isCompatible(c, Streamer.class, warnings)) { - c.addChild(streamer); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - return PlainTextHandler.INSTANCE; - } - - /** - * {@inheritDoc} - */ - @Override - public void closeElement(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if (RocksimCommonConstants.WIDTH.equals(element)) { - streamer.setStripWidth(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.LEN.equals(element)) { - streamer.setStripLength(Math.max(0, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if (RocksimCommonConstants.DRAG_COEFFICIENT.equals(element)) { - streamer.setCD(Double.parseDouble(content)); - } - if (RocksimCommonConstants.MATERIAL.equals(element)) { - setMaterialName(content); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Streamer getComponent() { - return streamer; - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java deleted file mode 100644 index f4b1720a..00000000 --- a/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * TransitionHandler.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimFinishCode; -import net.sf.openrocket.file.rocksim.RocksimNoseConeCode; -import net.sf.openrocket.file.simplesax.ElementHandler; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import org.xml.sax.SAXException; - -import java.util.HashMap; - -/** - * The SAX handler for Transition components. - */ -class TransitionHandler extends BaseHandler { - /** - * The OpenRocket Transition. - */ - private final Transition transition = new Transition(); - - /** - * The wall thickness. Used for hollow nose cones. - */ - private double thickness = 0d; - - /** - * Constructor. - * - * @param c the parent component - * @param warnings the warning set - * @throws IllegalArgumentException thrown if c is null - */ - public TransitionHandler(RocketComponent c, WarningSet warnings) throws IllegalArgumentException { - if (c == null) { - throw new IllegalArgumentException("The parent of a transition may not be null."); - } - if (isCompatible(c, Transition.class, warnings)) { - c.addChild(transition); - } - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { - if (RocksimCommonConstants.ATTACHED_PARTS.equals(element)) { - return new AttachedPartsHandler(transition); - } - return PlainTextHandler.INSTANCE; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - super.closeElement(element, attributes, content, warnings); - - try { - if ("ShapeCode".equals(element)) { - transition.setType(RocksimNoseConeCode.fromCode(Integer.parseInt(content)).asOpenRocket()); - } - if ("Len".equals(element)) { - transition.setLength(Math.max(0, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if ("FrontDia".equals(element)) { - transition.setForeRadius(Math.max(0, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if ("RearDia".equals(element)) { - transition.setAftRadius(Math.max(0, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if ("WallThickness".equals(element)) { - thickness = Math.max(0d, Double.parseDouble(content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH); - } - if ("FrontShoulderDia".equals(element)) { - transition.setForeShoulderRadius(Math.max(0d, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if ("RearShoulderDia".equals(element)) { - transition.setAftShoulderRadius(Math.max(0d, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS)); - } - if ("FrontShoulderLen".equals(element)) { - transition.setForeShoulderLength(Math.max(0d, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if ("RearShoulderLen".equals(element)) { - transition.setAftShoulderLength(Math.max(0d, Double.parseDouble( - content) / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH)); - } - if ("ShapeParameter".equals(element)) { - if (Transition.Shape.POWER.equals(transition.getType()) || - Transition.Shape.HAACK.equals(transition.getType()) || - Transition.Shape.PARABOLIC.equals(transition.getType())) { - transition.setShapeParameter(Double.parseDouble(content)); - } - } - if ("ConstructionType".equals(element)) { - int typeCode = Integer.parseInt(content); - if (typeCode == 0) { - //SOLID - transition.setFilled(true); - } - else if (typeCode == 1) { - //HOLLOW - transition.setFilled(false); - } - } - if ("FinishCode".equals(element)) { - transition.setFinish(RocksimFinishCode.fromCode(Integer.parseInt(content)).asOpenRocket()); - } - if ("Material".equals(element)) { - setMaterialName(content); - } - } - catch (NumberFormatException nfe) { - warnings.add("Could not convert " + element + " value of " + content + ". It is expected to be a number."); - } - } - - @Override - public void endHandler(String element, HashMap attributes, String content, WarningSet warnings) - throws SAXException { - super.endHandler(element, attributes, content, warnings); - - if (transition.isFilled()) { - transition.setAftShoulderThickness(transition.getAftShoulderRadius()); - transition.setForeShoulderThickness(transition.getForeShoulderRadius()); - } - else { - transition.setThickness(thickness); - transition.setAftShoulderThickness(thickness); - transition.setForeShoulderThickness(thickness); - } - } - - - @Override - public Transition getComponent() { - return transition; - } - - /** - * Get the required type of material for this component. - * - * @return BULK - */ - public Material.Type getMaterialType() { - return Material.Type.BULK; - } - - -} - diff --git a/core/src/net/sf/openrocket/file/simplesax/AbstractElementHandler.java b/core/src/net/sf/openrocket/file/simplesax/AbstractElementHandler.java deleted file mode 100644 index 208f68c0..00000000 --- a/core/src/net/sf/openrocket/file/simplesax/AbstractElementHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.sf.openrocket.file.simplesax; - -import java.util.HashMap; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; - -import org.xml.sax.SAXException; - - -/** - * An abstract base class for creating an ElementHandler. This implements the close - * methods so that warnings are generated for spurious content. - * - * @author Sampo Niskanen - */ -public abstract class AbstractElementHandler implements ElementHandler { - - @Override - public abstract ElementHandler openElement(String element, - HashMap attributes, WarningSet warnings) throws SAXException; - - /** - * {@inheritDoc} - *

- * The default implementation is to add warnings for any textual content or attributes. - * This is useful for generating warnings for unknown XML attributes. - */ - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - - if (!content.trim().equals("")) { - warnings.add(Warning.fromString("Unknown text in element '" + element - + "', ignoring.")); - } - if (!attributes.isEmpty()) { - warnings.add(Warning.fromString("Unknown attributes in element '" + element - + "', ignoring.")); - } - } - - /** - * {@inheritDoc} - *

- * The default implementation is a no-op. - */ - @Override - public void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - // No-op - } - -} diff --git a/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java b/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java deleted file mode 100644 index 169a4d70..00000000 --- a/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.sf.openrocket.file.simplesax; - -import java.util.HashMap; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.util.SimpleStack; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * The actual SAX handler class. Contains the necessary methods for parsing the SAX source. - * Delegates the actual content parsing to {@link ElementHandler} objects. - */ -class DelegatorHandler extends DefaultHandler { - private final WarningSet warnings; - - private final SimpleStack handlerStack = new SimpleStack(); - private final SimpleStack elementData = new SimpleStack(); - private final SimpleStack> elementAttributes = new SimpleStack>(); - - - // Ignore all elements as long as ignore > 0 - private int ignore = 0; - - - public DelegatorHandler(ElementHandler initialHandler, WarningSet warnings) { - this.warnings = warnings; - handlerStack.add(initialHandler); - elementData.add(new StringBuilder()); // Just in case - } - - - ///////// SAX handlers - - @Override - public void startElement(String uri, String localName, String name, - Attributes attributes) throws SAXException { - - // Check for ignore - if (ignore > 0) { - ignore++; - return; - } - - // Check for unknown namespace - if (!uri.equals("")) { - warnings.add(Warning.fromString("Unknown namespace element '" + uri - + "' encountered, ignoring.")); - ignore++; - return; - } - - // Add layer to data stacks - elementData.push(new StringBuilder()); - elementAttributes.push(copyAttributes(attributes)); - - // Call the handler - ElementHandler h = handlerStack.peek(); - h = h.openElement(localName, elementAttributes.peek(), warnings); - if (h != null) { - handlerStack.push(h); - } else { - // Start ignoring elements - ignore++; - } - } - - - /** - * Stores encountered characters in the elementData stack. - */ - @Override - public void characters(char[] chars, int start, int length) throws SAXException { - // Check for ignore - if (ignore > 0) - return; - - StringBuilder sb = elementData.peek(); - sb.append(chars, start, length); - } - - - /** - * Removes the last layer from the stack. - */ - @Override - public void endElement(String uri, String localName, String name) throws SAXException { - - // Check for ignore - if (ignore > 0) { - ignore--; - return; - } - - // Remove data from stack - String data = elementData.pop().toString(); // throws on error - HashMap attr = elementAttributes.pop(); - - // Remove last handler and call the next one - ElementHandler h; - - h = handlerStack.pop(); - h.endHandler(localName, attr, data, warnings); - - h = handlerStack.peek(); - h.closeElement(localName, attr, data, warnings); - } - - - private static HashMap copyAttributes(Attributes atts) { - HashMap ret = new HashMap(); - for (int i = 0; i < atts.getLength(); i++) { - ret.put(atts.getLocalName(i), atts.getValue(i)); - } - return ret; - } -} diff --git a/core/src/net/sf/openrocket/file/simplesax/ElementHandler.java b/core/src/net/sf/openrocket/file/simplesax/ElementHandler.java deleted file mode 100644 index cdbbe1d6..00000000 --- a/core/src/net/sf/openrocket/file/simplesax/ElementHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package net.sf.openrocket.file.simplesax; - -import java.util.HashMap; - -import net.sf.openrocket.aerodynamics.WarningSet; - -import org.xml.sax.SAXException; - - -/** - * A "simple XML" element handler. An object of this class handles a single element of - * an XML file. If the input file is: - * - * - * message - * - * - * and the initial handler is initHandler, then the following methods will be called: - * - * 1. initHandler.openElement(String, HashMap, WarningSet) is called for the opening element , which returns fooHandler - * 2. fooHandler.openElement(String, HashMap, WarningSet) is called for the opening element , which returns barHandler - * 3. barHandler.endHandler(String, HashMap, String, WarningSet) is called for the closing element - * 4. fooHandler.closeElement(String, HashMap, String, WarningSet) is called for the closing element - * 5. fooHandler.endHandler(String, HashMap, String, WarningSet) is called for the closing element - * 6. initHandler.closeElement(String, HashMap, String, WarningSet) is called for the closing element - * - * Note that endHandler(String, HashMap, String, WarningSet) is not called for the initial handler. - * - * @author Sampo Niskanen - */ -public interface ElementHandler { - - /** - * Called when an opening tag of a contained element is encountered. Returns the handler - * that will handle the elements within that element, or null if the element - * and all of its contents is to be ignored. - *

- * Note that this method may also return this, in which case this - * handler will also handle the subelement. - * - * @param element the element name. - * @param attributes attributes of the element. - * @param warnings the warning set to store warnings in. - * @return the handler that handles elements encountered within this element, - * or null if the element is to be ignored. - */ - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) throws SAXException; - - /** - * Called when a closing tag of a contained element is encountered. - *

- * This method can be used to handle the textual content of the element for simple text - * elements, which is passed in as the "content" parameter. - * - * @param element the element name. - * @param attributes attributes of the element. - * @param content the textual content of the element. - * @param warnings the warning set to store warnings in. - */ - public abstract void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException; - - /** - * Called when the current element that this handler is handling is closed. - * - * @param warnings the warning set to store warnings in. - */ - public abstract void endHandler(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException; - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/file/simplesax/NullElementHandler.java b/core/src/net/sf/openrocket/file/simplesax/NullElementHandler.java deleted file mode 100644 index 2cc86be3..00000000 --- a/core/src/net/sf/openrocket/file/simplesax/NullElementHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.file.simplesax; - -import java.util.HashMap; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; - -import org.xml.sax.SAXException; - -/** - * A singleton element handler that does not accept any content in the element - * except whitespace text. All subelements are ignored and a warning is produced - * of them. It ignores any attributes. - *

- * This class can be used for elements that have no content but contain attributes. - * - * @author Sampo Niskanen - */ -public class NullElementHandler extends AbstractElementHandler { - public static final NullElementHandler INSTANCE = new NullElementHandler(); - - private static final HashMap EMPTY_MAP = new HashMap(); - - private NullElementHandler() { - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - warnings.add(Warning.fromString("Unknown element " + element + ", ignoring.")); - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) throws SAXException { - super.closeElement(element, EMPTY_MAP, content, warnings); - } - -} diff --git a/core/src/net/sf/openrocket/file/simplesax/PlainTextHandler.java b/core/src/net/sf/openrocket/file/simplesax/PlainTextHandler.java deleted file mode 100644 index 406a522c..00000000 --- a/core/src/net/sf/openrocket/file/simplesax/PlainTextHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.file.simplesax; - -import java.util.HashMap; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; - -/** - * An element handler that does not allow any sub-elements. If any are encountered - * a warning is generated and they are ignored. - */ -public class PlainTextHandler extends AbstractElementHandler { - public static final PlainTextHandler INSTANCE = new PlainTextHandler(); - - private PlainTextHandler() { - } - - @Override - public ElementHandler openElement(String element, HashMap attributes, - WarningSet warnings) { - warnings.add(Warning.fromString("Unknown element " + element + ", ignoring.")); - return null; - } - - @Override - public void closeElement(String element, HashMap attributes, - String content, WarningSet warnings) { - // Warning from openElement is sufficient. - } -} - diff --git a/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java b/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java deleted file mode 100644 index 6f9bc2eb..00000000 --- a/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.sf.openrocket.file.simplesax; - -import java.io.IOException; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import net.sf.openrocket.aerodynamics.WarningSet; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - - -/** - * A "simple SAX" XML reader. This system imposes the limit that an XML element may - * contain either textual (non-whitespace) content OR additional elements, but not - * both. This holds true for both the OpenRocket and RockSim design formats and the - * RockSim engine definition format. - *

- * The actual handling is performed by subclasses of {@link ElementHandler}. The - * initial handler is provided to the {@link #readXML(InputSource, ElementHandler, WarningSet)} - * method. - * - * @author Sampo Niskanen - */ -public class SimpleSAX { - - static final XMLReaderCache cache = new XMLReaderCache(10); - - /** - * Read a simple XML file. - * - * @param source the SAX input source. - * @param initialHandler the initial content handler. - * @param warnings a warning set to store warning (cannot be null). - * @throws IOException if an I/O exception occurs while reading. - * @throws SAXException if e.g. malformed XML is encountered. - */ - public static void readXML(InputSource source, ElementHandler initialHandler, - WarningSet warnings) throws IOException, SAXException { - - DelegatorHandler xmlhandler = new DelegatorHandler(initialHandler, warnings); - - XMLReader reader = cache.createXMLReader(); - reader.setContentHandler(xmlhandler); - reader.setErrorHandler(xmlhandler); - reader.parse(source); - cache.releaseXMLReader(reader); - } - - private static class XMLReaderCache { - - private final BlockingQueue queue; - private XMLReaderCache( int maxSize ) { - this.queue = new LinkedBlockingQueue(maxSize); - } - - private XMLReader createXMLReader() throws SAXException { - - XMLReader reader = queue.poll(); - if ( reader == null ) { - reader = XMLReaderFactory.createXMLReader(); - } - return reader; - } - - private void releaseXMLReader( XMLReader reader ) { - queue.offer( reader ); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/Resettable.java b/core/src/net/sf/openrocket/gui/Resettable.java deleted file mode 100644 index 1f30d2b7..00000000 --- a/core/src/net/sf/openrocket/gui/Resettable.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.sf.openrocket.gui; - -/** - * An interface for GUI elements with a resettable model. The resetModel() method in - * this interface resets the model to some default model, releasing the old model - * listening connections. - * - * Some components that don't have a settable model simply release the current model. - * These components cannot therefore be reused after calling resetModel(). - * - * @author Sampo Niskanen - */ -public interface Resettable { - public void resetModel(); -} diff --git a/core/src/net/sf/openrocket/gui/SpinnerEditor.java b/core/src/net/sf/openrocket/gui/SpinnerEditor.java deleted file mode 100644 index be4b7952..00000000 --- a/core/src/net/sf/openrocket/gui/SpinnerEditor.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.sf.openrocket.gui; - -import javax.swing.JSpinner; -import javax.swing.text.DefaultFormatter; -import javax.swing.text.DefaultFormatterFactory; - -/** - * Editable editor for a JSpinner. Simply uses JSpinner.DefaultEditor, which has been made - * editable. Why the f*** isn't this possible in the normal API? - * - * @author Sampo Niskanen - */ - -//public class SpinnerEditor extends JSpinner.NumberEditor { -public class SpinnerEditor extends JSpinner.DefaultEditor { - - public SpinnerEditor(JSpinner spinner) { - super(spinner); - //super(spinner,"0.0##"); - getTextField().setEditable(true); - - DefaultFormatterFactory dff = (DefaultFormatterFactory) getTextField().getFormatterFactory(); - DefaultFormatter formatter = (DefaultFormatter) dff.getDefaultFormatter(); - formatter.setOverwriteMode(false); - } - - /** - * Constructor which sets the number of columns in the editor. - * @param spinner - * @param cols - */ - public SpinnerEditor(JSpinner spinner, int cols ) { - this(spinner); - getTextField().setColumns(cols); - } - -} diff --git a/core/src/net/sf/openrocket/gui/StorageOptionChooser.java b/core/src/net/sf/openrocket/gui/StorageOptionChooser.java deleted file mode 100644 index 49b21974..00000000 --- a/core/src/net/sf/openrocket/gui/StorageOptionChooser.java +++ /dev/null @@ -1,287 +0,0 @@ -package net.sf.openrocket.gui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.document.StorageOptions; -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.file.openrocket.OpenRocketSaver; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.startup.Application; - -public class StorageOptionChooser extends JPanel { - - public static final double DEFAULT_SAVE_TIME_SKIP = 0.20; - - private final OpenRocketDocument document; - - private JRadioButton allButton; - private JRadioButton someButton; - private JRadioButton noneButton; - - private JSpinner timeSpinner; - - private JCheckBox compressButton; - - private JLabel estimateLabel; - - - private boolean artificialEvent = false; - private static final Translator trans = Application.getTranslator(); - - public StorageOptionChooser(OpenRocketDocument doc, StorageOptions opts) { - super(new MigLayout()); - - this.document = doc; - - - ChangeListener changeUpdater = new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - updateEstimate(); - } - }; - ActionListener actionUpdater = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateEstimate(); - } - }; - - - ButtonGroup buttonGroup = new ButtonGroup(); - String tip; - - //// Simulated data to store: - this.add(new JLabel(trans.get("StorageOptChooser.lbl.Simdatatostore")), "spanx, wrap unrel"); - - //// All simulated data - allButton = new JRadioButton(trans.get("StorageOptChooser.rdbut.Allsimdata")); - //// Store all simulated data.
- //// This can result in very large files! - allButton.setToolTipText(trans.get("StorageOptChooser.lbl.longA1") + - trans.get("StorageOptChooser.lbl.longA2")); - buttonGroup.add(allButton); - allButton.addActionListener(actionUpdater); - this.add(allButton, "spanx, wrap rel"); - - //// Every - someButton = new JRadioButton(trans.get("StorageOptChooser.rdbut.Every")); - //// Store plottable values approximately this far apart.
" - //// Larger values result in smaller files. - tip = trans.get("StorageOptChooser.lbl.longB1") + - trans.get("StorageOptChooser.lbl.longB2"); - someButton.setToolTipText(tip); - buttonGroup.add(someButton); - someButton.addActionListener(actionUpdater); - this.add(someButton, ""); - - timeSpinner = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 5.0, 0.1)); - timeSpinner.setToolTipText(tip); - timeSpinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (artificialEvent) - return; - someButton.setSelected(true); - } - }); - this.add(timeSpinner, "wmin 55lp"); - timeSpinner.addChangeListener(changeUpdater); - - //// seconds - JLabel label = new JLabel(trans.get("StorageOptChooser.lbl.seconds")); - label.setToolTipText(tip); - this.add(label, "wrap rel"); - - //// Only primary figures - noneButton = new JRadioButton(trans.get("StorageOptChooser.rdbut.Onlyprimfig")); - //// Store only the values shown in the summary table.
- //// This results in the smallest files. - noneButton.setToolTipText(trans.get("StorageOptChooser.lbl.longC1") + - trans.get("StorageOptChooser.lbl.longC2")); - buttonGroup.add(noneButton); - noneButton.addActionListener(actionUpdater); - this.add(noneButton, "spanx, wrap 20lp"); - - - //// Compress file - compressButton = new JCheckBox(trans.get("StorageOptChooser.checkbox.Compfile")); - //// Using compression reduces the file size significantly. - compressButton.setToolTipText(trans.get("StorageOptChooser.lbl.UsingComp")); - compressButton.addActionListener(actionUpdater); - this.add(compressButton, "spanx, wrap para"); - - - // Estimate is updated in loadOptions(opts) - estimateLabel = new JLabel(""); - //// An estimate on how large the resulting file would - //// be with the present options. - estimateLabel.setToolTipText(trans.get("StorageOptChooser.lbl.longD1")); - this.add(estimateLabel, "spanx"); - - - this.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createEmptyBorder(0, 10, 0, 0), - //// Save options - BorderFactory.createTitledBorder(trans.get("StorageOptChooser.ttip.Saveopt")))); - - loadOptions(opts); - } - - - public void loadOptions(StorageOptions opts) { - double t; - - // Data storage radio button - t = opts.getSimulationTimeSkip(); - if (t == StorageOptions.SIMULATION_DATA_ALL) { - allButton.setSelected(true); - t = DEFAULT_SAVE_TIME_SKIP; - } else if (t == StorageOptions.SIMULATION_DATA_NONE) { - noneButton.setSelected(true); - t = DEFAULT_SAVE_TIME_SKIP; - } else { - someButton.setSelected(true); - } - - // Time skip spinner - artificialEvent = true; - timeSpinner.setValue(t); - artificialEvent = false; - - // Compression checkbox - compressButton.setSelected(opts.isCompressionEnabled()); - - updateEstimate(); - } - - - public void storeOptions(StorageOptions opts) { - double t; - - if (allButton.isSelected()) { - t = StorageOptions.SIMULATION_DATA_ALL; - } else if (noneButton.isSelected()) { - t = StorageOptions.SIMULATION_DATA_NONE; - } else { - t = (Double)timeSpinner.getValue(); - } - - opts.setSimulationTimeSkip(t); - - opts.setCompressionEnabled(compressButton.isSelected()); - - opts.setExplicitlySet(true); - } - - - - // TODO: MEDIUM: The estimation method always uses OpenRocketSaver! - private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver(); - - private void updateEstimate() { - StorageOptions opts = new StorageOptions(); - - storeOptions(opts); - long size = ROCKET_SAVER.estimateFileSize(document, opts); - size = Math.max((size+512)/1024, 1); - - String formatted; - - if (size >= 10000) { - formatted = (size/1000) + " MB"; - } else if (size >= 1000){ - formatted = (size/1000) + "." + ((size/100)%10) + " MB"; - } else if (size >= 100) { - formatted = ((size/10)*10) + " kB"; - } else { - formatted = size + " kB"; - } - - //// Estimated file size: - estimateLabel.setText(trans.get("StorageOptChooser.lbl.Estfilesize") + " " + formatted); - } - - - - /** - * Asks the user the storage options using a modal dialog window if the document - * contains simulated data and the user has not explicitly set how to store the data. - * - * @param document the document to check. - * @param parent the parent frame for the dialog. - * @return true to continue, false if the user cancelled. - */ - public static boolean verifyStorageOptions(OpenRocketDocument document, JFrame parent) { - StorageOptions options = document.getDefaultStorageOptions(); - - if (options.isExplicitlySet()) { - // User has explicitly set the values, save as is - return true; - } - - - boolean hasData = false; - - simulationLoop: - for (Simulation s: document.getSimulations()) { - if (s.getStatus() == Simulation.Status.NOT_SIMULATED || - s.getStatus() == Simulation.Status.EXTERNAL) - continue; - - FlightData data = s.getSimulatedData(); - if (data == null) - continue; - - for (int i=0; i < data.getBranchCount(); i++) { - FlightDataBranch branch = data.getBranch(i); - if (branch == null) - continue; - if (branch.getLength() > 0) { - hasData = true; - break simulationLoop; - } - } - } - - - if (!hasData) { - // No data to store, do not ask only about compression - return true; - } - - - StorageOptionChooser chooser = new StorageOptionChooser(document, options); - - //// Save options - if (JOptionPane.showConfirmDialog(parent, chooser, trans.get("StorageOptChooser.lbl.Saveopt"), - JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) != - JOptionPane.OK_OPTION) { - // User cancelled - return false; - } - - chooser.storeOptions(options); - return true; - } - -} diff --git a/core/src/net/sf/openrocket/gui/TextFieldListener.java b/core/src/net/sf/openrocket/gui/TextFieldListener.java deleted file mode 100644 index d0773004..00000000 --- a/core/src/net/sf/openrocket/gui/TextFieldListener.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.gui; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; - -import javax.swing.JTextField; - -public abstract class TextFieldListener implements ActionListener, FocusListener { - private JTextField field; - - public void listenTo(JTextField newField) { - if (field != null) { - field.removeActionListener(this); - field.removeFocusListener(this); - } - field = newField; - if (field != null) { - field.addActionListener(this); - field.addFocusListener(this); - } - } - - public abstract void setText(String text); - - public void actionPerformed(ActionEvent e) { - setText(field.getText()); - } - public void focusGained(FocusEvent e) { } - public void focusLost(FocusEvent e) { - setText(field.getText()); - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/adaptors/BooleanModel.java b/core/src/net/sf/openrocket/gui/adaptors/BooleanModel.java deleted file mode 100644 index a2f95ed3..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/BooleanModel.java +++ /dev/null @@ -1,331 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeListener; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EventObject; -import java.util.List; - -import javax.swing.AbstractAction; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Invalidatable; -import net.sf.openrocket.util.Invalidator; -import net.sf.openrocket.util.MemoryManagement; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.StateChangeListener; - - -/** - * A class that adapts an isXXX/setXXX boolean variable. It functions as an Action suitable - * for usage in JCheckBox or JToggleButton. You can create a suitable button with - * - * check = new JCheckBox(new BooleanModel(component,"Value")) - * check.setText("Label"); - * - * This will produce a button that uses isValue() and setValue(boolean) of the corresponding - * component. - *

- * Additionally a number of component enabled states may be controlled by this class using - * the method {@link #addEnableComponent(Component, boolean)}. - * - * @author Sampo Niskanen - */ -public class BooleanModel extends AbstractAction implements StateChangeListener, Invalidatable { - private static final LogHelper log = Application.getLogger(); - - private final ChangeSource source; - private final String valueName; - - /* Only used when referencing a ChangeSource! */ - private final Method getMethod; - private final Method setMethod; - private final Method getEnabled; - - /* Only used with internal boolean value! */ - private boolean value; - - - private final List components = new ArrayList(); - private final List componentEnableState = new ArrayList(); - - private String toString = null; - - private int firing = 0; - - private boolean oldValue; - private boolean oldEnabled; - - private Invalidator invalidator = new Invalidator(this); - - - /** - * Construct a BooleanModel that holds the boolean value within itself. - * - * @param initialValue the initial value of the boolean - */ - public BooleanModel(boolean initialValue) { - this.valueName = null; - this.source = null; - this.getMethod = null; - this.setMethod = null; - this.getEnabled = null; - - this.value = initialValue; - - oldValue = getValue(); - oldEnabled = getIsEnabled(); - - this.setEnabled(oldEnabled); - this.putValue(SELECTED_KEY, oldValue); - - } - - /** - * Construct a BooleanModel that references the boolean from a ChangeSource method. - * - * @param source the boolean source. - * @param valueName the name of the getter/setter method (without the get/is/set prefix) - */ - public BooleanModel(ChangeSource source, String valueName) { - this.source = source; - this.valueName = valueName; - - Method getter = null, setter = null; - - - // Try get/is and set - try { - getter = source.getClass().getMethod("is" + valueName); - } catch (NoSuchMethodException ignore) { - } - if (getter == null) { - try { - getter = source.getClass().getMethod("get" + valueName); - } catch (NoSuchMethodException ignore) { - } - } - try { - setter = source.getClass().getMethod("set" + valueName, boolean.class); - } catch (NoSuchMethodException ignore) { - } - - if (getter == null || setter == null) { - throw new IllegalArgumentException("get/is methods for boolean '" + valueName + - "' not present in class " + source.getClass().getCanonicalName()); - } - - getMethod = getter; - setMethod = setter; - - Method e = null; - try { - e = source.getClass().getMethod("is" + valueName + "Enabled"); - } catch (NoSuchMethodException ignore) { - } - getEnabled = e; - - oldValue = getValue(); - oldEnabled = getIsEnabled(); - - this.setEnabled(oldEnabled); - this.putValue(SELECTED_KEY, oldValue); - - source.addChangeListener(this); - } - - public boolean getValue() { - - if (getMethod != null) { - - try { - return (Boolean) getMethod.invoke(source); - } catch (IllegalAccessException e) { - throw new BugException("getMethod execution error for source " + source, e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - - } else { - - // Use internal value - return value; - - } - } - - public void setValue(boolean b) { - checkState(true); - log.debug("Setting value of " + this + " to " + b); - - if (setMethod != null) { - try { - setMethod.invoke(source, new Object[] { b }); - } catch (IllegalAccessException e) { - throw new BugException("setMethod execution error for source " + source, e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } else { - // Manually fire state change - normally the ChangeSource fires it - value = b; - stateChanged(null); - } - } - - - /** - * Add a component the enabled status of which will be controlled by the value - * of this boolean. The component will be enabled exactly when - * the state of this model is equal to that of enableState. - * - * @param component the component to control. - * @param enableState the state in which the component should be enabled. - */ - public void addEnableComponent(Component component, boolean enableState) { - checkState(true); - components.add(component); - componentEnableState.add(enableState); - updateEnableStatus(); - } - - /** - * Add a component which will be enabled when this boolean is true. - * This is equivalent to booleanModel.addEnableComponent(component, true). - * - * @param component the component to control. - * @see #addEnableComponent(Component, boolean) - */ - public void addEnableComponent(Component component) { - checkState(true); - addEnableComponent(component, true); - } - - private void updateEnableStatus() { - boolean state = getValue(); - - for (int i = 0; i < components.size(); i++) { - Component c = components.get(i); - boolean b = componentEnableState.get(i); - c.setEnabled(state == b); - } - } - - - - private boolean getIsEnabled() { - if (getEnabled == null) - return true; - try { - return (Boolean) getEnabled.invoke(source); - } catch (IllegalAccessException e) { - throw new BugException("getEnabled execution error for source " + source, e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - @Override - public void stateChanged(EventObject event) { - checkState(true); - - if (firing > 0) { - log.debug("Ignoring stateChanged of " + this + ", currently firing events"); - return; - } - - boolean v = getValue(); - boolean e = getIsEnabled(); - if (oldValue != v) { - log.debug("Value of " + this + " has changed to " + v + " oldValue=" + oldValue); - oldValue = v; - firing++; - this.putValue(SELECTED_KEY, getValue()); - // this.firePropertyChange(SELECTED_KEY, !v, v); - updateEnableStatus(); - firing--; - } - if (oldEnabled != e) { - log.debug("Enabled status of " + this + " has changed to " + e + " oldEnabled=" + oldEnabled); - oldEnabled = e; - setEnabled(e); - } - } - - - @Override - public void actionPerformed(ActionEvent e) { - if (firing > 0) { - log.debug("Ignoring actionPerformed of " + this + ", currently firing events"); - return; - } - - boolean v = (Boolean) this.getValue(SELECTED_KEY); - log.user("Value of " + this + " changed to " + v + " oldValue=" + oldValue); - if (v != oldValue) { - firing++; - setValue(v); - oldValue = getValue(); - // Update all states - this.putValue(SELECTED_KEY, oldValue); - this.setEnabled(getIsEnabled()); - updateEnableStatus(); - firing--; - } - } - - - @Override - public void addPropertyChangeListener(PropertyChangeListener listener) { - checkState(true); - super.addPropertyChangeListener(listener); - } - - - /** - * Invalidates this model by removing all listeners and removing this from - * listening to the source. After invalidation no listeners can be added to this - * model and the value cannot be set. - */ - @Override - public void invalidate() { - invalidator.invalidate(); - - PropertyChangeListener[] listeners = this.getPropertyChangeListeners(); - if (listeners.length > 0) { - log.warn("Invalidating " + this + " while still having listeners " + listeners); - for (PropertyChangeListener l : listeners) { - this.removePropertyChangeListener(l); - } - } - if (source != null) { - source.removeChangeListener(this); - } - MemoryManagement.collectable(this); - } - - - private void checkState(boolean error) { - invalidator.check(error); - } - - - - @Override - public String toString() { - if (toString == null) { - if (source != null) { - toString = "BooleanModel[" + source.getClass().getSimpleName() + ":" + valueName + "]"; - } else { - toString = "BooleanModel[internal value]"; - } - } - return toString; - } -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/Column.java b/core/src/net/sf/openrocket/gui/adaptors/Column.java deleted file mode 100644 index 9c4801a6..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/Column.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import javax.swing.table.TableColumnModel; - -public abstract class Column { - private final String name; - - /** - * Create a new column with specified name. Additionally, the {@link #getValueAt(int)} - * method must be implemented. - * - * @param name the caption of the column. - */ - public Column(String name) { - this.name = name; - } - - /** - * Return the caption of the column. - */ - @Override - public String toString() { - return name; - } - - /** - * Return the default width of the column. This is used by the method - * {@link #ColumnTableModel.setColumnWidth(TableColumnModel)}. The default width is - * 100, the method may be overridden to return other values relative to this value. - * - * @return the relative width of the column (default 100). - */ - public int getDefaultWidth() { - return 100; - } - - - /** - * Returns the exact width of this column. If the return value is positive, - * both the minimum and maximum widths of this column are set to this value - * - * @return the absolute exact width of the column (default 0). - */ - public int getExactWidth() { - return 0; - } - - - /** - * Return the column type class. This is necessary for example for numerical - * sorting of Value objects, showing booleans as checkboxes etc. - * - * @return the object class of this column, by default Object.class. - */ - public Class getColumnClass() { - return Object.class; - } - - /** - * Return the value in this column at the specified row. - * - * @param row the row of the data. - * @return the value at the specified position. - */ - public abstract Object getValueAt(int row); - - /** - * Set a value in the table. - * - * Override if the cell is editable. - * - * @param row - * @param value - */ - public void setValueAt(int row, Object value ) { - } - -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/ColumnTableModel.java b/core/src/net/sf/openrocket/gui/adaptors/ColumnTableModel.java deleted file mode 100644 index b8b8d3ec..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/ColumnTableModel.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; - -import net.sf.openrocket.startup.Application; - -public abstract class ColumnTableModel extends AbstractTableModel { - private final Column[] columns; - - public ColumnTableModel(Column... columns) { - this.columns = columns; - } - - public void setColumnWidths(TableColumnModel model) { - for (int i = 0; i < columns.length; i++) { - if (columns[i].getExactWidth() > 0) { - TableColumn col = model.getColumn(i); - int w = columns[i].getExactWidth(); - col.setResizable(false); - col.setMinWidth(w); - col.setMaxWidth(w); - col.setPreferredWidth(w); - } else { - model.getColumn(i).setPreferredWidth(columns[i].getDefaultWidth()); - } - } - } - - @Override - public int getColumnCount() { - return columns.length; - } - - @Override - public String getColumnName(int col) { - return columns[col].toString(); - } - - @Override - public Class getColumnClass(int col) { - return columns[col].getColumnClass(); - } - - @Override - public Object getValueAt(int row, int col) { - if ((row < 0) || (row >= getRowCount()) || - (col < 0) || (col >= columns.length)) { - Application.getExceptionHandler().handleErrorCondition("Error: Requested illegal column/row, col=" + col + " row=" + row); - return null; - } - return columns[col].getValueAt(row); - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - columns[columnIndex].setValueAt(rowIndex, aValue); - } - -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/DoubleModel.java b/core/src/net/sf/openrocket/gui/adaptors/DoubleModel.java deleted file mode 100644 index 3216f0a7..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/DoubleModel.java +++ /dev/null @@ -1,986 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EventListener; -import java.util.EventObject; - -import javax.swing.AbstractAction; -import javax.swing.AbstractSpinnerModel; -import javax.swing.Action; -import javax.swing.BoundedRangeModel; -import javax.swing.SpinnerModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.ExpressionParser; -import net.sf.openrocket.util.InvalidExpressionException; -import net.sf.openrocket.util.Invalidatable; -import net.sf.openrocket.util.Invalidator; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.MemoryManagement; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.StateChangeListener; - - -/** - * A model connector that can read and modify any value of any ChangeSource that - * has the appropriate get/set methods defined. - * - * The variable is defined in the constructor by providing the variable name as a string - * (e.g. "Radius" -> getRadius()/setRadius()). Additional scaling may be applied, e.g. a - * DoubleModel for the diameter can be defined by the variable "Radius" and a multiplier of 2. - * - * Sub-models suitable for JSpinners and other components are available from the appropriate - * methods. - * - * @author Sampo Niskanen - */ - -public class DoubleModel implements StateChangeListener, ChangeSource, Invalidatable { - private static final LogHelper log = Application.getLogger(); - - - public static final DoubleModel ZERO = new DoubleModel(0); - - //////////// JSpinner Model //////////// - - /** - * Model suitable for JSpinner. - * Note: Previously used using JSpinner.NumberEditor and extended SpinnerNumberModel - * to be compatible with the NumberEditor, but only has the necessary methods defined. - * This is still the design, but now extends AbstractSpinnerModel to allow other characters - * to be entered so that fractional units and expressions can be used. - */ - public class ValueSpinnerModel extends AbstractSpinnerModel implements Invalidatable { - - private ExpressionParser parser = new ExpressionParser(); - - @Override - public Object getValue() { - return currentUnit.toString(DoubleModel.this.getValue()); - } - - @Override - public void setValue(Object value) { - if (firing > 0) { - // Ignore, if called when model is sending events - log.verbose("Ignoring call to SpinnerModel setValue for " + DoubleModel.this.toString() + - " value=" + value + ", currently firing events"); - return; - } - - Number num = Double.NaN; - - // Set num if possible - if (value instanceof Number) { - num = (Number) value; - } - else if (value instanceof String) { - try { - String newValString = (String) value; - num = parser.parse(newValString); - } catch (InvalidExpressionException e) { - // Ignore - } - } - - // Update the doublemodel with the new number or return to the last number if not possible - if (((Double) num).isNaN()) { - DoubleModel.this.setValue(lastValue); - log.user("SpinnerModel could not set value for " + DoubleModel.this.toString() + ". Could not convert " + value.toString()); - } - else { - double newValue = num.doubleValue(); - double converted = currentUnit.fromUnit(newValue); - - log.user("SpinnerModel setValue called for " + DoubleModel.this.toString() + " newValue=" + newValue + - " converted=" + converted); - DoubleModel.this.setValue(converted); - } - - // Force a refresh if text doesn't match up exactly with the stored value - if (!((Double) lastValue).toString().equals(this.getValue().toString())) { - DoubleModel.this.fireStateChanged(); - log.debug("SpinnerModel " + DoubleModel.this.toString() + " refresh forced because string did not match actual value."); - } - } - - @Override - public Object getNextValue() { - double d = currentUnit.toUnit(DoubleModel.this.getValue()); - double max = currentUnit.toUnit(maxValue); - if (MathUtil.equals(d, max)) - return null; - d = currentUnit.getNextValue(d); - if (d > max) - d = max; - return d; - } - - @Override - public Object getPreviousValue() { - double d = currentUnit.toUnit(DoubleModel.this.getValue()); - double min = currentUnit.toUnit(minValue); - if (MathUtil.equals(d, min)) - return null; - d = currentUnit.getPreviousValue(d); - if (d < min) - d = min; - return d; - } - - @Override - public void addChangeListener(ChangeListener l) { - DoubleModel.this.addChangeListener(l); - } - - @Override - public void removeChangeListener(ChangeListener l) { - DoubleModel.this.removeChangeListener(l); - } - - @Override - public void invalidate() { - DoubleModel.this.invalidate(); - } - } - - /** - * Returns a new SpinnerModel with the same base as the DoubleModel. - * The values given to the JSpinner are in the currently selected units. - * - * @return A compatibility layer for a SpinnerModel. - */ - public SpinnerModel getSpinnerModel() { - return new ValueSpinnerModel(); - } - - //////////// JSlider model //////////// - - private class ValueSliderModel implements BoundedRangeModel, StateChangeListener, Invalidatable { - private static final int MAX = 1000; - - /* - * Use linear scale value = linear1 * x + linear0 when x < linearPosition - * Use quadratic scale value = quad2 * x^2 + quad1 * x + quad0 otherwise - */ - private final boolean islinear; - - // Linear in range x <= linearPosition - private final double linearPosition; - - // May be changing DoubleModels when using linear model - private final DoubleModel min, mid, max; - - // Linear multiplier and constant - //private final double linear1; - //private final double linear0; - - // Non-linear multiplier, exponent and constant - private double quad2, quad1, quad0; - - public ValueSliderModel(DoubleModel min, DoubleModel max) { - this.islinear = true; - linearPosition = 1.0; - - this.min = min; - this.mid = max; // Never use exponential scale - this.max = max; - - min.addChangeListener(this); - max.addChangeListener(this); - - quad2 = quad1 = quad0 = 0; // Not used - } - - - - /** - * Generate a linear model from min to max. - */ - public ValueSliderModel(double min, double max) { - this.islinear = true; - linearPosition = 1.0; - - this.min = new DoubleModel(min); - this.mid = new DoubleModel(max); // Never use exponential scale - this.max = new DoubleModel(max); - - quad2 = quad1 = quad0 = 0; // Not used - } - - public ValueSliderModel(double min, double mid, double max) { - this(min, 0.5, mid, max); - } - - public ValueSliderModel(double min, double mid, DoubleModel max) { - this(min, 0.5, mid, max); - } - - /* - * v(x) = mul * x^exp + add - * - * v(pos) = mul * pos^exp + add = mid - * v(1) = mul + add = max - * v'(pos) = mul*exp * pos^(exp-1) = linearMul - */ - public ValueSliderModel(double min, double pos, double mid, double max) { - this(min, pos, mid, new DoubleModel(max)); - } - - public ValueSliderModel(double min, double pos, double mid, DoubleModel max) { - this.min = new DoubleModel(min); - this.mid = new DoubleModel(mid); - this.max = max; - - this.islinear = false; - - max.addChangeListener(this); - - linearPosition = pos; - //linear0 = min; - //linear1 = (mid-min)/pos; - - if (!(min < mid && mid <= max.getValue() && 0 < pos && pos < 1)) { - throw new IllegalArgumentException("Bad arguments for ValueSliderModel " + - "min=" + min + " mid=" + mid + " max=" + max + " pos=" + pos); - } - - updateExponentialParameters(); - - } - - private void updateExponentialParameters() { - double pos = this.linearPosition; - double minValue = this.min.getValue(); - double midValue = this.mid.getValue(); - double maxValue = this.max.getValue(); - /* - * quad2..0 are calculated such that - * f(pos) = mid - continuity - * f(1) = max - end point - * f'(pos) = linear1 - continuity of derivative - */ - double delta = (midValue - minValue) / pos; - quad2 = (maxValue - midValue - delta + delta * pos) / pow2(pos - 1); - quad1 = (delta + 2 * (midValue - maxValue) * pos - delta * pos * pos) / pow2(pos - 1); - quad0 = (midValue - (2 * midValue + delta) * pos + (maxValue + delta) * pos * pos) / pow2(pos - 1); - } - - private double pow2(double x) { - return x * x; - } - - @Override - public int getValue() { - double value = DoubleModel.this.getValue(); - if (value <= min.getValue()) - return 0; - if (value >= max.getValue()) - return MAX; - - double x; - if (value <= mid.getValue()) { - // Use linear scale - //linear0 = min; - //linear1 = (mid-min)/pos; - - x = (value - min.getValue()) * linearPosition / (mid.getValue() - min.getValue()); - } else { - // Use quadratic scale - // Further solution of the quadratic equation - // a*x^2 + b*x + c-value == 0 - x = (MathUtil.safeSqrt(quad1 * quad1 - 4 * quad2 * (quad0 - value)) - quad1) / (2 * quad2); - } - return (int) (x * MAX); - } - - - @Override - public void setValue(int newValue) { - if (firing > 0) { - // Ignore loops - log.verbose("Ignoring call to SliderModel setValue for " + DoubleModel.this.toString() + - " value=" + newValue + ", currently firing events"); - return; - } - - double x = (double) newValue / MAX; - double scaledValue; - - if (x <= linearPosition) { - // Use linear scale - //linear0 = min; - //linear1 = (mid-min)/pos; - - scaledValue = (mid.getValue() - min.getValue()) / linearPosition * x + min.getValue(); - } else { - // Use quadratic scale - scaledValue = quad2 * x * x + quad1 * x + quad0; - } - - double converted = currentUnit.fromUnit(currentUnit.round(currentUnit.toUnit(scaledValue))); - log.user("SliderModel setValue called for " + DoubleModel.this.toString() + " newValue=" + newValue + - " scaledValue=" + scaledValue + " converted=" + converted); - DoubleModel.this.setValue(converted); - } - - - // Static get-methods - private boolean isAdjusting; - - @Override - public int getExtent() { - return 0; - } - - @Override - public int getMaximum() { - return MAX; - } - - @Override - public int getMinimum() { - return 0; - } - - @Override - public boolean getValueIsAdjusting() { - return isAdjusting; - } - - // Ignore set-values - @Override - public void setExtent(int newExtent) { - } - - @Override - public void setMaximum(int newMaximum) { - } - - @Override - public void setMinimum(int newMinimum) { - } - - @Override - public void setValueIsAdjusting(boolean b) { - isAdjusting = b; - } - - @Override - public void setRangeProperties(int value, int extent, int min, int max, boolean adjusting) { - setValueIsAdjusting(adjusting); - setValue(value); - } - - // Pass change listeners to the underlying model - @Override - public void addChangeListener(ChangeListener l) { - DoubleModel.this.addChangeListener(l); - } - - @Override - public void removeChangeListener(ChangeListener l) { - DoubleModel.this.removeChangeListener(l); - } - - @Override - public void invalidate() { - DoubleModel.this.invalidate(); - } - - @Override - public void stateChanged(EventObject e) { - // Min or max range has changed. - if (!islinear) { - double midValue = (max.getValue() - min.getValue()) / 3.0; - mid.setValue(midValue); - updateExponentialParameters(); - } - // Fire if not already firing - if (firing == 0) - fireStateChanged(); - } - } - - - public BoundedRangeModel getSliderModel(DoubleModel min, DoubleModel max) { - return new ValueSliderModel(min, max); - } - - public BoundedRangeModel getSliderModel(double min, double max) { - return new ValueSliderModel(min, max); - } - - public BoundedRangeModel getSliderModel(double min, double mid, double max) { - return new ValueSliderModel(min, mid, max); - } - - public BoundedRangeModel getSliderModel(double min, double mid, DoubleModel max) { - return new ValueSliderModel(min, mid, max); - } - - public BoundedRangeModel getSliderModel(double min, double pos, double mid, double max) { - return new ValueSliderModel(min, pos, mid, max); - } - - - - - - //////////// Action model //////////// - - private class AutomaticActionModel extends AbstractAction implements StateChangeListener, Invalidatable { - private boolean oldValue = false; - - public AutomaticActionModel() { - oldValue = isAutomatic(); - addChangeListener(this); - } - - - @Override - public boolean isEnabled() { - return isAutomaticAvailable(); - } - - @Override - public Object getValue(String key) { - if (key.equals(Action.SELECTED_KEY)) { - oldValue = isAutomatic(); - return oldValue; - } - return super.getValue(key); - } - - @Override - public void putValue(String key, Object value) { - if (firing > 0) { - log.verbose("Ignoring call to ActionModel putValue for " + DoubleModel.this.toString() + - " key=" + key + " value=" + value + ", currently firing events"); - return; - } - if (key.equals(Action.SELECTED_KEY) && (value instanceof Boolean)) { - log.user("ActionModel putValue called for " + DoubleModel.this.toString() + - " key=" + key + " value=" + value); - oldValue = (Boolean) value; - setAutomatic((Boolean) value); - } else { - log.debug("Passing ActionModel putValue call to supermethod for " + DoubleModel.this.toString() + - " key=" + key + " value=" + value); - super.putValue(key, value); - } - } - - // Implement a wrapper to the ChangeListeners - ArrayList propertyChangeListeners = - new ArrayList(); - - @Override - public void addPropertyChangeListener(PropertyChangeListener listener) { - propertyChangeListeners.add(listener); - DoubleModel.this.addChangeListener(this); - } - - @Override - public void removePropertyChangeListener(PropertyChangeListener listener) { - propertyChangeListeners.remove(listener); - if (propertyChangeListeners.isEmpty()) - DoubleModel.this.removeChangeListener(this); - } - - // If the value has changed, generate an event to the listeners - @Override - public void stateChanged(EventObject e) { - boolean newValue = isAutomatic(); - if (oldValue == newValue) - return; - PropertyChangeEvent event = new PropertyChangeEvent(this, Action.SELECTED_KEY, - oldValue, newValue); - oldValue = newValue; - Object[] l = propertyChangeListeners.toArray(); - for (int i = 0; i < l.length; i++) { - ((PropertyChangeListener) l[i]).propertyChange(event); - } - } - - @Override - public void actionPerformed(ActionEvent e) { - // Setting performed in putValue - } - - @Override - public void invalidate() { - DoubleModel.this.invalidate(); - } - } - - /** - * Returns a new Action corresponding to the changes of the automatic setting - * property of the value model. This may be used directly with e.g. check buttons. - * - * @return A compatibility layer for an Action. - */ - public Action getAutomaticAction() { - return new AutomaticActionModel(); - } - - - - - - //////////// Main model ///////////// - - /* - * The main model handles all values in SI units, i.e. no conversion is made within the model. - */ - - private final ChangeSource source; - private final String valueName; - private final double multiplier; - - private final Method getMethod; - private final Method setMethod; - - private final Method getAutoMethod; - private final Method setAutoMethod; - - private final ArrayList listeners = new ArrayList(); - - private final UnitGroup units; - private Unit currentUnit; - - private final double minValue; - private double maxValue; - - private String toString = null; - - - private int firing = 0; // >0 when model itself is sending events - - - // Used to differentiate changes in valueName and other changes in the component: - private double lastValue = 0; - private boolean lastAutomatic = false; - - private Invalidator invalidator = new Invalidator(this); - - - /** - * Generate a DoubleModel that contains an internal double value. - * - * @param value the initial value. - */ - public DoubleModel(double value) { - this(value, UnitGroup.UNITS_NONE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - } - - /** - * Generate a DoubleModel that contains an internal double value. - * - * @param value the initial value. - * @param unit the unit for the value. - */ - public DoubleModel(double value, UnitGroup unit) { - this(value, unit, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - } - - /** - * Generate a DoubleModel that contains an internal double value. - * - * @param value the initial value. - * @param unit the unit for the value. - * @param min minimum value. - */ - public DoubleModel(double value, UnitGroup unit, double min) { - this(value, unit, min, Double.POSITIVE_INFINITY); - } - - /** - * Generate a DoubleModel that contains an internal double value. - * - * @param value the initial value. - * @param unit the unit for the value. - * @param min minimum value. - * @param max maximum value. - */ - public DoubleModel(double value, UnitGroup unit, double min, double max) { - this.lastValue = value; - this.minValue = min; - this.maxValue = max; - - source = null; - valueName = "Constant value"; - multiplier = 1; - - getMethod = setMethod = null; - getAutoMethod = setAutoMethod = null; - units = unit; - currentUnit = units.getDefaultUnit(); - } - - - /** - * Generates a new DoubleModel that changes the values of the specified component. - * The double value is read and written using the methods "get"/"set" + valueName. - * - * @param source Component whose parameter to use. - * @param valueName Name of methods used to get/set the parameter. - * @param multiplier Value shown by the model is the value from component.getXXX * multiplier - * @param min Minimum value allowed (in SI units) - * @param max Maximum value allowed (in SI units) - */ - public DoubleModel(ChangeSource source, String valueName, double multiplier, UnitGroup unit, - double min, double max) { - this.source = source; - this.valueName = valueName; - this.multiplier = multiplier; - - this.units = unit; - currentUnit = units.getDefaultUnit(); - - this.minValue = min; - this.maxValue = max; - - try { - getMethod = source.getClass().getMethod("get" + valueName); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("get method for value '" + valueName + - "' not present in class " + source.getClass().getCanonicalName()); - } - - Method s = null; - try { - s = source.getClass().getMethod("set" + valueName, double.class); - } catch (NoSuchMethodException e1) { - } // Ignore - setMethod = s; - - // Automatic selection methods - - Method set = null, get = null; - - try { - get = source.getClass().getMethod("is" + valueName + "Automatic"); - set = source.getClass().getMethod("set" + valueName + "Automatic", boolean.class); - } catch (NoSuchMethodException e) { - } // ignore - - if (set != null && get != null) { - getAutoMethod = get; - setAutoMethod = set; - } else { - getAutoMethod = null; - setAutoMethod = null; - } - - } - - public DoubleModel(ChangeSource source, String valueName, double multiplier, UnitGroup unit, - double min) { - this(source, valueName, multiplier, unit, min, Double.POSITIVE_INFINITY); - } - - public DoubleModel(ChangeSource source, String valueName, double multiplier, UnitGroup unit) { - this(source, valueName, multiplier, unit, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - } - - public DoubleModel(ChangeSource source, String valueName, UnitGroup unit, - double min, double max) { - this(source, valueName, 1.0, unit, min, max); - } - - public DoubleModel(ChangeSource source, String valueName, UnitGroup unit, double min) { - this(source, valueName, 1.0, unit, min, Double.POSITIVE_INFINITY); - } - - public DoubleModel(ChangeSource source, String valueName, UnitGroup unit) { - this(source, valueName, 1.0, unit, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - } - - public DoubleModel(ChangeSource source, String valueName) { - this(source, valueName, 1.0, UnitGroup.UNITS_NONE, - Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); - } - - public DoubleModel(ChangeSource source, String valueName, double min) { - this(source, valueName, 1.0, UnitGroup.UNITS_NONE, min, Double.POSITIVE_INFINITY); - } - - public DoubleModel(ChangeSource source, String valueName, double min, double max) { - this(source, valueName, 1.0, UnitGroup.UNITS_NONE, min, max); - } - - - - /** - * Returns the value of the variable (in SI units). - */ - public double getValue() { - if (getMethod == null) // Constant value - return lastValue; - - try { - return (Double) getMethod.invoke(source) * multiplier; - } catch (IllegalArgumentException e) { - throw new BugException("Unable to invoke getMethod of " + this, e); - } catch (IllegalAccessException e) { - throw new BugException("Unable to invoke getMethod of " + this, e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - /** - * Sets the value of the variable. - * @param v New value for parameter in SI units. - */ - public void setValue(double v) { - checkState(true); - - log.debug("Setting value " + v + " for " + this); - if (setMethod == null) { - if (getMethod != null) { - throw new BugException("setMethod not available for variable '" + valueName + - "' in class " + source.getClass().getCanonicalName()); - } - lastValue = v; - fireStateChanged(); - return; - } - - try { - setMethod.invoke(source, v / multiplier); - } catch (IllegalArgumentException e) { - throw new BugException("Unable to invoke setMethod of " + this, e); - } catch (IllegalAccessException e) { - throw new BugException("Unable to invoke setMethod of " + this, e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - /** - * Returns whether setting the value automatically is available. - */ - public boolean isAutomaticAvailable() { - return (getAutoMethod != null) && (setAutoMethod != null); - } - - /** - * Returns whether the value is currently being set automatically. - * Returns false if automatic setting is not available at all. - */ - public boolean isAutomatic() { - if (getAutoMethod == null) - return false; - - try { - return (Boolean) getAutoMethod.invoke(source); - } catch (IllegalArgumentException e) { - throw new BugException("Method call failed", e); - } catch (IllegalAccessException e) { - throw new BugException("Method call failed", e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - /** - * Sets whether the value should be set automatically. Simply fires a - * state change event if automatic setting is not available. - */ - public void setAutomatic(boolean auto) { - checkState(true); - - if (setAutoMethod == null) { - log.debug("Setting automatic to " + auto + " for " + this + ", automatic not available"); - fireStateChanged(); // in case something is out-of-sync - return; - } - - log.debug("Setting automatic to " + auto + " for " + this); - lastAutomatic = auto; - try { - setAutoMethod.invoke(source, auto); - } catch (IllegalArgumentException e) { - throw new BugException(e); - } catch (IllegalAccessException e) { - throw new BugException(e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - - /** - * Returns the current Unit. At the beginning it is the default unit of the UnitGroup. - * @return The most recently set unit. - */ - public Unit getCurrentUnit() { - return currentUnit; - } - - /** - * Sets the current Unit. The unit must be one of those included in the UnitGroup. - * @param u The unit to set active. - */ - public void setCurrentUnit(Unit u) { - checkState(true); - if (currentUnit == u) - return; - log.debug("Setting unit for " + this + " to '" + u + "'"); - currentUnit = u; - fireStateChanged(); - } - - - /** - * Returns the UnitGroup associated with the parameter value. - * - * @return The UnitGroup given to the constructor. - */ - public UnitGroup getUnitGroup() { - return units; - } - - - - /** - * Add a listener to the model. Adds the model as a listener to the value source if this - * is the first listener. - * @param l Listener to add. - */ - @Override - public void addChangeListener(EventListener l) { - checkState(true); - - if (listeners.isEmpty()) { - if (source != null) { - source.addChangeListener(this); - lastValue = getValue(); - lastAutomatic = isAutomatic(); - } - } - - listeners.add(l); - log.verbose(this + " adding listener (total " + listeners.size() + "): " + l); - } - - /** - * Remove a listener from the model. Removes the model from being a listener to the Component - * if this was the last listener of the model. - * @param l Listener to remove. - */ - @Override - public void removeChangeListener(EventListener l) { - checkState(false); - - listeners.remove(l); - if (listeners.isEmpty() && source != null) { - source.removeChangeListener(this); - } - log.verbose(this + " removing listener (total " + listeners.size() + "): " + l); - } - - - /** - * Invalidates this model by removing all listeners and removing this from - * listening to the source. After invalidation no listeners can be added to this - * model and the value cannot be set. - */ - @Override - public void invalidate() { - log.verbose("Invalidating " + this); - invalidator.invalidate(); - - if (!listeners.isEmpty()) { - log.warn("Invalidating " + this + " while still having listeners " + listeners); - } - listeners.clear(); - if (source != null) { - source.removeChangeListener(this); - } - MemoryManagement.collectable(this); - } - - - private void checkState(boolean error) { - invalidator.check(error); - } - - - @Override - protected void finalize() throws Throwable { - super.finalize(); - if (!listeners.isEmpty()) { - log.warn(this + " being garbage-collected while having listeners " + listeners); - } - }; - - - /** - * Fire a ChangeEvent to all listeners. - */ - protected void fireStateChanged() { - checkState(true); - - EventObject event = new EventObject(this); - ChangeEvent cevent = new ChangeEvent(this); - firing++; - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] ls = listeners.toArray(new EventListener[0]); - for (EventListener l : ls) { - if (l instanceof StateChangeListener) { - ((StateChangeListener) l).stateChanged(event); - } else if (l instanceof ChangeListener) { - ((ChangeListener) l).stateChanged(cevent); - } - } - firing--; - } - - /** - * Called when the component changes. Checks whether the modeled value has changed, and if - * it has, updates lastValue and generates ChangeEvents for all listeners of the model. - */ - @Override - public void stateChanged(EventObject e) { - checkState(true); - - double v = getValue(); - boolean b = isAutomatic(); - if (lastValue == v && lastAutomatic == b) - return; - lastValue = v; - lastAutomatic = b; - fireStateChanged(); - } - - - /** - * Explain the DoubleModel as a String. - */ - @Override - public String toString() { - if (toString == null) { - if (source == null) { - toString = "DoubleModel[constant=" + lastValue + "]"; - } else { - toString = "DoubleModel[" + source.getClass().getSimpleName() + ":" + valueName + "]"; - } - } - return toString; - } -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/EnumModel.java b/core/src/net/sf/openrocket/gui/adaptors/EnumModel.java deleted file mode 100644 index a6757a38..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/EnumModel.java +++ /dev/null @@ -1,133 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import java.util.EventObject; - -import javax.swing.AbstractListModel; -import javax.swing.ComboBoxModel; - -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.StateChangeListener; - - -public class EnumModel> extends AbstractListModel - implements ComboBoxModel, StateChangeListener { - - private final ChangeSource source; - private final String valueName; - private final String nullText; - - private final Enum[] values; - private Enum currentValue = null; - - private final Reflection.Method getMethod; - private final Reflection.Method setMethod; - - - - public EnumModel(ChangeSource source, String valueName) { - this(source,valueName,null,null); - } - - public EnumModel(ChangeSource source, String valueName, Enum[] values) { - this(source, valueName, values, null); - } - - @SuppressWarnings("unchecked") - public EnumModel(ChangeSource source, String valueName, Enum[] values, String nullText) { - Class> enumClass; - this.source = source; - this.valueName = valueName; - - try { - java.lang.reflect.Method getM = source.getClass().getMethod("get" + valueName); - enumClass = (Class>) getM.getReturnType(); - if (!enumClass.isEnum()) { - throw new IllegalArgumentException("Return type of get" + valueName + - " not an enum type"); - } - - getMethod = new Reflection.Method(getM); - setMethod = new Reflection.Method(source.getClass().getMethod("set" + valueName, - enumClass)); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("get/is methods for enum '"+valueName+ - "' not present in class "+source.getClass().getCanonicalName()); - } - - if (values != null) - this.values = values; - else - this.values = enumClass.getEnumConstants(); - - this.nullText = nullText; - - stateChanged(null); // Update current value - source.addChangeListener(this); - } - - - - @Override - public Object getSelectedItem() { - if (currentValue==null) - return nullText; - return currentValue; - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - if (item instanceof String) { - if (currentValue != null) - setMethod.invoke(source, (Object)null); - return; - } - - if (!(item instanceof Enum)) { - throw new IllegalArgumentException("Not String or Enum, item="+item); - } - - // Comparison with == ok, since both are enums - if (currentValue == item) - return; - setMethod.invoke(source, item); - } - - @Override - public Object getElementAt(int index) { - if (values[index] == null) - return nullText; - return values[index]; - } - - @Override - public int getSize() { - return values.length; - } - - - - - - @SuppressWarnings("unchecked") - @Override - public void stateChanged(EventObject e) { - Enum value = (Enum) getMethod.invoke(source); - if (value != currentValue) { - currentValue = value; - this.fireContentsChanged(this, 0, values.length); - } - } - - - - @Override - public String toString() { - return "EnumModel["+source.getClass().getCanonicalName()+":"+valueName+"]"; - } - -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/IntegerModel.java b/core/src/net/sf/openrocket/gui/adaptors/IntegerModel.java deleted file mode 100644 index e948918a..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/IntegerModel.java +++ /dev/null @@ -1,262 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.EventListener; -import java.util.EventObject; - -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.StateChangeListener; - - -public class IntegerModel implements StateChangeListener { - private static final LogHelper log = Application.getLogger(); - - - //////////// JSpinner Model //////////// - - private class IntegerSpinnerModel extends SpinnerNumberModel { - @Override - public Object getValue() { - return IntegerModel.this.getValue(); - } - - @Override - public void setValue(Object value) { - if (firing > 0) { - // Ignore, if called when model is sending events - log.verbose("Ignoring call to SpinnerModel setValue for " + IntegerModel.this.toString() + - " value=" + value + ", currently firing events"); - return; - - } - Number num = (Number) value; - int newValue = num.intValue(); - log.user("SpinnerModel setValue called for " + IntegerModel.this.toString() + " newValue=" + newValue); - IntegerModel.this.setValue(newValue); - } - - @Override - public Object getNextValue() { - int d = IntegerModel.this.getValue(); - if (d >= maxValue) - return null; - return (d + 1); - } - - @Override - public Object getPreviousValue() { - int d = IntegerModel.this.getValue(); - if (d <= minValue) - return null; - return (d - 1); - } - - @Override - public void addChangeListener(ChangeListener l) { - IntegerModel.this.addChangeListener(l); - } - - @Override - public void removeChangeListener(ChangeListener l) { - IntegerModel.this.removeChangeListener(l); - } - } - - /** - * Returns a new SpinnerModel with the same base as the DoubleModel. - * The values given to the JSpinner are in the currently selected units. - * - * @return A compatibility layer for a SpinnerModel. - */ - public SpinnerModel getSpinnerModel() { - return new IntegerSpinnerModel(); - } - - - - - //////////// Main model ///////////// - - /* - * The main model handles all values in SI units, i.e. no conversion is made within the model. - */ - - private final ChangeSource source; - private final String valueName; - - private final Method getMethod; - private final Method setMethod; - - private final ArrayList listeners = new ArrayList(); - - private final int minValue; - private final int maxValue; - - private String toString = null; - - - private int firing = 0; // >0 when model itself is sending events - - - // Used to differentiate changes in valueName and other changes in the source: - private int lastValue = 0; - - - - /** - * Generates a new DoubleModel that changes the values of the specified source. - * The double value is read and written using the methods "get"/"set" + valueName. - * - * @param source Component whose parameter to use. - * @param valueName Name of methods used to get/set the parameter. - * @param min Minimum value allowed (in SI units) - * @param max Maximum value allowed (in SI units) - */ - public IntegerModel(ChangeSource source, String valueName, int min, int max) { - this.source = source; - this.valueName = valueName; - - this.minValue = min; - this.maxValue = max; - - try { - getMethod = source.getClass().getMethod("get" + valueName); - setMethod = source.getClass().getMethod("set" + valueName, int.class); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("get/set methods for value '" + valueName + - "' not present in class " + source.getClass().getCanonicalName()); - } - } - - public IntegerModel(ChangeSource source, String valueName, int min) { - this(source, valueName, min, Integer.MAX_VALUE); - } - - public IntegerModel(ChangeSource source, String valueName) { - this(source, valueName, Integer.MIN_VALUE, Integer.MAX_VALUE); - } - - - - - /** - * Returns the value of the variable. - */ - public int getValue() { - try { - return (Integer) getMethod.invoke(source); - } catch (IllegalArgumentException e) { - throw new BugException(e); - } catch (IllegalAccessException e) { - throw new BugException(e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - /** - * Sets the value of the variable. - */ - public void setValue(int v) { - log.debug("Setting value " + v + " for " + this); - try { - setMethod.invoke(source, v); - } catch (IllegalArgumentException e) { - throw new BugException(e); - } catch (IllegalAccessException e) { - throw new BugException(e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - - /** - * Add a listener to the model. Adds the model as a listener to the Component if this - * is the first listener. - * @param l Listener to add. - */ - public void addChangeListener(EventListener l) { - if (listeners.isEmpty()) { - source.addChangeListener(this); - lastValue = getValue(); - } - - listeners.add(l); - log.verbose(this + " adding listener (total " + listeners.size() + "): " + l); - } - - /** - * Remove a listener from the model. Removes the model from being a listener to the Component - * if this was the last listener of the model. - * @param l Listener to remove. - */ - public void removeChangeListener(ChangeListener l) { - listeners.remove(l); - if (listeners.isEmpty()) { - source.removeChangeListener(this); - } - log.verbose(this + " removing listener (total " + listeners.size() + "): " + l); - } - - - @Override - protected void finalize() throws Throwable { - super.finalize(); - if (!listeners.isEmpty()) { - log.warn(this + " being garbage-collected while having listeners " + listeners); - } - }; - - - public void fireStateChanged() { - EventListener[] list = listeners.toArray(new EventListener[0] ); - EventObject event = new EventObject(this); - ChangeEvent cevent = new ChangeEvent(this); - firing++; - for( EventListener l : list ) { - if ( l instanceof ChangeListener) { - ((ChangeListener)l).stateChanged(cevent); - } else if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(event); - } - } - firing--; - } - - /** - * Called when the source changes. Checks whether the modeled value has changed, and if - * it has, updates lastValue and generates ChangeEvents for all listeners of the model. - */ - @Override - public void stateChanged(EventObject e) { - int v = getValue(); - if (lastValue == v) - return; - lastValue = v; - fireStateChanged(); - } - - /** - * Explain the DoubleModel as a String. - */ - @Override - public String toString() { - if (toString == null) { - toString = "IntegerModel[" + source.getClass().getSimpleName() + ":" + valueName + "]"; - } - return toString; - } - -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java b/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java deleted file mode 100644 index c3ebf835..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java +++ /dev/null @@ -1,166 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - - -import java.awt.Component; - -import javax.swing.AbstractListModel; -import javax.swing.ComboBoxModel; -import javax.swing.SwingUtilities; - -import net.sf.openrocket.database.Database; -import net.sf.openrocket.database.DatabaseListener; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.gui.dialogs.CustomMaterialDialog; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Reflection; - -public class MaterialModel extends AbstractListModel implements - ComboBoxModel, ComponentChangeListener, DatabaseListener { - - private final String custom; - - - private final Component parentComponent; - - private final RocketComponent component; - private final Material.Type type; - private final Database database; - - private final Reflection.Method getMethod; - private final Reflection.Method setMethod; - private static final Translator trans = Application.getTranslator(); - - - public MaterialModel(Component parent, RocketComponent component, Material.Type type) { - //// Material - //this(parent, component, type, trans.get("MaterialModel.title.Material")); - this(parent, component, type, "Material"); - } - - public MaterialModel(Component parent, RocketComponent component, Material.Type type, - String name) { - this.parentComponent = parent; - this.component = component; - this.type = type; - this.custom = trans.get ("Material.CUSTOM"); - - switch (type) { - case LINE: - this.database = Databases.LINE_MATERIAL; - break; - - case BULK: - this.database = Databases.BULK_MATERIAL; - break; - - case SURFACE: - this.database = Databases.SURFACE_MATERIAL; - break; - - default: - throw new IllegalArgumentException("Unknown material type:"+type); - } - - try { - getMethod = new Reflection.Method(component.getClass().getMethod("get"+name)); - setMethod = new Reflection.Method(component.getClass().getMethod("set"+name, - Material.class)); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("get/is methods for material " + - "not present in class "+component.getClass().getCanonicalName()); - } - - component.addComponentChangeListener(this); - database.addDatabaseListener(this); - } - - @Override - public Object getSelectedItem() { - return getMethod.invoke(component); - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - - if (item == custom) { - - // Open custom material dialog in the future, after combo box has closed - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - CustomMaterialDialog dialog = new CustomMaterialDialog( - SwingUtilities.getWindowAncestor(parentComponent), - (Material) getSelectedItem(), true, - //// Define custom material - trans.get("MaterialModel.title.Defcustmat")); - - dialog.setVisible(true); - - if (!dialog.getOkClicked()) - return; - - Material material = dialog.getMaterial(); - setMethod.invoke(component, material); - - if (dialog.isAddSelected()) { - database.add(material); - } - } - }); - - } else if (item instanceof Material) { - - setMethod.invoke(component, item); - - } else { - throw new IllegalArgumentException("Illegal item class " + item.getClass() + - " item=" + item); - } - } - - @Override - public Object getElementAt(int index) { - if (index == database.size()) { - return custom; - } else if (index >= database.size()+1) { - return null; - } - return database.get(index); - } - - @Override - public int getSize() { - return database.size() + 1; - } - - - - //////// Change listeners - - @Override - public void componentChanged(ComponentChangeEvent e) { - if (((ComponentChangeEvent)e).isMassChange()) { - this.fireContentsChanged(this, 0, 0); - } - } - - @Override - public void elementAdded(Material element, Database source) { - this.fireContentsChanged(this, 0, database.size()); - } - - @Override - public void elementRemoved(Material element, Database source) { - this.fireContentsChanged(this, 0, database.size()); - } - -} diff --git a/core/src/net/sf/openrocket/gui/adaptors/MotorConfigurationModel.java b/core/src/net/sf/openrocket/gui/adaptors/MotorConfigurationModel.java deleted file mode 100644 index 57852699..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/MotorConfigurationModel.java +++ /dev/null @@ -1,170 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - - -import java.util.EventObject; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.ComboBoxModel; -import javax.swing.SwingUtilities; -import javax.swing.event.EventListenerList; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; - -import net.sf.openrocket.gui.dialogs.EditMotorConfigurationDialog; -import net.sf.openrocket.gui.main.BasicFrame; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.StateChangeListener; - -public class MotorConfigurationModel implements ComboBoxModel, StateChangeListener { - private static final Translator trans = Application.getTranslator(); - - private static final String EDIT = trans.get("MotorCfgModel.Editcfg"); - - - private EventListenerList listenerList = new EventListenerList(); - - private final Configuration config; - private final Rocket rocket; - - private Map map = new HashMap(); - - - public MotorConfigurationModel(Configuration config) { - this.config = config; - this.rocket = config.getRocket(); - config.addChangeListener(this); - } - - - - @Override - public Object getElementAt(int index) { - String[] ids = rocket.getMotorConfigurationIDs(); - if (index < 0 || index > ids.length) - return null; - - if (index == ids.length) - return EDIT; - - return get(ids[index]); - } - - @Override - public int getSize() { - return rocket.getMotorConfigurationIDs().length + 1; - } - - @Override - public Object getSelectedItem() { - return get(config.getMotorConfigurationID()); - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - if (item == EDIT) { - - // Open edit dialog in the future, after combo box has closed - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - new EditMotorConfigurationDialog(rocket, BasicFrame.findFrame(rocket)) - .setVisible(true); - } - }); - - return; - } - if (!(item instanceof ID)) { - throw new IllegalArgumentException("MotorConfigurationModel item="+item); - } - - ID idObject = (ID) item; - config.setMotorConfigurationID(idObject.getID()); - } - - - - //////////////// Event/listener handling //////////////// - - - @Override - public void addListDataListener(ListDataListener l) { - listenerList.add(ListDataListener.class, l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listenerList.remove(ListDataListener.class, l); - } - - protected void fireListDataEvent() { - Object[] listeners = listenerList.getListenerList(); - ListDataEvent e = null; - - for (int i = listeners.length-2; i>=0; i-=2) { - if (listeners[i] == ListDataListener.class) { - if (e == null) - e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize()); - ((ListDataListener) listeners[i+1]).contentsChanged(e); - } - } - } - - - @Override - public void stateChanged(EventObject e) { - if (e instanceof ComponentChangeEvent) { - // Ignore unnecessary changes - if (!((ComponentChangeEvent)e).isMotorChange()) - return; - } - fireListDataEvent(); - } - - - - /* - * The ID class is an adapter, that contains the actual configuration ID, - * but gives the configuration description as its String representation. - * The get(id) method retrieves ID objects and caches them for reuse. - */ - - private ID get(String id) { - ID idObject = map.get(id); - if (idObject != null) - return idObject; - - idObject = new ID(id); - map.put(id, idObject); - return idObject; - } - - - private class ID { - private final String id; - - public ID(String id) { - this.id = id; - } - - public String getID() { - return id; - } - - @Override - public String toString() { - return rocket.getMotorConfigurationNameOrDescription(id); - } - } - -} - diff --git a/core/src/net/sf/openrocket/gui/adaptors/PresetModel.java b/core/src/net/sf/openrocket/gui/adaptors/PresetModel.java deleted file mode 100644 index 474610de..00000000 --- a/core/src/net/sf/openrocket/gui/adaptors/PresetModel.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.sf.openrocket.gui.adaptors; - -import java.awt.Component; -import java.util.List; - -import javax.swing.AbstractListModel; -import javax.swing.ComboBoxModel; -import javax.swing.SwingUtilities; - -import net.sf.openrocket.database.Database; -import net.sf.openrocket.database.DatabaseListener; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.dialogs.preset.ComponentPresetChooserDialog; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; - -public class PresetModel extends AbstractListModel implements ComboBoxModel, ComponentChangeListener, DatabaseListener { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private static final String NONE_SELECTED = trans.get("lbl.select"); - private static final String SELECT_DATABASE = trans.get("lbl.database"); - - private final Component parent; - private final RocketComponent component; - private final OpenRocketDocument document; - private ComponentPreset previousPreset; - - private List presets; - - public PresetModel(Component parent, OpenRocketDocument document, RocketComponent component) { - this.parent = parent; - this.document = document; - presets = Application.getComponentPresetDao().listForType(component.getPresetType(), true); - this.component = component; - previousPreset = component.getPresetComponent(); - component.addComponentChangeListener(this); - } - - @Override - public int getSize() { - return presets.size() + 2; - } - - @Override - public Object getElementAt(int index) { - if (index == 0) { - return NONE_SELECTED; - } - if (index == getSize() - 1) { - return SELECT_DATABASE; - } - return presets.get(index - 1); - } - - @Override - public void setSelectedItem(Object item) { - log.user("User selected preset item '" + item + "' for component " + component); - - if (item == null) { - throw new BugException("item is null"); - } else if (item.equals(NONE_SELECTED)) { - component.clearPreset(); - } else if (item.equals(SELECT_DATABASE)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ComponentPresetChooserDialog dialog = - new ComponentPresetChooserDialog(SwingUtilities.getWindowAncestor(parent), component); - dialog.setVisible(true); - ComponentPreset preset = dialog.getSelectedComponentPreset(); - if (preset != null) { - setSelectedItem(preset); - } - } - }); - } else { - document.addUndoPosition("Use Preset " + component.getComponentName()); - component.loadPreset((ComponentPreset) item); - } - } - - @Override - public Object getSelectedItem() { - ComponentPreset preset = component.getPresetComponent(); - if (preset == null) { - return NONE_SELECTED; - } else { - return preset; - } - } - - @Override - public void componentChanged(ComponentChangeEvent e) { - if (previousPreset != component.getPresetComponent()) { - previousPreset = component.getPresetComponent(); - fireContentsChanged(this, 0, getSize()); - } - } - - @Override - public void elementAdded(ComponentPreset element, Database source) { - presets = Application.getComponentPresetDao().listForType(component.getPresetType(), true); - this.fireContentsChanged(this, 0, getSize()); - } - - @Override - public void elementRemoved(ComponentPreset element, Database source) { - presets = Application.getComponentPresetDao().listForType(component.getPresetType(), true); - this.fireContentsChanged(this, 0, getSize()); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/BasicSlider.java b/core/src/net/sf/openrocket/gui/components/BasicSlider.java deleted file mode 100644 index 0ac92e79..00000000 --- a/core/src/net/sf/openrocket/gui/components/BasicSlider.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.gui.components; - -import javax.swing.BoundedRangeModel; -import javax.swing.JSlider; -import javax.swing.plaf.basic.BasicSliderUI; - -/** - * A simple slider that does not show the current value. GTK l&f shows the value, and cannot - * be configured otherwise(!). - * - * @author Sampo Niskanen - */ - -public class BasicSlider extends JSlider { - - public BasicSlider(BoundedRangeModel brm) { - this(brm,JSlider.HORIZONTAL,false); - } - - public BasicSlider(BoundedRangeModel brm, int orientation) { - this(brm,orientation,false); - } - - public BasicSlider(BoundedRangeModel brm, int orientation, boolean inverted) { - super(brm); - setOrientation(orientation); - setInverted(inverted); - setUI(new BasicSliderUI(this)); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/BasicTree.java b/core/src/net/sf/openrocket/gui/components/BasicTree.java deleted file mode 100644 index 6ec8804e..00000000 --- a/core/src/net/sf/openrocket/gui/components/BasicTree.java +++ /dev/null @@ -1,145 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; - -import javax.swing.Icon; -import javax.swing.JTree; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -public class BasicTree extends JTree { - - - public BasicTree() { - super(); - setDefaultOptions(); - } - - public BasicTree(TreeNode node) { - super(node); - setDefaultOptions(); - } - - - private void setDefaultOptions() { - this.setToggleClickCount(0); - - javax.swing.plaf.basic.BasicTreeUI plainUI = new javax.swing.plaf.basic.BasicTreeUI(); - this.setUI(plainUI); - plainUI.setExpandedIcon(TreeIcon.MINUS); - plainUI.setCollapsedIcon(TreeIcon.PLUS); - plainUI.setLeftChildIndent(15); - - - this.setBackground(Color.WHITE); - this.setShowsRootHandles(false); - } - - - /** - * Expand the entire tree structure. All nodes will be visible after the call. - */ - public void expandTree() { - for (int i = 0; i < getRowCount(); i++) - expandRow(i); - } - - - - - @Override - public void treeDidChange() { - super.treeDidChange(); - /* - * Expand the childless nodes to prevent leaf nodes from looking expandable. - */ - expandChildlessNodes(); - } - - /** - * Expand all nodes in the tree that are visible and have no children. This can be used - * to avoid the situation where a non-leaf node is marked as being expandable, but when - * expanding it it has no children. - */ - private void expandChildlessNodes() { - TreeModel model = this.getModel(); - if (model == null) { - return; - } - Object root = model.getRoot(); - expandChildlessNodes(model, new TreePath(root)); - } - - private void expandChildlessNodes(TreeModel model, TreePath path) { - Object object = path.getLastPathComponent(); - if (this.isVisible(path)) { - int count = model.getChildCount(object); - if (count == 0) { - this.expandPath(path); - } - for (int i = 0; i < count; i++) { - expandChildlessNodes(model, path.pathByAddingChild(model.getChild(object, i))); - } - } - } - - - - /** - * Plain-looking tree expand/collapse icons. - */ - private static class TreeIcon implements Icon { - public static final Icon PLUS = new TreeIcon(true); - public static final Icon MINUS = new TreeIcon(false); - - // Implementation: - - private final static int width = 9; - private final static int height = 9; - private final static BasicStroke stroke = new BasicStroke(2); - private boolean plus; - - private TreeIcon(boolean plus) { - this.plus = plus; - } - - @Override - public void paintIcon(Component c, Graphics g, int x, int y) { - Graphics2D g2 = (Graphics2D) g.create(); - - // Background - g2.setColor(Color.WHITE); - g2.fillRect(x, y, width, height); - - // Border - g2.setColor(Color.DARK_GRAY); - g2.drawRect(x, y, width, height); - - // Horizontal stroke - g2.setStroke(stroke); - g2.drawLine(x + 3, y + (height + 1) / 2, x + width - 2, y + (height + 1) / 2); - - // Vertical stroke - if (plus) { - g2.drawLine(x + (width + 1) / 2, y + 3, x + (width + 1) / 2, y + height - 2); - } - - g2.dispose(); - } - - @Override - public int getIconWidth() { - return width; - } - - @Override - public int getIconHeight() { - return height; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/components/CollectionTable.java b/core/src/net/sf/openrocket/gui/components/CollectionTable.java deleted file mode 100644 index ef14dc61..00000000 --- a/core/src/net/sf/openrocket/gui/components/CollectionTable.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.sf.openrocket.gui.components; - -import javax.swing.JTable; -import javax.swing.table.AbstractTableModel; - - -/* - * TODO: LOW: This is currently unused. - */ -public abstract class CollectionTable extends JTable { - - private final String[] columnNames; - private CollectionTableModel model; - - - protected CollectionTable(String[] columnNames) { - this.columnNames = columnNames.clone(); - } - - - protected void initializeTable() { - model = new CollectionTableModel(); - this.setModel(model); - } - - - /** - * Retrieve the object for the specified row number. - * - * @param row the row number being queried. - * @return the object at that row. - */ - protected abstract T getModelObjectAt(int row); - - protected abstract int getModelRowCount(); - - - - protected abstract Object getViewForModelObject(T object, int column); - - protected Class getViewColumnClass(int column) { - return Object.class; - } - - - - private class CollectionTableModel extends AbstractTableModel { - @Override - public int getColumnCount() { - return columnNames.length; - } - - @Override - public String getColumnName(int column) { - return columnNames[column]; - } - - @Override - public Class getColumnClass(int column) { - return getViewColumnClass(column); - } - - - @Override - public int getRowCount() { - return getModelRowCount(); - } - - @Override - public Object getValueAt(int row, int column) { - T value = getModelObjectAt(row); - return getViewForModelObject(value, column); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/components/ColorChooser.java b/core/src/net/sf/openrocket/gui/components/ColorChooser.java deleted file mode 100644 index e149e3ca..00000000 --- a/core/src/net/sf/openrocket/gui/components/ColorChooser.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ColorChooser.java - */ -package net.sf.openrocket.gui.components; - -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.colorchooser.ColorSelectionModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * A panel implementation of a color chooser. The panel has a label and a textfield. The label identifies - * what the color is to be used for (the purpose), and the textfield is uneditable but has its background set - * to the currently chosen color as a way of visualizing the color. - * - * The chosen color may be retrieved via a call to getCurrentColor. - */ -public class ColorChooser extends JPanel { - - private static final String COLOR_CHOOSER_BUTTON_LABEL = "Color"; - - // The currently selected color - private Color curColor; - - final JColorChooser chooser; - final JLabel label; - final JTextField field; - final JPanel p; - - /** - * Construct a color chooser as a panel. - * l - * @param parent the parent panel to which this component will be added - * @param theChooser the delegated color chooser; the initial color taken from this chooser - * @param theLabel the label used as the 'purpose' of the color; placed next to a textfield - */ - public ColorChooser (JPanel parent, JColorChooser theChooser, final String theLabel) { - p = parent; - chooser = theChooser; - chooser.setPreviewPanel(this); - // Initialize the currently selected color - curColor = chooser.getColor(); - label = new JLabel(theLabel + ":"); - - parent.add(label, "align right"); - field = new JTextField(); - field.setEditable(false); - field.setBackground(curColor); - parent.add(field, "width 50:100:100"); - - final JButton button = new JButton(COLOR_CHOOSER_BUTTON_LABEL); - - ActionListener actionListener = new ActionListener() { - public void actionPerformed (ActionEvent actionEvent) { - chooser.updateUI(); - - final JDialog dialog = JColorChooser.createDialog(null, - theLabel, true, - chooser, - null, null); - - // Wait until current event dispatching completes before showing - // dialog - Runnable showDialog = new Runnable() { - public void run () { - dialog.show(); - } - }; - SwingUtilities.invokeLater(showDialog); - } - }; - button.addActionListener(actionListener); - parent.add(button, "wrap"); - - // Add listener on model to detect changes to selected color - ColorSelectionModel model = chooser.getSelectionModel(); - model.addChangeListener(new ChangeListener() { - public void stateChanged (ChangeEvent evt) { - ColorSelectionModel model = (ColorSelectionModel) evt.getSource(); - // Get the new color value - curColor = model.getSelectedColor(); - field.setBackground(curColor); - } - }); - } - - /** - * Get the user-selected color. - * - * @return the current color - */ - public Color getCurrentColor () { - return curColor; - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/components/ColorChooserButton.java b/core/src/net/sf/openrocket/gui/components/ColorChooserButton.java deleted file mode 100644 index 15e4adc6..00000000 --- a/core/src/net/sf/openrocket/gui/components/ColorChooserButton.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeListener; - -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JDialog; -import javax.swing.JPanel; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * A color chooser button. The currently selected color can be queried or set using the - * {@link #getSelectedColor()} and {@link #setSelectedColor(Color)}, and changes listened - * to by listening to property events with property name {@link #COLOR_KEY}. - * - * @author Sampo Niskanen - */ -public class ColorChooserButton extends JButton { - private static final LogHelper log = Application.getLogger(); - - public static final String COLOR_KEY = "selectedColor"; - - - public ColorChooserButton(Color initial) { - - setSelectedColor(initial); - - // Add action listener that opens color chooser dialog - this.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Activating color chooser"); - final JColorChooser chooser = new JColorChooser(getSelectedColor()); - chooser.setPreviewPanel(new JPanel()); - final JDialog dialog = JColorChooser.createDialog(ColorChooserButton.this, "Select color", true, - chooser, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e2) { - Color c = chooser.getColor(); - log.user("User selected color " + c); - setSelectedColor(chooser.getColor()); - } - }, null); - log.info("Closing color chooser"); - dialog.setVisible(true); - } - }); - - } - - - public void addColorPropertyChangeListener(PropertyChangeListener listener) { - this.addPropertyChangeListener(COLOR_KEY, listener); - } - - public void setSelectedColor(Color c) { - log.debug("Selecting color " + c); - this.setIcon(new ColorIcon(c)); - this.putClientProperty(COLOR_KEY, c); - } - - public Color getSelectedColor() { - return (Color) this.getClientProperty(COLOR_KEY); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/ColorIcon.java b/core/src/net/sf/openrocket/gui/components/ColorIcon.java deleted file mode 100644 index 747a4268..00000000 --- a/core/src/net/sf/openrocket/gui/components/ColorIcon.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Color; - -import javax.swing.Icon; - -/** - * An Icon that displays a specific color, suitable for drawing into a button. - * - * @author Sampo Niskanen - */ -public class ColorIcon implements Icon { - private final Color color; - - public ColorIcon(Color c) { - this.color = c; - } - - @Override - public int getIconHeight() { - return 15; - } - - @Override - public int getIconWidth() { - return 25; - } - - @Override - public void paintIcon(java.awt.Component c, java.awt.Graphics g, int x, int y) { - g.setColor(color); - g.fill3DRect(x, y, getIconWidth(), getIconHeight(), false); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/CsvOptionPanel.java b/core/src/net/sf/openrocket/gui/components/CsvOptionPanel.java deleted file mode 100644 index cd979e16..00000000 --- a/core/src/net/sf/openrocket/gui/components/CsvOptionPanel.java +++ /dev/null @@ -1,126 +0,0 @@ -package net.sf.openrocket.gui.components; - -import javax.swing.BorderFactory; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; - -/** - * A panel that shows options for saving CSV files. - * - * @author Sampo Niskanen - */ -public class CsvOptionPanel extends JPanel { - - private static final Translator trans = Application.getTranslator(); - - private static final String SPACE = trans.get("CsvOptionPanel.separator.space"); - private static final String TAB = trans.get("CsvOptionPanel.separator.tab"); - - private final String baseClassName; - - private final JComboBox fieldSeparator; - private final JCheckBox[] options; - private final JComboBox commentCharacter; - - /** - * Sole constructor. - * - * @param includeComments a list of comment inclusion options to provide; - * every second item is the option name and every second the tooltip - */ - public CsvOptionPanel(Class baseClass, String... includeComments) { - super(new MigLayout("fill, insets 0")); - - this.baseClassName = baseClass.getSimpleName(); - - JPanel panel; - JLabel label; - String tip; - - - // TODO: HIGH: Rename the translation keys - - // Field separator panel - panel = new JPanel(new MigLayout("fill")); - panel.setBorder(BorderFactory.createTitledBorder(trans.get("SimExpPan.border.Fieldsep"))); - - label = new JLabel(trans.get("SimExpPan.lbl.Fieldsepstr")); - tip = trans.get("SimExpPan.lbl.longA1") + - trans.get("SimExpPan.lbl.longA2"); - label.setToolTipText(tip); - panel.add(label, "gapright unrel"); - - fieldSeparator = new JComboBox(new String[] { ",", ";", SPACE, TAB }); - fieldSeparator.setEditable(true); - fieldSeparator.setSelectedItem(Application.getPreferences().getString(Preferences.EXPORT_FIELD_SEPARATOR, ",")); - fieldSeparator.setToolTipText(tip); - panel.add(fieldSeparator, "growx"); - - this.add(panel, "growx, wrap unrel"); - - - - // Comments separator panel - panel = new JPanel(new MigLayout("fill")); - panel.setBorder(BorderFactory.createTitledBorder(trans.get("SimExpPan.border.Comments"))); - - - // List of include comments options - if (includeComments.length % 2 == 1) { - throw new IllegalArgumentException("Invalid argument length, must be even, length=" + includeComments.length); - } - options = new JCheckBox[includeComments.length / 2]; - for (int i = 0; i < includeComments.length / 2; i++) { - options[i] = new JCheckBox(includeComments[i * 2]); - options[i].setToolTipText(includeComments[i * 2 + 1]); - options[i].setSelected(Application.getPreferences().getBoolean("csvOptions." + baseClassName + "." + i, true)); - panel.add(options[i], "wrap"); - } - - - label = new JLabel(trans.get("SimExpPan.lbl.Commentchar")); - tip = trans.get("SimExpPan.lbl.ttip.Commentchar"); - label.setToolTipText(tip); - panel.add(label, "split 2, gapright unrel"); - - commentCharacter = new JComboBox(new String[] { "#", "%", ";" }); - commentCharacter.setEditable(true); - commentCharacter.setSelectedItem(Application.getPreferences().getString(Preferences.EXPORT_COMMENT_CHARACTER, "#")); - commentCharacter.setToolTipText(tip); - panel.add(commentCharacter, "growx"); - - this.add(panel, "growx, wrap"); - } - - - public String getFieldSeparator() { - return fieldSeparator.getSelectedItem().toString(); - } - - public String getCommentCharacter() { - return commentCharacter.getSelectedItem().toString(); - } - - public boolean getSelectionOption(int index) { - return options[index].isSelected(); - } - - /** - * Store the selected options to the user preferences. - */ - public void storePreferences() { - Application.getPreferences().putString(Preferences.EXPORT_FIELD_SEPARATOR, getFieldSeparator()); - Application.getPreferences().putString(Preferences.EXPORT_COMMENT_CHARACTER, getCommentCharacter()); - for (int i = 0; i < options.length; i++) { - Application.getPreferences().putBoolean("csvOptions." + baseClassName + "." + i, options[i].isSelected()); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/DescriptionArea.java b/core/src/net/sf/openrocket/gui/components/DescriptionArea.java deleted file mode 100644 index 1e37bb6f..00000000 --- a/core/src/net/sf/openrocket/gui/components/DescriptionArea.java +++ /dev/null @@ -1,106 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Rectangle; - -import javax.swing.JEditorPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingUtilities; - -public class DescriptionArea extends JScrollPane { - - private final JEditorPane editorPane; - - - /** - * Construct a description area with the specified number of rows, default description font size, - * being opaque. - * - * @param rows the number of rows - */ - public DescriptionArea(int rows) { - this("", rows, -1); - } - - /** - * Construct a description area with the specified number of rows and size, being opaque. - * - * @param rows the number of rows. - * @param size the font size difference compared to the default font size. - */ - public DescriptionArea(int rows, float size) { - this("", rows, size); - } - - /** - * Construct an opaque description area with the specified number of rows, size and text, being opaque. - * - * @param text the initial text. - * @param rows the number of rows. - * @param size the font size difference compared to the default font size. - */ - public DescriptionArea(String text, int rows, float size) { - this(text, rows, size, true); - } - - /** - * Constructor with all options. - * - * @param text the text for the description area. - * @param rows the number of rows to set - * @param size the relative font size in points (positive or negative) - * @param opaque if false the background color will be set to the background color - * of a default JPanel (simulation non-opaque) - */ - public DescriptionArea(String text, int rows, float size, boolean opaque) { - super(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - - editorPane = new JEditorPane("text/html", ""); - Font font = editorPane.getFont(); - editorPane.setFont(font.deriveFont(font.getSize2D() + size)); - editorPane.setEditable(false); - - if (!opaque) { - Color bg = new JPanel().getBackground(); - editorPane.setBackground(new Color(bg.getRed(), bg.getGreen(), bg.getBlue())); - this.setOpaque(true); - } - - // Calculate correct height - editorPane.setText("abc"); - Dimension oneline = editorPane.getPreferredSize(); - editorPane.setText("abc
def"); - Dimension twolines = editorPane.getPreferredSize(); - editorPane.setText(""); - - int lineheight = twolines.height - oneline.height; - int extraheight = oneline.height - lineheight; - - Dimension dim = editorPane.getPreferredSize(); - dim.height = lineheight * rows + extraheight + 2; - this.setPreferredSize(dim); - - this.setViewportView(editorPane); - this.setText(text); - } - - public void setText(String txt) { - editorPane.setText(txt); - editorPane.revalidate(); - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - editorPane.scrollRectToVisible(new Rectangle(0, 0, 1, 1)); - } - - }); - editorPane.scrollRectToVisible(new Rectangle(0, 0, 1, 1)); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/DoubleCellEditor.java b/core/src/net/sf/openrocket/gui/components/DoubleCellEditor.java deleted file mode 100644 index 1602350a..00000000 --- a/core/src/net/sf/openrocket/gui/components/DoubleCellEditor.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Component; -import java.text.ParseException; - -import javax.swing.AbstractCellEditor; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.table.TableCellEditor; - -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; - -public class DoubleCellEditor extends AbstractCellEditor implements TableCellEditor { - - private final JSpinner editor; - private final DoubleModel model; - - public DoubleCellEditor() { - model = new DoubleModel(0); - editor = new JSpinner(model.getSpinnerModel()); - editor.setEditor(new SpinnerEditor(editor)); - // editor.addChangeListener(this); - } - - - @Override - public Component getTableCellEditorComponent(JTable table, Object value, - boolean isSelected, int row, int column) { - - double val = (Double) value; - model.setValue(val); - - return editor; - } - - - @Override - public boolean stopCellEditing() { - try { - editor.commitEdit(); - } catch (ParseException e) { - // Ignore - } - return super.stopCellEditing(); - } - - - @Override - public Object getCellEditorValue() { - return model.getValue(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/FlatButton.java b/core/src/net/sf/openrocket/gui/components/FlatButton.java deleted file mode 100644 index d4c39ef4..00000000 --- a/core/src/net/sf/openrocket/gui/components/FlatButton.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JButton; - -/** - * A JButton that appears flat until you roll over it. - * - * @author Sampo Niskanen - */ -public class FlatButton extends JButton { - - public FlatButton() { - super(); - initialize(); - } - - public FlatButton(Icon icon) { - super(icon); - initialize(); - } - - public FlatButton(String text) { - super(text); - initialize(); - } - - public FlatButton(Action a) { - super(a); - initialize(); - } - - public FlatButton(String text, Icon icon) { - super(text, icon); - initialize(); - } - - - private void initialize() { - this.addMouseListener(new MouseAdapter() { - @Override - public void mouseExited(MouseEvent e) { - flatten(); - } - - @Override - public void mouseEntered(MouseEvent e) { - raise(); - } - }); - flatten(); - } - - - private void flatten() { - this.setContentAreaFilled(false); - this.setBorderPainted(false); - } - - private void raise() { - this.setContentAreaFilled(true); - this.setBorderPainted(true); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/HtmlLabel.java b/core/src/net/sf/openrocket/gui/components/HtmlLabel.java deleted file mode 100644 index 59fdbfa7..00000000 --- a/core/src/net/sf/openrocket/gui/components/HtmlLabel.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Dimension; - -import javax.swing.JLabel; - -/** - * A JLabel that limits the minimum and maximum height of the label to the - * initial preferred height of the label. This is required in labels that use HTML - * since these often cause the panels to expand too much in height. - * - * @author Sampo Niskanen - */ -public class HtmlLabel extends JLabel { - - public HtmlLabel() { - super(); - limitSize(); - } - - public HtmlLabel(String text) { - super(text); - limitSize(); - } - - public HtmlLabel(String text, int horizontalAlignment) { - super(text, horizontalAlignment); - limitSize(); - } - - - private void limitSize() { - Dimension dim = this.getPreferredSize(); - this.setMinimumSize(new Dimension(0, dim.height)); - this.setMaximumSize(new Dimension(Integer.MAX_VALUE, dim.height)); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/ImageDisplayComponent.java b/core/src/net/sf/openrocket/gui/components/ImageDisplayComponent.java deleted file mode 100644 index aaf82928..00000000 --- a/core/src/net/sf/openrocket/gui/components/ImageDisplayComponent.java +++ /dev/null @@ -1,124 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.File; - -import javax.imageio.ImageIO; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.util.MathUtil; - -/** - * Draws a BufferedImage centered and scaled to fit to the component. - * - * @author Sampo Niskanen - */ -public class ImageDisplayComponent extends JPanel { - - private BufferedImage image; - - public ImageDisplayComponent() { - this(null); - } - - public ImageDisplayComponent(BufferedImage image) { - this.image = image; - } - - - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - - if (image == null) { - return; - } - - final int width = Math.max(this.getWidth(), 1); - final int height = Math.max(this.getHeight(), 1); - - final int origWidth = Math.max(image.getWidth(), 1); - final int origHeight = Math.max(image.getHeight(), 1); - - - // Determine scaling factor - double scaleX = ((double) width) / origWidth; - double scaleY = ((double) height) / origHeight; - - double scale = MathUtil.min(scaleX, scaleY); - - if (scale >= 1) { - scale = 1.0; - } - - - // Center in the middle of the component - int finalWidth = (int) Math.round(origWidth * scale); - int finalHeight = (int) Math.round(origHeight * scale); - - int posX = (width - finalWidth) / 2; - int posY = (height - finalHeight) / 2; - - - // Draw the image - int dx1 = posX; - int dy1 = posY; - int dx2 = posX + finalWidth; - int dy2 = posY + finalHeight; - int sx1 = 0; - int sy1 = 0; - int sx2 = origWidth; - int sy2 = origHeight; - - Graphics2D g2 = (Graphics2D) g; - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); - g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null); - - } - - - public BufferedImage getImage() { - return image; - } - - - public void setImage(BufferedImage image) { - this.image = image; - this.repaint(); - } - - - public static void main(String[] args) throws Exception { - final BufferedImage image = ImageIO.read(new File("test.png")); - - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - - JFrame frame = new JFrame(); - - JPanel panel = new JPanel(new MigLayout("fill")); - panel.setBackground(Color.red); - frame.add(panel); - - ImageDisplayComponent c = new ImageDisplayComponent(image); - panel.add(c, "grow"); - - frame.setSize(500, 500); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.setVisible(true); - - } - }); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/SelectableLabel.java b/core/src/net/sf/openrocket/gui/components/SelectableLabel.java deleted file mode 100644 index d4fd622e..00000000 --- a/core/src/net/sf/openrocket/gui/components/SelectableLabel.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Cursor; -import java.awt.Dimension; - -import javax.swing.JTextField; -import javax.swing.UIManager; -import javax.swing.plaf.basic.BasicTextFieldUI; - -public class SelectableLabel extends JTextField { - - public SelectableLabel() { - this(""); - } - - public SelectableLabel(String text) { - super(text); - - // Set basic UI since GTK l&f doesn't support null border - this.setUI(new BasicTextFieldUI()); - - this.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); - - this.setEditable(false); - this.setBorder(null); - this.setOpaque(true); - if (UIManager.getColor("Label.foreground") != null) - this.setForeground(UIManager.getColor("Label.foreground")); - if (UIManager.getColor("Label.background") != null) - this.setBackground(UIManager.getColor("Label.background")); - if (UIManager.getFont("Label.font") != null) - this.setFont(UIManager.getFont("Label.font")); - - } - - // The default preferred size is slightly too short, causing it to scroll - @Override - public Dimension getPreferredSize() { - Dimension dim = super.getPreferredSize(); - dim.width += 5; - return dim; - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/SimulationExportPanel.java b/core/src/net/sf/openrocket/gui/components/SimulationExportPanel.java deleted file mode 100644 index 69bc02f0..00000000 --- a/core/src/net/sf/openrocket/gui/components/SimulationExportPanel.java +++ /dev/null @@ -1,432 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.Arrays; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.util.FileHelper; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.gui.util.SaveCSVWorker; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; - -public class SimulationExportPanel extends JPanel { - - private static final String SPACE = "SPACE"; - private static final String TAB = "TAB"; - private static final Translator trans = Application.getTranslator(); - - private static final int OPTION_SIMULATION_COMMENTS = 0; - private static final int OPTION_FIELD_DESCRIPTIONS = 1; - private static final int OPTION_FLIGHT_EVENTS = 2; - - private final JTable table; - private final SelectionTableModel tableModel; - private final JLabel selectedCountLabel; - - private final Simulation simulation; - private final FlightDataBranch branch; - - private final boolean[] selected; - private final FlightDataType[] types; - private final Unit[] units; - - private final CsvOptionPanel csvOptions; - - - public SimulationExportPanel(Simulation sim) { - super(new MigLayout("fill, flowy")); - - JPanel panel; - JButton button; - - - this.simulation = sim; - - // TODO: MEDIUM: Only exports primary branch - - final FlightData data = simulation.getSimulatedData(); - - // Check that data exists - if (data == null || data.getBranchCount() == 0 || - data.getBranch(0).getTypes().length == 0) { - throw new IllegalArgumentException("No data for panel"); - } - - - // Create the data model - branch = data.getBranch(0); - - types = branch.getTypes(); - Arrays.sort(types); - - selected = new boolean[types.length]; - units = new Unit[types.length]; - for (int i = 0; i < types.length; i++) { - selected[i] = ((SwingPreferences) Application.getPreferences()).isExportSelected(types[i]); - units[i] = types[i].getUnitGroup().getDefaultUnit(); - } - - - //// Create the panel - - - // Set up the variable selection table - tableModel = new SelectionTableModel(); - table = new JTable(tableModel); - table.setDefaultRenderer(Object.class, - new SelectionBackgroundCellRenderer(table.getDefaultRenderer(Object.class))); - table.setDefaultRenderer(Boolean.class, - new SelectionBackgroundCellRenderer(table.getDefaultRenderer(Boolean.class))); - table.setRowSelectionAllowed(false); - table.setColumnSelectionAllowed(false); - - table.setDefaultEditor(Unit.class, new UnitCellEditor() { - @Override - protected UnitGroup getUnitGroup(Unit value, int row, int column) { - return types[row].getUnitGroup(); - } - }); - - // Set column widths - TableColumnModel columnModel = table.getColumnModel(); - TableColumn col = columnModel.getColumn(0); - int w = table.getRowHeight(); - col.setMinWidth(w); - col.setPreferredWidth(w); - col.setMaxWidth(w); - - col = columnModel.getColumn(1); - col.setPreferredWidth(200); - - col = columnModel.getColumn(2); - col.setPreferredWidth(100); - - table.addMouseListener(new GUIUtil.BooleanTableClickListener(table)); - - // Add table - panel = new JPanel(new MigLayout("fill")); - panel.setBorder(BorderFactory.createTitledBorder(trans.get("SimExpPan.border.Vartoexport"))); - - panel.add(new JScrollPane(table), "wmin 300lp, width 300lp, height 1, grow 100, wrap"); - - // Select all/none buttons - button = new JButton(trans.get("SimExpPan.but.Selectall")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tableModel.selectAll(); - } - }); - panel.add(button, "split 2, growx 1, sizegroup selectbutton"); - - button = new JButton(trans.get("SimExpPan.but.Selectnone")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tableModel.selectNone(); - } - }); - panel.add(button, "growx 1, sizegroup selectbutton, wrap"); - - - selectedCountLabel = new JLabel(); - updateSelectedCount(); - panel.add(selectedCountLabel); - - this.add(panel, "grow 100, wrap"); - - - // These need to be in the order of the OPTIONS_XXX indices - csvOptions = new CsvOptionPanel(SimulationExportPanel.class, - trans.get("SimExpPan.checkbox.Includesimudesc"), - trans.get("SimExpPan.checkbox.ttip.Includesimudesc"), - trans.get("SimExpPan.checkbox.Includefielddesc"), - trans.get("SimExpPan.checkbox.ttip.Includefielddesc"), - trans.get("SimExpPan.checkbox.Incflightevents"), - trans.get("SimExpPan.checkbox.ttip.Incflightevents")); - - this.add(csvOptions, "spany, split, growx 1"); - - - // Space-filling panel - panel = new JPanel(); - this.add(panel, "width 1, height 1, grow 1"); - - - // Export button - button = new JButton(trans.get("SimExpPan.but.Exporttofile")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - doExport(); - } - }); - this.add(button, "gapbottom para, gapright para, right"); - - } - - - private void doExport() { - JFileChooser chooser = new JFileChooser(); - chooser.setFileFilter(FileHelper.CSV_FILE_FILTER); - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) - return; - - File file = chooser.getSelectedFile(); - if (file == null) - return; - - file = FileHelper.ensureExtension(file, "csv"); - if (!FileHelper.confirmWrite(file, this)) { - return; - } - - - String commentChar = csvOptions.getCommentCharacter(); - String fieldSep = csvOptions.getFieldSeparator(); - boolean simulationComment = csvOptions.getSelectionOption(OPTION_SIMULATION_COMMENTS); - boolean fieldComment = csvOptions.getSelectionOption(OPTION_FIELD_DESCRIPTIONS); - boolean eventComment = csvOptions.getSelectionOption(OPTION_FLIGHT_EVENTS); - csvOptions.storePreferences(); - - // Store preferences and export - int n = 0; - ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory()); - for (int i = 0; i < selected.length; i++) { - ((SwingPreferences) Application.getPreferences()).setExportSelected(types[i], selected[i]); - if (selected[i]) - n++; - } - - - FlightDataType[] fieldTypes = new FlightDataType[n]; - Unit[] fieldUnits = new Unit[n]; - int pos = 0; - for (int i = 0; i < selected.length; i++) { - if (selected[i]) { - fieldTypes[pos] = types[i]; - fieldUnits[pos] = units[i]; - pos++; - } - } - - if (fieldSep.equals(SPACE)) { - fieldSep = " "; - } else if (fieldSep.equals(TAB)) { - fieldSep = "\t"; - } - - - SaveCSVWorker.export(file, simulation, branch, fieldTypes, fieldUnits, fieldSep, - commentChar, simulationComment, fieldComment, eventComment, - SwingUtilities.getWindowAncestor(this)); - } - - - private void updateSelectedCount() { - int total = selected.length; - int n = 0; - String str; - - for (int i = 0; i < selected.length; i++) { - if (selected[i]) - n++; - } - - if (n == 1) { - //// Exporting 1 variable out of - str = trans.get("SimExpPan.ExportingVar.desc1") + " " + total + "."; - } else { - //// Exporting - //// variables out of - str = trans.get("SimExpPan.ExportingVar.desc2") + " " + n + " " + - trans.get("SimExpPan.ExportingVar.desc3") + " " + total + "."; - } - - selectedCountLabel.setText(str); - } - - - - /** - * A table cell renderer that uses another renderer and sets the background and - * foreground of the returned component based on the selection of the variable. - */ - private class SelectionBackgroundCellRenderer implements TableCellRenderer { - - private final TableCellRenderer renderer; - - public SelectionBackgroundCellRenderer(TableCellRenderer renderer) { - this.renderer = renderer; - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - - Component component = renderer.getTableCellRendererComponent(table, - value, isSelected, hasFocus, row, column); - - if (selected[row]) { - component.setBackground(table.getSelectionBackground()); - component.setForeground(table.getSelectionForeground()); - } else { - component.setBackground(table.getBackground()); - component.setForeground(table.getForeground()); - } - - return component; - } - - } - - - /** - * The table model for the variable selection. - */ - private class SelectionTableModel extends AbstractTableModel { - private static final int SELECTED = 0; - private static final int NAME = 1; - private static final int UNIT = 2; - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public int getRowCount() { - return types.length; - } - - @Override - public String getColumnName(int column) { - switch (column) { - case SELECTED: - return ""; - case NAME: - //// Variable - return trans.get("SimExpPan.Col.Variable"); - case UNIT: - //// Unit - return trans.get("SimExpPan.Col.Unit"); - default: - throw new IndexOutOfBoundsException("column=" + column); - } - - } - - @Override - public Class getColumnClass(int column) { - switch (column) { - case SELECTED: - return Boolean.class; - case NAME: - return FlightDataType.class; - case UNIT: - return Unit.class; - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - @Override - public Object getValueAt(int row, int column) { - - switch (column) { - case SELECTED: - return selected[row]; - - case NAME: - return types[row]; - - case UNIT: - return units[row]; - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - - } - - @Override - public void setValueAt(Object value, int row, int column) { - - switch (column) { - case SELECTED: - selected[row] = (Boolean) value; - this.fireTableRowsUpdated(row, row); - updateSelectedCount(); - break; - - case NAME: - break; - - case UNIT: - units[row] = (Unit) value; - break; - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - - } - - @Override - public boolean isCellEditable(int row, int column) { - switch (column) { - case SELECTED: - return true; - - case NAME: - return false; - - case UNIT: - return types[row].getUnitGroup().getUnitCount() > 1; - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - public void selectAll() { - Arrays.fill(selected, true); - updateSelectedCount(); - this.fireTableDataChanged(); - } - - public void selectNone() { - Arrays.fill(selected, false); - updateSelectedCount(); - this.fireTableDataChanged(); - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/StageSelector.java b/core/src/net/sf/openrocket/gui/components/StageSelector.java deleted file mode 100644 index 94792791..00000000 --- a/core/src/net/sf/openrocket/gui/components/StageSelector.java +++ /dev/null @@ -1,111 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.event.ActionEvent; -import java.util.ArrayList; -import java.util.EventObject; -import java.util.List; - -import javax.swing.AbstractAction; -import javax.swing.JPanel; -import javax.swing.JToggleButton; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.StateChangeListener; - - -public class StageSelector extends JPanel implements StateChangeListener { - private static final Translator trans = Application.getTranslator(); - - private final Configuration configuration; - - private List buttons = new ArrayList(); - - public StageSelector(Configuration configuration) { - super(new MigLayout("gap 0!")); - this.configuration = configuration; - - JToggleButton button = new JToggleButton(new StageAction(0)); - this.add(button); - buttons.add(button); - - updateButtons(); - configuration.addChangeListener(this); - } - - private void updateButtons() { - int stages = configuration.getStageCount(); - if (buttons.size() == stages) - return; - - while (buttons.size() > stages) { - JToggleButton button = buttons.remove(buttons.size() - 1); - this.remove(button); - } - - while (buttons.size() < stages) { - JToggleButton button = new JToggleButton(new StageAction(buttons.size())); - this.add(button); - buttons.add(button); - } - - this.revalidate(); - } - - - - - @Override - public void stateChanged(EventObject e) { - updateButtons(); - } - - - private class StageAction extends AbstractAction implements StateChangeListener { - private final int stage; - - public StageAction(final int stage) { - this.stage = stage; - configuration.addChangeListener(this); - stateChanged(null); - } - - @Override - public Object getValue(String key) { - if (key.equals(NAME)) { - //// Stage - return trans.get("StageAction.Stage") + " " + (stage + 1); - } - return super.getValue(key); - } - - @Override - public void actionPerformed(ActionEvent e) { - configuration.setToStage(stage); - - // boolean state = (Boolean)getValue(SELECTED_KEY); - // if (state == true) { - // // Was disabled, now enabled - // configuration.setToStage(stage); - // } else { - // // Was enabled, check what to do - // if (configuration.isStageActive(stage + 1)) { - // configuration.setToStage(stage); - // } else { - // if (stage == 0) - // configuration.setAllStages(); - // else - // configuration.setToStage(stage-1); - // } - // } - // stateChanged(null); - } - - @Override - public void stateChanged(EventObject e) { - this.putValue(SELECTED_KEY, configuration.isStageActive(stage)); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/components/StarCheckBox.java b/core/src/net/sf/openrocket/gui/components/StarCheckBox.java deleted file mode 100644 index a7bdb6d5..00000000 --- a/core/src/net/sf/openrocket/gui/components/StarCheckBox.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Graphics; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; - -import net.sf.openrocket.gui.util.Icons; - -public class StarCheckBox extends JCheckBox { - - - - @Override - public void paint(Graphics g) { - JLabel l = new JLabel(Icons.FAVORITE); - l.paint(g); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/StyledLabel.java b/core/src/net/sf/openrocket/gui/components/StyledLabel.java deleted file mode 100644 index 70328411..00000000 --- a/core/src/net/sf/openrocket/gui/components/StyledLabel.java +++ /dev/null @@ -1,111 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Font; - -import javax.swing.JLabel; -import javax.swing.SwingConstants; - -/** - * A resizeable and styleable JLabel. The method {@link #resizeFont(float)} changes the - * current font size by the given (positive or negative) amount. The change is relative - * to the current font size. The method {@link #setFontStyle(Style)} sets the style - * (bold/italic) of the font. - *

- * A nice small text is achievable by new ResizeLabel("My text", -2); - * - * @author Sampo Niskanen - */ - -public class StyledLabel extends JLabel { - - public enum Style { - PLAIN(Font.PLAIN), - BOLD(Font.BOLD), - ITALIC(Font.ITALIC), - BOLD_ITALIC(Font.BOLD | Font.ITALIC); - - private int style; - Style(int fontStyle) { - this.style = fontStyle; - } - public int getFontStyle() { - return style; - } - } - - - - public StyledLabel() { - this("", SwingConstants.LEADING, 0f); - } - - public StyledLabel(String text) { - this(text, SwingConstants.LEADING, 0f); - } - - public StyledLabel(float size) { - this("", SwingConstants.LEADING, size); - } - - public StyledLabel(String text, float size) { - this(text, SwingConstants.LEADING, size); - } - - public StyledLabel(String text, int horizontalAlignment, float size) { - super(text, horizontalAlignment); - resizeFont(size); - checkPreferredSize(size, Style.PLAIN); - } - - - - public StyledLabel(Style style) { - this("", SwingConstants.LEADING, 0f, style); - } - - public StyledLabel(String text, Style style) { - this(text, SwingConstants.LEADING, 0f, style); - } - - public StyledLabel(float size, Style style) { - this("", SwingConstants.LEADING, size, style); - } - - public StyledLabel(String text, float size, Style style) { - this(text, SwingConstants.LEADING, size, style); - } - - public StyledLabel(String text, int horizontalAlignment, float size, Style style) { - super(text, horizontalAlignment); - resizeFont(size); - setFontStyle(style); - checkPreferredSize(size, style); - } - - - - - private void checkPreferredSize(float size, Style style) { - String str = this.getText(); - if (str.startsWith("") && str.indexOf(" - */ -public class URLLabel extends SelectableLabel { - private static final LogHelper log = Application.getLogger(); - - /** - * Create a label showing the url it will direct to. - * - * @param url the URL. - */ - public URLLabel(String url) { - this(url, url); - } - - /** - * Create a label with separate URL and label. - * - * @param url the URL clicking will open. - * @param label the label. - */ - public URLLabel(final String url, String label) { - super(); - - setText(label); - - if (Desktop.isDesktopSupported()) { - - // Blue, underlined font - Map map = new HashMap(); - map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); - this.setFont(this.getFont().deriveFont(map)); - this.setForeground(Color.BLUE); - - this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - - - this.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - Desktop d = Desktop.getDesktop(); - try { - d.browse(new URI(url)); - } catch (URISyntaxException e1) { - throw new BugException("Illegal URL: " + url, e1); - } catch (IOException e1) { - log.error("Unable to launch browser: " + e1.getMessage(), e1); - } - } - }); - - } - } -} diff --git a/core/src/net/sf/openrocket/gui/components/UnitCellEditor.java b/core/src/net/sf/openrocket/gui/components/UnitCellEditor.java deleted file mode 100644 index 2ff47abc..00000000 --- a/core/src/net/sf/openrocket/gui/components/UnitCellEditor.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.gui.components; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.AbstractCellEditor; -import javax.swing.JComboBox; -import javax.swing.JTable; -import javax.swing.table.TableCellEditor; - -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; - - -/** - * A cell editor that returns a combo box containing a selection of units. - * Using classes must implement the {@link #getUnitGroup(Unit, int, int)} method - * to return the appropriate unit group for the selection. - * - * @author Sampo Niskanen - */ -public abstract class UnitCellEditor extends AbstractCellEditor - implements TableCellEditor, ActionListener { - - private final JComboBox editor; - - public UnitCellEditor() { - editor = new JComboBox(); - editor.setEditable(false); - editor.addActionListener(this); - } - - - @Override - public Component getTableCellEditorComponent(JTable table, Object value, - boolean isSelected, int row, int column) { - - Unit unit = (Unit) value; - UnitGroup group = getUnitGroup(unit, row, column); - - editor.removeAllItems(); - for (Unit u : group.getUnits()) { - editor.addItem(u); - } - - editor.setSelectedItem(unit); - - return editor; - } - - - @Override - public Object getCellEditorValue() { - return editor.getSelectedItem(); - } - - - - @Override - public void actionPerformed(ActionEvent e) { - // End editing when a value has been selected - this.fireEditingStopped(); - } - - - /** - * Return the unit group corresponding to the specified cell. - * - * @param value the cell's value. - * @param row the cell's row. - * @param column the cell's column. - * @return the unit group of this cell. - */ - protected abstract UnitGroup getUnitGroup(Unit value, int row, int column); - -} diff --git a/core/src/net/sf/openrocket/gui/components/UnitSelector.java b/core/src/net/sf/openrocket/gui/components/UnitSelector.java deleted file mode 100644 index 1bdef68e..00000000 --- a/core/src/net/sf/openrocket/gui/components/UnitSelector.java +++ /dev/null @@ -1,339 +0,0 @@ -package net.sf.openrocket.gui.components; - - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.ItemSelectable; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.util.ArrayList; -import java.util.EventObject; -import java.util.List; - -import javax.swing.Action; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.border.Border; -import javax.swing.border.CompoundBorder; -import javax.swing.border.EmptyBorder; -import javax.swing.border.LineBorder; - -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.StateChangeListener; - - -/** - * A Swing component that allows one to choose a unit from a UnitGroup within - * a DoubleModel model. The current unit of the model is shown as a JLabel, and - * the unit can be changed by clicking on the label. - * - * @author Sampo Niskanen - */ - -public class UnitSelector extends StyledLabel implements StateChangeListener, MouseListener, - ItemSelectable { - - private DoubleModel model; - private final Action[] extraActions; - - private UnitGroup unitGroup; - private Unit currentUnit; - - private final boolean showValue; - - private final Border normalBorder; - private final Border withinBorder; - - - private final List itemListeners = new ArrayList(); - - - /** - * Common private constructor that sets the values and sets up the borders. - * Either model or group must be null. - * - * @param model - * @param showValue - * @param group - * @param actions - */ - private UnitSelector(DoubleModel model, boolean showValue, UnitGroup group, - Action[] actions) { - super(); - - this.model = model; - this.showValue = showValue; - - if (model != null) { - this.unitGroup = model.getUnitGroup(); - this.currentUnit = model.getCurrentUnit(); - } else if (group != null) { - this.unitGroup = group; - this.currentUnit = group.getDefaultUnit(); - } else { - this.unitGroup = UnitGroup.UNITS_NONE; - this.currentUnit = UnitGroup.UNITS_NONE.getDefaultUnit(); - } - - this.extraActions = actions; - - addMouseListener(this); - - // Define borders to use: - - normalBorder = new CompoundBorder( - new LineBorder(new Color(0f, 0f, 0f, 0.08f), 1), new EmptyBorder(1, 1, 1, - 1)); - withinBorder = new CompoundBorder(new LineBorder(new Color(0f, 0f, 0f, 0.6f)), - new EmptyBorder(1, 1, 1, 1)); - - // Add model listener if showing value - if (showValue) - this.model.addChangeListener(this); - - setBorder(normalBorder); - updateText(); - } - - - - public UnitSelector(DoubleModel model, Action... actions) { - this(model, false, actions); - } - - public UnitSelector(DoubleModel model, boolean showValue, Action... actions) { - this(model, showValue, null, actions); - } - - - public UnitSelector(UnitGroup group, Action... actions) { - this(null, false, group, actions); - } - - - - - /** - * Return the DoubleModel that is backing this selector up, or null. - * Either this method or {@link #getUnitGroup()} always returns null. - * - * @return the DoubleModel being used, or null. - */ - public DoubleModel getModel() { - return model; - } - - - /** - * Set the current double model. - * - * @param model the model to set, null is NOT allowed. - */ - public void setModel(DoubleModel model) { - if (this.model != null && showValue) { - this.model.removeChangeListener(this); - } - this.model = model; - this.unitGroup = model.getUnitGroup(); - this.currentUnit = model.getCurrentUnit(); - if (showValue) { - this.model.addChangeListener(this); - } - updateText(); - } - - - - /** - * Return the unit group that is being shown, or null. Either this method - * or {@link #getModel()} always returns null. - * - * @return the UnitGroup being used, or null. - */ - public UnitGroup getUnitGroup() { - return unitGroup; - } - - - public void setUnitGroup(UnitGroup group) { - if (model != null) { - throw new IllegalStateException( - "UnitGroup cannot be set when backed up with model."); - } - - if (this.unitGroup == group) - return; - - this.unitGroup = group; - this.currentUnit = group.getDefaultUnit(); - updateText(); - } - - - /** - * Return the currently selected unit. Works both when backup up with a DoubleModel - * and UnitGroup. - * - * @return the currently selected unit. - */ - public Unit getSelectedUnit() { - return currentUnit; - } - - - /** - * Set the currently selected unit. Sets it to the DoubleModel if it is backed up - * by it. - * - * @param unit the unit to select. - */ - public void setSelectedUnit(Unit unit) { - if (!unitGroup.contains(unit)) { - throw new IllegalArgumentException("unit " + unit - + " not contained in group " + unitGroup); - } - - this.currentUnit = unit; - if (model != null) { - model.setCurrentUnit(unit); - } - updateText(); - fireItemEvent(); - } - - - - /** - * Updates the text of the label - */ - private void updateText() { - if (model != null) { - - Unit unit = model.getCurrentUnit(); - if (showValue) { - setText(unit.toStringUnit(model.getValue())); - } else { - setText(unit.getUnit()); - } - - } else if (unitGroup != null) { - - setText(currentUnit.getUnit()); - - } else { - throw new IllegalStateException("Both model and unitGroup are null."); - } - } - - - /** - * Update the component when the DoubleModel changes. - */ - @Override - public void stateChanged(EventObject e) { - updateText(); - } - - - - //////// ItemListener handling //////// - - public void addItemListener(ItemListener listener) { - itemListeners.add(listener); - } - - public void removeItemListener(ItemListener listener) { - itemListeners.remove(listener); - } - - protected void fireItemEvent() { - ItemEvent event = null; - ItemListener[] listeners = itemListeners.toArray(new ItemListener[0]); - for (ItemListener l: listeners) { - if (event == null) { - event = new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, getSelectedUnit(), - ItemEvent.SELECTED); - } - l.itemStateChanged(event); - } - } - - - - //////// Popup //////// - - private void popup() { - JPopupMenu popup = new JPopupMenu(); - - for (int i = 0; i < unitGroup.getUnitCount(); i++) { - Unit unit = unitGroup.getUnit(i); - JMenuItem item = new JMenuItem(unit.getUnit()); - item.addActionListener(new UnitSelectorItem(unit)); - popup.add(item); - } - - for (int i = 0; i < extraActions.length; i++) { - if (extraActions[i] == null && i < extraActions.length - 1) { - popup.addSeparator(); - } else { - popup.add(new JMenuItem(extraActions[i])); - } - } - - Dimension d = getSize(); - popup.show(this, 0, d.height); - } - - - /** - * ActionListener class that sets the currently selected unit. - */ - private class UnitSelectorItem implements ActionListener { - private final Unit unit; - - public UnitSelectorItem(Unit u) { - unit = u; - } - - public void actionPerformed(ActionEvent e) { - setSelectedUnit(unit); - } - } - - - @Override - public Object[] getSelectedObjects() { - return new Object[]{ getSelectedUnit() }; - } - - - - //////// Mouse handling //////// - - public void mouseClicked(MouseEvent e) { - if (unitGroup.getUnitCount() > 1) - popup(); - } - - public void mouseEntered(MouseEvent e) { - if (unitGroup.getUnitCount() > 1) - setBorder(withinBorder); - } - - public void mouseExited(MouseEvent e) { - setBorder(normalBorder); - } - - public void mousePressed(MouseEvent e) { - } // Ignore - - public void mouseReleased(MouseEvent e) { - } // Ignore - -} diff --git a/core/src/net/sf/openrocket/gui/components/compass/CompassPointer.java b/core/src/net/sf/openrocket/gui/components/compass/CompassPointer.java deleted file mode 100644 index 37fdad42..00000000 --- a/core/src/net/sf/openrocket/gui/components/compass/CompassPointer.java +++ /dev/null @@ -1,218 +0,0 @@ -package net.sf.openrocket.gui.components.compass; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; - -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.sf.openrocket.gui.Resettable; -import net.sf.openrocket.gui.adaptors.DoubleModel; - -/** - * A component that draws a pointer onto a compass rose. - * - * @author Sampo Niskanen - */ -public class CompassPointer extends CompassRose implements Resettable { - - private static final Color PRIMARY_POINTER_COLOR = new Color(1.0f, 0.2f, 0.2f); - private static final Color SECONDARY_POINTER_COLOR = new Color(0.2f, 0.2f, 0.2f, 0.2f); - - private final DoubleModel model; - private final ChangeListener listener; - - protected int width = -1; - protected int mid = -1; - - private DoubleModel secondaryModel; - - private float pointerLength = 0.95f; - private float pointerWidth = 0.1f; - private float pointerArrowWidth = 0.2f; - private boolean pointerArrow = true; - - - - public CompassPointer(DoubleModel model) { - super(); - this.model = model; - listener = new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - CompassPointer.this.repaint(); - } - }; - model.addChangeListener(listener); - } - - - @Override - public void paintComponent(Graphics g) { - super.paintComponent(g); - - Graphics2D g2 = (Graphics2D) g; - - - Dimension dimension = this.getSize(); - - width = Math.min(dimension.width, dimension.height); - mid = width / 2; - width = (int) (getScaler() * width); - - - g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - - - if (secondaryModel != null) { - drawArrow(secondaryModel.getValue(), SECONDARY_POINTER_COLOR, g2); - } - drawArrow(model.getValue(), PRIMARY_POINTER_COLOR, g2); - - - } - - - private void drawArrow(double angle, Color color, Graphics2D g2) { - - int pLength = (int) (width * pointerLength / 2); - int pWidth = (int) (width * pointerWidth / 2); - int pArrowWidth = (int) (width * pointerArrowWidth / 2); - - int[] x = new int[8]; - int[] y = new int[8]; - - g2.setColor(color); - - - double sin = Math.sin(angle); - double cos = Math.cos(angle); - - int n = 0; - - // Top part - x[n] = 0; - y[n] = -pLength; - n++; - if (pointerArrow) { - x[n] = -pArrowWidth; - y[n] = -pLength + 2 * pArrowWidth; - n++; - x[n] = -pWidth; - y[n] = -pLength + 2 * pArrowWidth; - n++; - } - - // Bottom part - x[n] = -pWidth; - y[n] = pLength; - n++; - x[n] = 0; - y[n] = pLength - pWidth; - n++; - x[n] = pWidth; - y[n] = pLength; - n++; - - // Top part - if (pointerArrow) { - x[n] = pWidth; - y[n] = -pLength + 2 * pArrowWidth; - n++; - x[n] = pArrowWidth; - y[n] = -pLength + 2 * pArrowWidth; - n++; - } - - // Rotate and shift - for (int i = 0; i < n; i++) { - double x2, y2; - x2 = cos * x[i] - sin * y[i]; - y2 = sin * x[i] + cos * y[i]; - - x[i] = (int) (x2 + mid); - y[i] = (int) (y2 + mid); - } - - g2.fillPolygon(x, y, n); - - g2.setColor(color.darker()); - g2.drawPolygon(x, y, n); - - } - - - public boolean isPointerArrow() { - return pointerArrow; - } - - - public void setPointerArrow(boolean useArrow) { - this.pointerArrow = useArrow; - repaint(); - } - - - public float getPointerLength() { - return pointerLength; - } - - - public void setPointerLength(float pointerLength) { - this.pointerLength = pointerLength; - repaint(); - } - - - public float getPointerWidth() { - return pointerWidth; - } - - - public void setPointerWidth(float pointerWidth) { - this.pointerWidth = pointerWidth; - repaint(); - } - - - public float getPointerArrowWidth() { - return pointerArrowWidth; - } - - - public void setPointerArrowWidth(float pointerArrowWidth) { - this.pointerArrowWidth = pointerArrowWidth; - repaint(); - } - - - - public DoubleModel getSecondaryModel() { - return secondaryModel; - } - - - public void setSecondaryModel(DoubleModel secondaryModel) { - if (this.secondaryModel != null) { - this.secondaryModel.removeChangeListener(listener); - } - this.secondaryModel = secondaryModel; - if (this.secondaryModel != null) { - this.secondaryModel.addChangeListener(listener); - } - } - - - @Override - public void resetModel() { - model.removeChangeListener(listener); - setSecondaryModel(null); - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/components/compass/CompassRose.java b/core/src/net/sf/openrocket/gui/components/compass/CompassRose.java deleted file mode 100644 index 49f1d059..00000000 --- a/core/src/net/sf/openrocket/gui/components/compass/CompassRose.java +++ /dev/null @@ -1,221 +0,0 @@ -package net.sf.openrocket.gui.components.compass; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.font.GlyphVector; -import java.awt.geom.Rectangle2D; - -import javax.swing.JComponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; - -/** - * A component that draws a compass rose. This class has no other functionality, but superclasses - * may add functionality to it. - * - * @author Sampo Niskanen - */ -public class CompassRose extends JComponent { - private static final Translator trans = Application.getTranslator(); - - - private static final Color MAIN_COLOR = new Color(0.4f, 0.4f, 1.0f); - private static final float MAIN_LENGTH = 0.95f; - private static final float MAIN_WIDTH = 0.15f; - - private static final int CIRCLE_BORDER = 2; - private static final Color CIRCLE_HIGHLIGHT = new Color(1.0f, 1.0f, 1.0f, 0.7f); - private static final Color CIRCLE_SHADE = new Color(0.0f, 0.0f, 0.0f, 0.2f); - - private static final Color MARKER_COLOR = Color.BLACK; - - - private double scaler; - - private double markerRadius; - private Font markerFont; - - - /** - * Construct a compass rose with the default settings. - */ - public CompassRose() { - this(0.8, 1.1, Font.decode("Serif-PLAIN-16")); - } - - - /** - * Construct a compass rose with the specified settings. - * - * @param scaler The scaler of the rose. The bordering circle will we this portion of the component dimensions. - * @param markerRadius The radius for the marker positions (N/E/S/W), or NaN for no markers. A value greater than one - * will position the markers outside of the bordering circle. - * @param markerFont The font used for the markers. - */ - public CompassRose(double scaler, double markerRadius, Font markerFont) { - this.scaler = scaler; - this.markerRadius = markerRadius; - this.markerFont = markerFont; - } - - - - @Override - public void paintComponent(Graphics g) { - - Graphics2D g2 = (Graphics2D) g; - - int[] x = new int[3]; - int[] y = new int[3]; - Dimension dimension = this.getSize(); - - int width = Math.min(dimension.width, dimension.height); - int mid = width / 2; - width = (int) (scaler * width); - - int mainLength = (int) (width * MAIN_LENGTH / 2); - int mainWidth = (int) (width * MAIN_WIDTH / 2); - - - g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - - g2.setColor(MAIN_COLOR); - - // North - x[0] = mid; - y[0] = mid; - x[1] = mid; - y[1] = mid - mainLength; - x[2] = mid - mainWidth; - y[2] = mid - mainWidth; - g2.fillPolygon(x, y, 3); - - x[2] = mid + mainWidth; - g2.drawPolygon(x, y, 3); - - // East - x[0] = mid; - y[0] = mid; - x[1] = mid + mainLength; - y[1] = mid; - x[2] = mid + mainWidth; - y[2] = mid - mainWidth; - g2.fillPolygon(x, y, 3); - - y[2] = mid + mainWidth; - g2.drawPolygon(x, y, 3); - - // South - x[0] = mid; - y[0] = mid; - x[1] = mid; - y[1] = mid + mainLength; - x[2] = mid + mainWidth; - y[2] = mid + mainWidth; - g2.fillPolygon(x, y, 3); - - x[2] = mid - mainWidth; - g2.drawPolygon(x, y, 3); - - // West - x[0] = mid; - y[0] = mid; - x[1] = mid - mainLength; - y[1] = mid; - x[2] = mid - mainWidth; - y[2] = mid + mainWidth; - g2.fillPolygon(x, y, 3); - - y[2] = mid - mainWidth; - g2.drawPolygon(x, y, 3); - - - // Border circle - g2.setColor(CIRCLE_SHADE); - g2.drawArc(mid - width / 2 + CIRCLE_BORDER, mid - width / 2 + CIRCLE_BORDER, - width - 2 * CIRCLE_BORDER, width - 2 * CIRCLE_BORDER, 45, 180); - g2.setColor(CIRCLE_HIGHLIGHT); - g2.drawArc(mid - width / 2 + CIRCLE_BORDER, mid - width / 2 + CIRCLE_BORDER, - width - 2 * CIRCLE_BORDER, width - 2 * CIRCLE_BORDER, 180 + 45, 180); - - - // Draw direction markers - if (!Double.isNaN(markerRadius) && markerFont != null) { - - int pos = (int) (width * markerRadius / 2); - - g2.setColor(MARKER_COLOR); - drawMarker(g2, mid, mid - pos, trans.get("lbl.north")); - drawMarker(g2, mid + pos, mid, trans.get("lbl.east")); - drawMarker(g2, mid, mid + pos, trans.get("lbl.south")); - drawMarker(g2, mid - pos, mid, trans.get("lbl.west")); - - } - - } - - - - private void drawMarker(Graphics2D g2, float x, float y, String str) { - GlyphVector gv = markerFont.createGlyphVector(g2.getFontRenderContext(), str); - Rectangle2D rect = gv.getVisualBounds(); - - x -= rect.getWidth() / 2; - y += rect.getHeight() / 2; - - g2.drawGlyphVector(gv, x, y); - - } - - - - - - public double getScaler() { - return scaler; - } - - - public void setScaler(double scaler) { - this.scaler = scaler; - repaint(); - } - - - public double getMarkerRadius() { - return markerRadius; - } - - - public void setMarkerRadius(double markerRadius) { - this.markerRadius = markerRadius; - repaint(); - } - - - public Font getMarkerFont() { - return markerFont; - } - - - public void setMarkerFont(Font markerFont) { - this.markerFont = markerFont; - repaint(); - } - - @Override - public Dimension getPreferredSize() { - Dimension dim = super.getPreferredSize(); - int min = Math.min(dim.width, dim.height); - dim.setSize(min, min); - return dim; - } - - -} diff --git a/core/src/net/sf/openrocket/gui/components/compass/CompassSelectionButton.java b/core/src/net/sf/openrocket/gui/components/compass/CompassSelectionButton.java deleted file mode 100644 index c8b0fee2..00000000 --- a/core/src/net/sf/openrocket/gui/components/compass/CompassSelectionButton.java +++ /dev/null @@ -1,190 +0,0 @@ -package net.sf.openrocket.gui.components.compass; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JSpinner; -import javax.swing.border.BevelBorder; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.Resettable; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.FlatButton; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.MathUtil; - - -/** - * A button that displays a current compass direction and opens a popup to edit - * the value when clicked. - * - * @author Sampo Niskanen - */ -public class CompassSelectionButton extends FlatButton implements Resettable { - - private static final Translator trans = Application.getTranslator(); - - private static final int POPUP_COMPASS_SIZE = 200; - private static final double SECTOR = 45; - - private static int minWidth = -1; - - - private final DoubleModel model; - private final ChangeListener listener; - - private JPopupMenu popup; - - - public CompassSelectionButton(final DoubleModel model) { - this.model = model; - - JPanel panel = new JPanel(new MigLayout("fill, ins 0")); - panel.setOpaque(false); - - CompassPointer pointer = new CompassPointer(model); - pointer.setPreferredSize(new Dimension(24, 24)); - pointer.setMarkerFont(null); - pointer.setPointerArrow(false); - pointer.setPointerWidth(0.45f); - pointer.setScaler(1.0f); - panel.add(pointer, "gapright rel"); - - - final JLabel label = new JLabel(); - label.setText(getLabel(model.getValue())); - panel.add(label); - - listener = new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - label.setText(getLabel(model.getValue())); - } - }; - model.addChangeListener(listener); - - - if (minWidth < 0) { - calculateMinWidth(); - label.setMinimumSize(new Dimension(minWidth, 0)); - } - - - this.add(panel); - - this.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - openPopup(); - } - }); - } - - - - - private String getLabel(double value) { - String str; - - value = MathUtil.reduce360(value); - value = Math.toDegrees(value); - str = "" + Math.round(value) + Chars.DEGREE + " ("; - - if (value <= 0.5 * SECTOR || value >= 7.5 * SECTOR) { - str += trans.get("lbl.N"); - } else if (value <= 1.5 * SECTOR) { - str += trans.get("lbl.NE"); - } else if (value <= 2.5 * SECTOR) { - str += trans.get("lbl.E"); - } else if (value <= 3.5 * SECTOR) { - str += trans.get("lbl.SE"); - } else if (value <= 4.5 * SECTOR) { - str += trans.get("lbl.S"); - } else if (value <= 5.5 * SECTOR) { - str += trans.get("lbl.SW"); - } else if (value <= 6.5 * SECTOR) { - str += trans.get("lbl.W"); - } else { - str += trans.get("lbl.NW"); - } - - str += ")"; - return str; - } - - - private void openPopup() { - if (popup == null) { - popup = new JPopupMenu(); - - - final JPanel panel = new JPanel(new MigLayout("fill")); - - final CompassPointer rose = new CompassSelector(model); - rose.setPreferredSize(new Dimension(POPUP_COMPASS_SIZE, POPUP_COMPASS_SIZE)); - panel.add(rose, "spany, gapright unrel"); - - panel.add(new JPanel(), "growy, wrap"); - - JSpinner spin = new JSpinner(model.getSpinnerModel()); - panel.add(spin, "wmin 50lp, growx, gapright 0, aligny bottom"); - - panel.add(new JLabel("" + Chars.DEGREE), "wrap para"); - - JButton close = new JButton("OK"); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - popup.setVisible(false); - } - }); - panel.add(close, "span 2, growx, wrap"); - - panel.add(new JPanel(), "growy, wrap"); - - popup.add(panel); - popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); - } - - popup.pack(); - - Dimension popupSize = popup.getPreferredSize(); - Dimension buttonSize = this.getSize(); - - int posX = buttonSize.width / 2 - popupSize.width / 2; - int posY = buttonSize.height / 2 - popupSize.height / 2; - popup.show(this, posX, posY); - } - - private void calculateMinWidth() { - JLabel label = new JLabel(); - int max = 0; - for (double deg = 0; deg < 360; deg += 0.99999999999) { - label.setText(getLabel(Math.toRadians(deg))); - int w = label.getPreferredSize().width; - if (w > max) { - max = w; - } - } - minWidth = max + 1; - } - - - - - @Override - public void resetModel() { - model.removeChangeListener(listener); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/compass/CompassSelector.java b/core/src/net/sf/openrocket/gui/components/compass/CompassSelector.java deleted file mode 100644 index deed9cf7..00000000 --- a/core/src/net/sf/openrocket/gui/components/compass/CompassSelector.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.sf.openrocket.gui.components.compass; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.util.MathUtil; - -/** - * Component that allows selecting a compass direction on a CompassSelector. - * - * @author Sampo Niskanen - */ -public class CompassSelector extends CompassPointer { - - private final DoubleModel model; - - public CompassSelector(DoubleModel model) { - super(model); - this.model = model; - - MouseAdapter mouse = new MouseAdapter() { - private boolean dragging = false; - - @Override - public void mousePressed(MouseEvent e) { - if (!isWithinCircle(e)) - return; - if (e.getButton() != MouseEvent.BUTTON1) - return; - dragging = true; - clicked(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() != MouseEvent.BUTTON1) - return; - dragging = false; - } - - - @Override - public void mouseDragged(MouseEvent e) { - if (!dragging) - return; - clicked(e); - } - }; - this.addMouseListener(mouse); - this.addMouseMotionListener(mouse); - - } - - private boolean isWithinCircle(MouseEvent e) { - if (mid < 0 || width < 0) { - return false; - } - - int x = e.getX() - mid; - int y = e.getY() - mid; - - double distance = Math.hypot(x, y); - return distance < width / 2; - } - - private void clicked(MouseEvent e) { - - if (mid < 0 || width < 0) { - return; - } - - int x = e.getX() - mid; - int y = e.getY() - mid; - - double distance = Math.hypot(x, y); - - double theta = Math.atan2(y, x); - theta = MathUtil.reduce360(theta + Math.PI / 2); - - // Round the value appropriately - theta = Math.toDegrees(theta); - - if (distance > 50) { - theta = Math.round(theta); - } else if (distance > 10) { - theta = 5 * Math.round(theta / 5); - } else { - // Do nothing if too close to center - return; - } - theta = Math.toRadians(theta); - - model.setValue(theta); - } - -} diff --git a/core/src/net/sf/openrocket/gui/components/compass/Tester.java b/core/src/net/sf/openrocket/gui/components/compass/Tester.java deleted file mode 100644 index 86a82a49..00000000 --- a/core/src/net/sf/openrocket/gui/components/compass/Tester.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.sf.openrocket.gui.components.compass; - -import java.awt.Dimension; -import java.lang.reflect.InvocationTargetException; - -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SwingUtilities; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class Tester { - - - public static void main(String[] args) throws InterruptedException, InvocationTargetException { - - Application.setBaseTranslator(new ResourceBundleTranslator("l10n.messages")); - - GUIUtil.setBestLAF(); - - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - JFrame frame = new JFrame(); - - JPanel panel = new JPanel(new MigLayout("fill")); - DoubleModel model = new DoubleModel(Math.toRadians(45), UnitGroup.UNITS_ANGLE); - DoubleModel second = new DoubleModel(Math.toRadians(30), UnitGroup.UNITS_ANGLE); - - - CompassPointer rose = new CompassSelector(model); - rose.setPreferredSize(new Dimension(300, 300)); - rose.setSecondaryModel(second); - panel.add(rose); - - rose = new CompassPointer(model); - rose.setPreferredSize(new Dimension(24, 24)); - panel.add(rose); - rose.setMarkerFont(null); - rose.setPointerArrow(false); - rose.setPointerWidth(0.45f); - rose.setScaler(1.0f); - - JSpinner spin = new JSpinner(model.getSpinnerModel()); - spin.setPreferredSize(new Dimension(50, 20)); - panel.add(spin, "wrap para"); - - - CompassSelectionButton button = new CompassSelectionButton(model); - panel.add(button); - - - frame.add(panel); - frame.pack(); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.setVisible(true); - } - }); - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/BodyTubeConfig.java b/core/src/net/sf/openrocket/gui/configdialog/BodyTubeConfig.java deleted file mode 100644 index b6ff3bdd..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/BodyTubeConfig.java +++ /dev/null @@ -1,128 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.ComponentPresetDatabase; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.BooleanModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.PresetModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class BodyTubeConfig extends RocketComponentConfig { - - private MotorConfig motorConfigPane = null; - private DoubleModel maxLength; - private static final Translator trans = Application.getTranslator(); - - public BodyTubeConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - - - //// Body tube length - panel.add(new JLabel(trans.get("BodyTubecfg.lbl.Bodytubelength"))); - - maxLength = new DoubleModel(2.0); - DoubleModel length = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(length.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(length), "growx"); - panel.add(new BasicSlider(length.getSliderModel(0, 0.5, maxLength)), "w 100lp, wrap"); - - - //// Body tube diameter - panel.add(new JLabel(trans.get("BodyTubecfg.lbl.Outerdiameter"))); - - DoubleModel od = new DoubleModel(component, "OuterRadius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap 0px"); - - JCheckBox check = new JCheckBox(od.getAutomaticAction()); - //// Automatic - check.setText(trans.get("BodyTubecfg.checkbox.Automatic")); - panel.add(check, "skip, span 2, wrap"); - - - //// Inner diameter - panel.add(new JLabel(trans.get("BodyTubecfg.lbl.Innerdiameter"))); - - // Diameter = 2*Radius - DoubleModel m = new DoubleModel(component, "InnerRadius", 2, UnitGroup.UNITS_LENGTH, 0); - - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(new DoubleModel(0), od)), "w 100lp, wrap"); - - - //// Wall thickness - panel.add(new JLabel(trans.get("BodyTubecfg.lbl.Wallthickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap 0px"); - - //// Filled - check = new JCheckBox(new BooleanModel(component, "Filled")); - check.setText(trans.get("BodyTubecfg.checkbox.Filled")); - panel.add(check, "skip, span 2, wrap"); - - - //// Material - panel.add(materialPanel(new JPanel(new MigLayout()), Material.Type.BULK), - "cell 4 0, gapleft paragraph, aligny 0%, spany"); - - //// General and General properties - tabbedPane.insertTab(trans.get("BodyTubecfg.tab.General"), null, panel, - trans.get("BodyTubecfg.tab.Generalproperties"), 0); - motorConfigPane = new MotorConfig((BodyTube) c); - //// Motor and Motor mount configuration - tabbedPane.insertTab(trans.get("BodyTubecfg.tab.Motor"), null, motorConfigPane, - trans.get("BodyTubecfg.tab.Motormountconf"), 1); - tabbedPane.setSelectedIndex(0); - - - } - - @Override - public void updateFields() { - super.updateFields(); - if (motorConfigPane != null) - motorConfigPane.updateFields(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/BulkheadConfig.java b/core/src/net/sf/openrocket/gui/configdialog/BulkheadConfig.java deleted file mode 100644 index 135ec94e..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/BulkheadConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JPanel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - - - -public class BulkheadConfig extends RingComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public BulkheadConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel tab; - - tab = generalTab(trans.get("BulkheadCfg.tab.Diameter"), null, null, - trans.get("BulkheadCfg.tab.Thickness")); - //// General and General properties - tabbedPane.insertTab(trans.get("BulkheadCfg.tab.General"), null, tab, - trans.get("BulkheadCfg.tab.Generalproperties"), 0); - tabbedPane.setSelectedIndex(0); - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/configdialog/CenteringRingConfig.java b/core/src/net/sf/openrocket/gui/configdialog/CenteringRingConfig.java deleted file mode 100644 index dfe6a352..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/CenteringRingConfig.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JPanel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - - - -public class CenteringRingConfig extends RingComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public CenteringRingConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel tab; - - //// Outer diameter: and Inner diameter: and Thickness: - tab = generalTab(trans.get("CenteringRingCfg.tab.Outerdiam"), - trans.get("CenteringRingCfg.tab.Innerdiam"), null, - trans.get("CenteringRingCfg.tab.Thickness")); - //// General and General properties - tabbedPane.insertTab(trans.get("CenteringRingCfg.tab.General"), null, tab, - trans.get("CenteringRingCfg.tab.Generalproperties"), 0); - tabbedPane.setSelectedIndex(0); - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/configdialog/ComponentConfigDialog.java b/core/src/net/sf/openrocket/gui/configdialog/ComponentConfigDialog.java deleted file mode 100644 index a669b2dc..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/ComponentConfigDialog.java +++ /dev/null @@ -1,219 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.Window; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import javax.swing.JDialog; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Reflection; - -/** - * A dialog that contains the configuration elements of one component. - * The contents of the dialog are instantiated from CONFIGDIALOGPACKAGE according - * to the current component. - * - * @author Sampo Niskanen - */ - -public class ComponentConfigDialog extends JDialog implements ComponentChangeListener { - private static final long serialVersionUID = 1L; - private static final String CONFIGDIALOGPACKAGE = "net.sf.openrocket.gui.configdialog"; - private static final String CONFIGDIALOGPOSTFIX = "Config"; - - - private static ComponentConfigDialog dialog = null; - - - private OpenRocketDocument document = null; - private RocketComponent component = null; - private RocketComponentConfig configurator = null; - - private final Window parent; - private static final Translator trans = Application.getTranslator(); - - private ComponentConfigDialog(Window parent, OpenRocketDocument document, - RocketComponent component) { - super(parent); - this.parent = parent; - - setComponent(document, component); - - GUIUtil.setDisposableDialogOptions(this, null); - GUIUtil.rememberWindowPosition(this); - } - - - /** - * Set the component being configured. The listening connections of the old configurator - * will be removed and the new ones created. - * - * @param component Component to configure. - */ - private void setComponent(OpenRocketDocument document, RocketComponent component) { - if (this.document != null) { - this.document.getRocket().removeComponentChangeListener(this); - } - - if (configurator != null) { - // Remove listeners by setting all applicable models to null - GUIUtil.setNullModels(configurator); // null-safe - } - - this.document = document; - this.component = component; - this.document.getRocket().addComponentChangeListener(this); - - configurator = getDialogContents(); - this.setContentPane(configurator); - configurator.updateFields(); - - //// configuration - setTitle(trans.get("ComponentCfgDlg.configuration1") + " " + component.getComponentName() + " " + trans.get("ComponentCfgDlg.configuration")); - - this.pack(); - } - - /** - * Return the configurator panel of the current component. - */ - private RocketComponentConfig getDialogContents() { - Constructor c = - findDialogContentsConstructor(component); - if (c != null) { - try { - return c.newInstance(document, component); - } catch (InstantiationException e) { - throw new BugException("BUG in constructor reflection", e); - } catch (IllegalAccessException e) { - throw new BugException("BUG in constructor reflection", e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - // Should never be reached, since RocketComponentConfig should catch all - // components without their own configurator. - throw new BugException("Unable to find any configurator for " + component); - } - - - private void closeDialog() { - this.setVisible(false); - this.dispose(); - this.configurator.invalidateModels(); - } - - - @Override - public void componentChanged(ComponentChangeEvent e) { - if (e.isTreeChange() || e.isUndoChange()) { - - // Hide dialog in case of tree or undo change - dialog.closeDialog(); - - } else { - /* - * TODO: HIGH: The line below has caused a NullPointerException (without null check) - * How is this possible? The null check was added to avoid this, but the - * root cause should be analyzed. - * [Openrocket-bugs] 2009-12-12 19:23:22 Automatic bug report for OpenRocket 0.9.5 - */ - if (configurator != null) - configurator.updateFields(); - } - } - - - /** - * Finds the Constructor of the given component's config dialog panel in - * CONFIGDIALOGPACKAGE. - */ - @SuppressWarnings("unchecked") - private static Constructor findDialogContentsConstructor(RocketComponent component) { - Class currentclass; - String currentclassname; - String configclassname; - - Class configclass; - Constructor c; - - currentclass = component.getClass(); - while ((currentclass != null) && (currentclass != Object.class)) { - currentclassname = currentclass.getCanonicalName(); - int index = currentclassname.lastIndexOf('.'); - if (index >= 0) - currentclassname = currentclassname.substring(index + 1); - configclassname = CONFIGDIALOGPACKAGE + "." + currentclassname + - CONFIGDIALOGPOSTFIX; - - try { - configclass = Class.forName(configclassname); - c = (Constructor) - configclass.getConstructor(OpenRocketDocument.class, RocketComponent.class); - return c; - } catch (Exception ignore) { - } - - currentclass = currentclass.getSuperclass(); - } - return null; - } - - - - - ////////// Static dialog ///////// - - /** - * A singleton configuration dialog. Will create and show a new dialog if one has not - * previously been used, or update the dialog and show it if a previous one exists. - * - * @param document the document to configure. - * @param component the component to configure. - */ - public static void showDialog(Window parent, OpenRocketDocument document, - RocketComponent component) { - if (dialog != null) - dialog.dispose(); - - dialog = new ComponentConfigDialog(parent, document, component); - dialog.setVisible(true); - - ////Modify - document.addUndoPosition(trans.get("ComponentCfgDlg.Modify") + " " + component.getComponentName()); - } - - - /* package */ - static void showDialog(RocketComponent component) { - showDialog(dialog.parent, dialog.document, component); - } - - /** - * Hides the configuration dialog. May be used even if not currently visible. - */ - public static void hideDialog() { - if (dialog != null) { - dialog.closeDialog(); - } - } - - - /** - * Returns whether the singleton configuration dialog is currently visible or not. - */ - public static boolean isDialogVisible() { - return (dialog != null) && (dialog.isVisible()); - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/EllipticalFinSetConfig.java b/core/src/net/sf/openrocket/gui/configdialog/EllipticalFinSetConfig.java deleted file mode 100644 index 7f985725..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/EllipticalFinSetConfig.java +++ /dev/null @@ -1,189 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JSpinner; -import javax.swing.SwingConstants; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.IntegerModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class EllipticalFinSetConfig extends FinSetConfig { - private static final Translator trans = Application.getTranslator(); - - public EllipticalFinSetConfig(OpenRocketDocument d, final RocketComponent component) { - super(d, component); - - DoubleModel m; - JSpinner spin; - JComboBox combo; - - JPanel mainPanel = new JPanel(new MigLayout()); - - - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - //// Number of fins - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Nbroffins"))); - - IntegerModel im = new IntegerModel(component, "FinCount", 1, 8); - - spin = new JSpinner(im.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx, wrap"); - - - //// Base rotation - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Rotation"))); - - m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - //// Fin cant - JLabel label = new JLabel(trans.get("EllipticalFinSetCfg.Fincant")); - //// "The angle that the fins are canted with respect to the rocket - label.setToolTipText(trans.get("EllipticalFinSetCfg.ttip.Fincant")); - panel.add(label); - - m = new DoubleModel(component, "CantAngle", UnitGroup.UNITS_ANGLE, - -FinSet.MAX_CANT, FinSet.MAX_CANT); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-FinSet.MAX_CANT, FinSet.MAX_CANT)), - "w 100lp, wrap"); - - - - //// Root chord - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Rootchord"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.2)), "w 100lp, wrap"); - - - //// Height - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Height"))); - - m = new DoubleModel(component, "Height", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.2)), "w 100lp, wrap"); - - - //// Position - //// Position relative to: - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Positionrelativeto"))); - - combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx, growx, wrap"); - - //// plus - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap"); - - - - //// Right portion - mainPanel.add(panel, "aligny 20%"); - - mainPanel.add(new JSeparator(SwingConstants.VERTICAL), "growy"); - - - - panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - - //// Cross section - //// Fin cross section: - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.FincrossSection")), "span, split"); - combo = new JComboBox( - new EnumModel(component, "CrossSection")); - panel.add(combo, "growx, wrap unrel"); - - - //// Thickness: - panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Thickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap 30lp"); - - - - //// Material - materialPanel(panel, Material.Type.BULK); - - - - - - mainPanel.add(panel, "aligny 20%"); - - addFinSetButtons(); - - //// General and General properties - tabbedPane.insertTab(trans.get("EllipticalFinSetCfg.General"), null, mainPanel, - trans.get("EllipticalFinSetCfg.Generalproperties"), 0); - tabbedPane.setSelectedIndex(0); - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/FinSetConfig.java b/core/src/net/sf/openrocket/gui/configdialog/FinSetConfig.java deleted file mode 100644 index 67eb4074..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/FinSetConfig.java +++ /dev/null @@ -1,468 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.Coaxial; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - - -public abstract class FinSetConfig extends RocketComponentConfig { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private JButton split = null; - - public FinSetConfig(OpenRocketDocument d, RocketComponent component) { - super(d, component); - - //// Fin tabs and Through-the-wall fin tabs - tabbedPane.insertTab(trans.get("FinSetConfig.tab.Fintabs"), null, finTabPanel(), - trans.get("FinSetConfig.tab.Through-the-wall"), 0); - } - - - protected void addFinSetButtons() { - JButton convert = null; - - //// Convert buttons - if (!(component instanceof FreeformFinSet)) { - //// Convert to freeform - convert = new JButton(trans.get("FinSetConfig.but.Converttofreeform")); - //// Convert this fin set into a freeform fin set - convert.setToolTipText(trans.get("FinSetConfig.but.Converttofreeform.ttip")); - convert.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Converting " + component.getComponentName() + " into freeform fin set"); - - // Do change in future for overall safety - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - //// Convert fin set - document.addUndoPosition(trans.get("FinSetConfig.Convertfinset")); - RocketComponent freeform = - FreeformFinSet.convertFinSet((FinSet) component); - ComponentConfigDialog.showDialog(freeform); - } - }); - - ComponentConfigDialog.hideDialog(); - } - }); - } - - //// Split fins - split = new JButton(trans.get("FinSetConfig.but.Splitfins")); - //// Split the fin set into separate fins - split.setToolTipText(trans.get("FinSetConfig.but.Splitfins.ttip")); - split.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Splitting " + component.getComponentName() + " into separate fins, fin count=" + - ((FinSet) component).getFinCount()); - - // Do change in future for overall safety - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - RocketComponent parent = component.getParent(); - int index = parent.getChildPosition(component); - int count = ((FinSet) component).getFinCount(); - double base = ((FinSet) component).getBaseRotation(); - if (count <= 1) - return; - - document.addUndoPosition("Split fin set"); - parent.removeChild(index); - for (int i = 0; i < count; i++) { - FinSet copy = (FinSet) component.copy(); - copy.setFinCount(1); - copy.setBaseRotation(base + i * 2 * Math.PI / count); - copy.setName(copy.getName() + " #" + (i + 1)); - parent.addChild(copy, index + i); - } - } - }); - - ComponentConfigDialog.hideDialog(); - } - }); - split.setEnabled(((FinSet) component).getFinCount() > 1); - - if (convert == null) - addButtons(split); - else - addButtons(split, convert); - - } - - public JPanel finTabPanel() { - JPanel panel = new JPanel( - new MigLayout("align 50% 20%, fillx, gap rel unrel, ins 20lp 10% 20lp 10%", - "[150lp::][65lp::][30lp::][200lp::]", "")); - // JPanel panel = new JPanel(new MigLayout("fillx, align 20% 20%, gap rel unrel", - // "[40lp][80lp::][30lp::][100lp::]","")); - - //// Through-the-wall fin tabs: - panel.add(new StyledLabel(trans.get("FinSetConfig.lbl.Through-the-wall"), Style.BOLD), - "spanx, wrap 30lp"); - - JLabel label; - DoubleModel length; - DoubleModel length2; - DoubleModel length_2; - JSpinner spin; - JButton autoCalc; - - length = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - length2 = new DoubleModel(component, "Length", 0.5, UnitGroup.UNITS_LENGTH, 0); - length_2 = new DoubleModel(component, "Length", -0.5, UnitGroup.UNITS_LENGTH, 0); - - register(length); - register(length2); - register(length_2); - - //// Tab length - //// Tab length: - label = new JLabel(trans.get("FinSetConfig.lbl.Tablength")); - //// The length of the fin tab. - label.setToolTipText(trans.get("FinSetConfig.ttip.Tablength")); - panel.add(label, "gapleft para, gapright 40lp, growx 1"); - - final DoubleModel mtl = new DoubleModel(component, "TabLength", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(mtl.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx 1"); - - panel.add(new UnitSelector(mtl), "growx 1"); - panel.add(new BasicSlider(mtl.getSliderModel(DoubleModel.ZERO, length)), - "w 100lp, growx 5, wrap"); - - - //// Tab length - //// Tab height: - label = new JLabel(trans.get("FinSetConfig.lbl.Tabheight")); - //// The spanwise height of the fin tab. - label.setToolTipText(trans.get("FinSetConfig.ttip.Tabheight")); - panel.add(label, "gapleft para"); - - final DoubleModel mth = new DoubleModel(component, "TabHeight", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(mth.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(mth), "growx"); - panel.add(new BasicSlider(mth.getSliderModel(DoubleModel.ZERO, length2)), - "w 100lp, growx 5, wrap"); - - //// Tab position: - label = new JLabel(trans.get("FinSetConfig.lbl.Tabposition")); - //// The position of the fin tab. - label.setToolTipText(trans.get("FinSetConfig.ttip.Tabposition")); - panel.add(label, "gapleft para"); - - final DoubleModel mts = new DoubleModel(component, "TabShift", UnitGroup.UNITS_LENGTH); - - spin = new JSpinner(mts.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(mts), "growx"); - panel.add(new BasicSlider(mts.getSliderModel(length_2, length2)), "w 100lp, growx 5, wrap"); - - - //// relative to - label = new JLabel(trans.get("FinSetConfig.lbl.relativeto")); - panel.add(label, "right, gapright unrel"); - - final EnumModel em = - new EnumModel(component, "TabRelativePosition"); - - panel.add(new JComboBox(em), "spanx 3, growx, wrap para"); - - - // Calculate fin tab height, length, and position - autoCalc = new JButton(trans.get("FinSetConfig.but.AutoCalc")); - - autoCalc.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Computing " + component.getComponentName() + " tab height."); - - RocketComponent parent = component.getParent(); - if (parent instanceof Coaxial) { - try { - document.startUndo("Compute fin tabs"); - - List rings = new ArrayList(); - //Do deep recursive iteration - Iterator iter = parent.iterator(false); - while (iter.hasNext()) { - RocketComponent rocketComponent = iter.next(); - if (rocketComponent instanceof InnerTube) { - InnerTube it = (InnerTube) rocketComponent; - if (it.isMotorMount()) { - double depth = ((Coaxial) parent).getOuterRadius() - it.getOuterRadius(); - //Set fin tab depth - if (depth >= 0.0d) { - mth.setValue(depth); - mth.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - } - } else if (rocketComponent instanceof CenteringRing) { - rings.add((CenteringRing) rocketComponent); - } - } - //Figure out position and length of the fin tab - if (!rings.isEmpty()) { - FinSet.TabRelativePosition temp = (FinSet.TabRelativePosition) em.getSelectedItem(); - em.setSelectedItem(FinSet.TabRelativePosition.FRONT); - double len = computeFinTabLength(rings, component.asPositionValue(RocketComponent.Position.TOP, parent), - component.getLength(), mts, parent); - mtl.setValue(len); - //Be nice to the user and set the tab relative position enum back the way they had it. - em.setSelectedItem(temp); - } - - } finally { - document.stopUndo(); - } - } - } - }); - panel.add(autoCalc, "skip 1, spanx"); - - return panel; - } - - /** - * Scenarios: - *

- * 1. All rings ahead of start of fin. - * 2. First ring ahead of start of fin. Second ring ahead of end of fin. - * 3. First ring ahead of start of fin. Second ring behind end of fin. - * 4. First ring equal or behind start of fin. Second ring ahead of, or equal to, end of fin. - * 5. First ring equal or behind start of fin. Second ring behind end of fin. - * 6. All rings behind end of fin. - * - * @param rings an unordered list of centering rings attached to the parent of the fin set - * @param finPositionFromTop the position from the top of the parent of the start of the fin set root - * @param finLength the length of the root chord - * @param mts the model for the tab shift (position); the model's value is modified as a result of this method call - * @param relativeTo the parent component of the finset - * - * @return the length of the fin tab - */ - private static double computeFinTabLength(List rings, Double finPositionFromTop, Double finLength, DoubleModel mts, - final RocketComponent relativeTo) { - List positionsFromTop = new ArrayList(); - - //Fin tabs will be computed between the last two rings that meet the criteria, represented by top and bottom here. - SortableRing top = null; - SortableRing bottom = null; - - if (rings != null) { - //Sort rings from top of parent to bottom - Collections.sort(rings, new Comparator() { - @Override - public int compare(CenteringRing centeringRing, CenteringRing centeringRing1) { - return (int) (1000d * (centeringRing.asPositionValue(RocketComponent.Position.TOP, relativeTo) - - centeringRing1.asPositionValue(RocketComponent.Position.TOP, relativeTo))); - } - }); - - for (int i = 0; i < rings.size(); i++) { - CenteringRing centeringRing = rings.get(i); - //Handle centering rings that overlap or are adjacent by synthetically merging them into one virtual ring. - if (!positionsFromTop.isEmpty() && - positionsFromTop.get(positionsFromTop.size() - 1).bottomSidePositionFromTop() >= - centeringRing.asPositionValue(RocketComponent.Position.TOP, relativeTo)) { - SortableRing adjacent = positionsFromTop.get(positionsFromTop.size() - 1); - adjacent.merge(centeringRing, relativeTo); - } else { - positionsFromTop.add(new SortableRing(centeringRing, relativeTo)); - } - } - - for (int i = 0; i < positionsFromTop.size(); i++) { - SortableRing sortableRing = positionsFromTop.get(i); - if (top == null) { - top = sortableRing; - } else if (sortableRing.bottomSidePositionFromTop() <= finPositionFromTop) { - top = sortableRing; - bottom = null; - } else if (top.bottomSidePositionFromTop() <= finPositionFromTop) { - if (bottom == null) { - //If the current ring is in the upper half of the root chord, make it the top ring - if (sortableRing.bottomSidePositionFromTop() < finPositionFromTop + finLength / 2d) { - top = sortableRing; - } else { - bottom = sortableRing; - } - } - //Is the ring even with or above the end of the root chord? If so, make the existing bottom the top ring, - //and the current ring the bottom - else if (sortableRing.positionFromTop() <= finPositionFromTop + finLength) { - top = bottom; - bottom = sortableRing; - } - } else { - if (bottom == null) { - bottom = sortableRing; - } - } - } - } - - double resultFinTabLength = 0d; - - // Edge case where there are no centering rings or for some odd reason top and bottom are identical. - if (top == null || top == bottom) { - mts.setValue(0); - resultFinTabLength = finLength; - } else if (bottom == null) { - // If there is no bottom ring and the top ring's bottom edge is within the span of the root chord, then - // set the position of the fin tab starting at the bottom side of the top ring. - if (top.bottomSidePositionFromTop() >= finPositionFromTop) { - mts.setValue(top.bottomSidePositionFromTop() - finPositionFromTop); - resultFinTabLength = (finPositionFromTop + finLength - top.bottomSidePositionFromTop()); - } else { - mts.setValue(0); - double diffLen = top.positionFromTop() - finPositionFromTop; - if (diffLen < 0) { - // Otherwise the top ring is outside the span of the root chord so set the tab length to be the entire - // root chord. - resultFinTabLength = finLength; - } - else { - // Otherwise there is one ring within the span. Return the length from the start of the fin to the top - // side of the ring. - resultFinTabLength = diffLen; - } - } - } - // If the bottom edge of the top centering ring is above the start of the fin's root chord, then make the - // fin tab align with the start of the root chord. - else if (top.bottomSidePositionFromTop() < finPositionFromTop) { - mts.setValue(0); - - double lenToBottomRing = bottom.positionFromTop - finPositionFromTop; - // If the bottom ring lies farther back (down) than the trailing edge of the fin, then the tab should - // only be as long as the fin. - if (lenToBottomRing > finLength) { - resultFinTabLength = finLength; - } - else { - resultFinTabLength = lenToBottomRing; - } - } else { - mts.setValue(top.bottomSidePositionFromTop() - finPositionFromTop); - // The bottom ring is beyond the trailing edge of the fin. - if (bottom.positionFromTop() > finLength + finPositionFromTop) { - resultFinTabLength = (finLength + finPositionFromTop - top.bottomSidePositionFromTop()); - } - // The rings are within the span of the root chord. Place the tab between them. - else { - resultFinTabLength = (bottom.positionFromTop() - top.bottomSidePositionFromTop()); - } - } - if (resultFinTabLength < 0) { - resultFinTabLength = 0d; - } - return resultFinTabLength; - } - - @Override - public void updateFields() { - super.updateFields(); - if (split != null) - split.setEnabled(((FinSet) component).getFinCount() > 1); - } - - /** - * A container class to store pertinent info about centering rings. This is used in the computation to figure - * out tab length and position. - */ - static class SortableRing { - - /** - * The length of the ring (more commonly called the thickness). - */ - private double thickness; - /** - * The position of the ring from the top of the parent. - */ - private double positionFromTop; - - /** - * Constructor. - * - * @param r the source centering ring - */ - SortableRing(CenteringRing r, RocketComponent relativeTo) { - thickness = r.getLength(); - positionFromTop = r.asPositionValue(RocketComponent.Position.TOP, relativeTo); - } - - /** - * Merge an adjacent ring. - * - * @param adjacent the adjacent ring - */ - public void merge(CenteringRing adjacent, RocketComponent relativeTo) { - double v = adjacent.asPositionValue(RocketComponent.Position.TOP, relativeTo); - if (positionFromTop < v) { - thickness = (v + adjacent.getLength()) - positionFromTop; - } else { - double tmp = positionFromTop + thickness; - positionFromTop = v; - thickness = tmp - v; - } - } - - /** - * Compute the position of the bottom edge of the ring, relative to the top of the parent. - * - * @return the distance from the top of the parent to the bottom edge of the ring - */ - public double bottomSidePositionFromTop() { - return positionFromTop + thickness; - } - - /** - * Compute the position of the top edge of the ring, relative to the top of the parent. - * - * @return the distance from the top of the parent to the top edge of the ring - */ - public double positionFromTop() { - return positionFromTop; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java b/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java deleted file mode 100644 index aa82e994..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java +++ /dev/null @@ -1,534 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.io.IOException; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.SwingUtilities; -import javax.swing.table.AbstractTableModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.IntegerModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.dialogs.ScaleDialog; -import net.sf.openrocket.gui.scalefigure.FinPointFigure; -import net.sf.openrocket.gui.scalefigure.ScaleScrollPane; -import net.sf.openrocket.gui.scalefigure.ScaleSelector; -import net.sf.openrocket.gui.util.CustomFinImporter; -import net.sf.openrocket.gui.util.FileHelper; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.IllegalFinPointException; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Coordinate; - -public class FreeformFinSetConfig extends FinSetConfig { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private final FreeformFinSet finset; - private JTable table = null; - private FinPointTableModel tableModel = null; - - private FinPointFigure figure = null; - - - public FreeformFinSetConfig(OpenRocketDocument d, RocketComponent component) { - super(d, component); - this.finset = (FreeformFinSet) component; - - //// General and General properties - tabbedPane.insertTab(trans.get("FreeformFinSetCfg.tab.General"), null, generalPane(), trans.get("FreeformFinSetCfg.tab.ttip.General"), 0); - //// Shape and Fin shape - tabbedPane.insertTab(trans.get("FreeformFinSetCfg.tab.Shape"), null, shapePane(), trans.get("FreeformFinSetCfg.tab.ttip.Finshape"), 1); - tabbedPane.setSelectedIndex(0); - - addFinSetButtons(); - } - - - - private JPanel generalPane() { - - DoubleModel m; - JSpinner spin; - JComboBox combo; - - JPanel mainPanel = new JPanel(new MigLayout("fill")); - - JPanel panel = new JPanel(new MigLayout("fill, gap rel unrel", "[][65lp::][30lp::]", "")); - - - - //// Number of fins: - panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Numberoffins"))); - - IntegerModel im = new IntegerModel(component, "FinCount", 1, 8); - - spin = new JSpinner(im.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx, wrap"); - - - //// Base rotation - panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Finrotation"))); - - m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - - //// Fin cant - JLabel label = new JLabel(trans.get("FreeformFinSetCfg.lbl.Fincant")); - //// The angle that the fins are canted with respect to the rocket body. - label.setToolTipText(trans.get("FreeformFinSetCfg.lbl.ttip.Fincant")); - panel.add(label); - - m = new DoubleModel(component, "CantAngle", UnitGroup.UNITS_ANGLE, -FinSet.MAX_CANT, FinSet.MAX_CANT); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-FinSet.MAX_CANT, FinSet.MAX_CANT)), "w 100lp, wrap 40lp"); - - - - //// Position - //// Position relative to: - panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Posrelativeto"))); - - combo = new JComboBox(new EnumModel(component, "RelativePosition", new RocketComponent.Position[] { RocketComponent.Position.TOP, RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, RocketComponent.Position.ABSOLUTE })); - panel.add(combo, "spanx 3, growx, wrap"); - //// plus - panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap"); - - - - - - mainPanel.add(panel, "aligny 20%"); - mainPanel.add(new JSeparator(SwingConstants.VERTICAL), "growy, height 150lp"); - - - panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - - - - //// Cross section - //// Fin cross section: - panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.FincrossSection")), "span, split"); - combo = new JComboBox(new EnumModel(component, "CrossSection")); - panel.add(combo, "growx, wrap unrel"); - - - //// Thickness: - panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Thickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap 30lp"); - - - //// Material - materialPanel(panel, Material.Type.BULK); - - - - mainPanel.add(panel, "aligny 20%"); - - return mainPanel; - } - - - - private JPanel shapePane() { - JPanel panel = new JPanel(new MigLayout("fill")); - - - // Create the figure - figure = new FinPointFigure(finset); - ScaleScrollPane figurePane = new FinPointScrollPane(); - figurePane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - figurePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - - // Create the table - tableModel = new FinPointTableModel(); - table = new JTable(tableModel); - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - for (int i = 0; i < Columns.values().length; i++) { - table.getColumnModel().getColumn(i).setPreferredWidth(Columns.values()[i].getWidth()); - } - JScrollPane tablePane = new JScrollPane(table); - - JButton scaleButton = new JButton(trans.get("FreeformFinSetConfig.lbl.scaleFin")); - scaleButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Scaling free-form fin"); - ScaleDialog dialog = new ScaleDialog(document, finset, SwingUtilities.getWindowAncestor(FreeformFinSetConfig.this), true); - dialog.setVisible(true); - dialog.dispose(); - } - }); - - // panel.add(new JLabel("Coordinates:"), "aligny bottom, alignx 50%"); - // panel.add(new JLabel(" View:"), "wrap, aligny bottom"); - - - panel.add(tablePane, "growy, width 100lp:100lp:, height 100lp:250lp:"); - panel.add(figurePane, "gap unrel, spanx, spany 3, growx, growy 1000, height 100lp:250lp:, wrap"); - - panel.add(new StyledLabel(trans.get("lbl.doubleClick1"), -2), "alignx 50%, wrap"); - panel.add(new StyledLabel(trans.get("FreeformFinSetConfig.lbl.doubleClick2"), -2), "alignx 50%, wrap"); - - panel.add(scaleButton, "spany 2, alignx 50%, aligny 50%"); - panel.add(new ScaleSelector(figurePane), "spany 2, aligny 50%"); - - JButton importButton = new JButton(trans.get("CustomFinImport.button.label")); - importButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - importImage(); - } - }); - panel.add(importButton, "spany 2, bottom"); - - // panel.add(new CustomFinBmpImporter(finset), "spany 2, bottom"); - panel.add(new StyledLabel(trans.get("FreeformFinSetConfig.lbl.clickDrag"), -2), "right, wrap"); - panel.add(new StyledLabel(trans.get("FreeformFinSetConfig.lbl.ctrlClick"), -2), "right"); - - return panel; - } - - - - - - private void importImage() { - JFileChooser chooser = new JFileChooser(); - chooser.setFileFilter(FileHelper.getImageFileFilter()); - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - - JPanel desc = new JPanel(new MigLayout("fill, ins 0 para 0 para")); - desc.add(new DescriptionArea(trans.get("CustomFinImport.description"), 5, 0), "grow, wmin 150lp"); - chooser.setAccessory(desc); - - int option = chooser.showOpenDialog(this); - - if (option == JFileChooser.APPROVE_OPTION) { - try { - CustomFinImporter importer = new CustomFinImporter(); - List points = importer.getPoints(chooser.getSelectedFile()); - document.startUndo(trans.get("CustomFinImport.undo")); - finset.setPoints(points); - } catch (IllegalFinPointException e) { - log.warn("Error storing fin points", e); - JOptionPane.showMessageDialog(this, trans.get("CustomFinImport.error.badimage"), - trans.get("CustomFinImport.error.title"), JOptionPane.ERROR_MESSAGE); - } catch (IOException e) { - log.warn("Error loading file", e); - JOptionPane.showMessageDialog(this, e.getLocalizedMessage(), - trans.get("CustomFinImport.error.title"), JOptionPane.ERROR_MESSAGE); - } finally { - document.stopUndo(); - } - } - - } - - - @Override - public void updateFields() { - super.updateFields(); - - if (tableModel != null) { - tableModel.fireTableDataChanged(); - } - if (figure != null) { - figure.updateFigure(); - } - } - - - - - private class FinPointScrollPane extends ScaleScrollPane { - private static final int ANY_MASK = (MouseEvent.ALT_DOWN_MASK | MouseEvent.ALT_GRAPH_DOWN_MASK | MouseEvent.META_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK | MouseEvent.SHIFT_DOWN_MASK); - - private int dragIndex = -1; - - public FinPointScrollPane() { - super(figure, false); // Disallow fitting as it's buggy - } - - @Override - public void mousePressed(MouseEvent event) { - int mods = event.getModifiersEx(); - - if (event.getButton() != MouseEvent.BUTTON1 || (mods & ANY_MASK) != 0) { - super.mousePressed(event); - return; - } - - int index = getPoint(event); - if (index >= 0) { - dragIndex = index; - return; - } - index = getSegment(event); - if (index >= 0) { - Point2D.Double point = getCoordinates(event); - finset.addPoint(index); - try { - finset.setPoint(index, point.x, point.y); - } catch (IllegalFinPointException ignore) { - } - dragIndex = index; - - return; - } - - super.mousePressed(event); - return; - } - - - @Override - public void mouseDragged(MouseEvent event) { - int mods = event.getModifiersEx(); - if (dragIndex < 0 || (mods & (ANY_MASK | MouseEvent.BUTTON1_DOWN_MASK)) != MouseEvent.BUTTON1_DOWN_MASK) { - super.mouseDragged(event); - return; - } - Point2D.Double point = getCoordinates(event); - - try { - finset.setPoint(dragIndex, point.x, point.y); - } catch (IllegalFinPointException ignore) { - log.debug("Ignoring IllegalFinPointException while dragging, dragIndex=" + dragIndex + " x=" + point.x + " y=" + point.y); - } - } - - - @Override - public void mouseReleased(MouseEvent event) { - dragIndex = -1; - super.mouseReleased(event); - } - - @Override - public void mouseClicked(MouseEvent event) { - int mods = event.getModifiersEx(); - if (event.getButton() != MouseEvent.BUTTON1 || (mods & ANY_MASK) != MouseEvent.CTRL_DOWN_MASK) { - super.mouseClicked(event); - return; - } - - int index = getPoint(event); - if (index < 0) { - super.mouseClicked(event); - return; - } - - try { - finset.removePoint(index); - } catch (IllegalFinPointException ignore) { - } - } - - - private int getPoint(MouseEvent event) { - Point p0 = event.getPoint(); - Point p1 = this.getViewport().getViewPosition(); - int x = p0.x + p1.x; - int y = p0.y + p1.y; - - return figure.getIndexByPoint(x, y); - } - - private int getSegment(MouseEvent event) { - Point p0 = event.getPoint(); - Point p1 = this.getViewport().getViewPosition(); - int x = p0.x + p1.x; - int y = p0.y + p1.y; - - return figure.getSegmentByPoint(x, y); - } - - private Point2D.Double getCoordinates(MouseEvent event) { - Point p0 = event.getPoint(); - Point p1 = this.getViewport().getViewPosition(); - int x = p0.x + p1.x; - int y = p0.y + p1.y; - - return figure.convertPoint(x, y); - } - - - } - - - - - - private enum Columns { - // NUMBER { - // @Override - // public String toString() { - // return "#"; - // } - // @Override - // public String getValue(FreeformFinSet finset, int row) { - // return "" + (row+1) + "."; - // } - // @Override - // public int getWidth() { - // return 10; - // } - // }, - X { - @Override - public String toString() { - return "X / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().toString(); - } - - @Override - public String getValue(FreeformFinSet finset, int row) { - return UnitGroup.UNITS_LENGTH.getDefaultUnit().toString(finset.getFinPoints()[row].x); - } - }, - Y { - @Override - public String toString() { - return "Y / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().toString(); - } - - @Override - public String getValue(FreeformFinSet finset, int row) { - return UnitGroup.UNITS_LENGTH.getDefaultUnit().toString(finset.getFinPoints()[row].y); - } - }; - - public abstract String getValue(FreeformFinSet finset, int row); - - @Override - public abstract String toString(); - - public int getWidth() { - return 20; - } - } - - private class FinPointTableModel extends AbstractTableModel { - - @Override - public int getColumnCount() { - return Columns.values().length; - } - - @Override - public int getRowCount() { - return finset.getPointCount(); - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - return Columns.values()[columnIndex].getValue(finset, rowIndex); - } - - @Override - public String getColumnName(int columnIndex) { - return Columns.values()[columnIndex].toString(); - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - if (rowIndex == 0 || rowIndex == getRowCount() - 1) { - return (columnIndex == Columns.X.ordinal()); - } - - return (columnIndex == Columns.X.ordinal() || columnIndex == Columns.Y.ordinal()); - } - - @Override - public void setValueAt(Object o, int rowIndex, int columnIndex) { - if (!(o instanceof String)) - return; - - if (rowIndex < 0 || rowIndex >= finset.getFinPoints().length || columnIndex < 0 || columnIndex >= Columns.values().length) { - throw new IllegalArgumentException("Index out of bounds, row=" + rowIndex + " column=" + columnIndex + " fin point count=" + finset.getFinPoints().length); - } - - String str = (String) o; - try { - - double value = UnitGroup.UNITS_LENGTH.fromString(str); - Coordinate c = finset.getFinPoints()[rowIndex]; - if (columnIndex == Columns.X.ordinal()) - c = c.setX(value); - else - c = c.setY(value); - - finset.setPoint(rowIndex, c.x, c.y); - - } catch (NumberFormatException ignore) { - } catch (IllegalFinPointException ignore) { - } - } - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/InnerTubeConfig.java b/core/src/net/sf/openrocket/gui/configdialog/InnerTubeConfig.java deleted file mode 100644 index e679ed05..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/InnerTubeConfig.java +++ /dev/null @@ -1,327 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.Resettable; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.ClusterConfiguration; -import net.sf.openrocket.rocketcomponent.Clusterable; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.StateChangeListener; - -import javax.swing.*; -import javax.swing.border.BevelBorder; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.geom.Ellipse2D; -import java.util.EventObject; -import java.util.List; - - -public class InnerTubeConfig extends ThicknessRingComponentConfig { - private static final Translator trans = Application.getTranslator(); - - - public InnerTubeConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel tab; - - tab = new MotorConfig((MotorMount) c); - //// Motor and Motor mount configuration - tabbedPane.insertTab(trans.get("InnerTubeCfg.tab.Motor"), null, tab, - trans.get("InnerTubeCfg.tab.ttip.Motor"), 1); - - tab = clusterTab(); - //// Cluster and Cluster configuration - tabbedPane.insertTab(trans.get("InnerTubeCfg.tab.Cluster"), null, tab, - trans.get("InnerTubeCfg.tab.ttip.Cluster"), 2); - - tab = positionTab(); - //// Radial position - tabbedPane.insertTab(trans.get("InnerTubeCfg.tab.Radialpos"), null, tab, - trans.get("InnerTubeCfg.tab.ttip.Radialpos"), 3); - - tabbedPane.setSelectedIndex(0); - } - - - private JPanel clusterTab() { - JPanel panel = new JPanel(new MigLayout()); - - JPanel subPanel = new JPanel(new MigLayout()); - - // Cluster type selection - //// Select cluster configuration: - subPanel.add(new JLabel(trans.get("InnerTubeCfg.lbl.Selectclustercfg")), "spanx, wrap"); - subPanel.add(new ClusterSelectionPanel((InnerTube) component), "spanx, wrap"); - // JPanel clusterSelection = new ClusterSelectionPanel((InnerTube)component); - // clusterSelection.setBackground(Color.blue); - // subPanel.add(clusterSelection); - - panel.add(subPanel); - - - subPanel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]")); - - // Tube separation scale - //// Tube separation: - JLabel l = new JLabel(trans.get("InnerTubeCfg.lbl.TubeSep")); - //// The separation of the tubes, 1.0 = touching each other - l.setToolTipText(trans.get("InnerTubeCfg.lbl.ttip.TubeSep")); - subPanel.add(l); - DoubleModel dm = new DoubleModel(component, "ClusterScale", 1, UnitGroup.UNITS_NONE, 0); - - JSpinner spin = new JSpinner(dm.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - //// The separation of the tubes, 1.0 = touching each other - spin.setToolTipText(trans.get("InnerTubeCfg.lbl.ttip.TubeSep")); - subPanel.add(spin, "growx"); - - BasicSlider bs = new BasicSlider(dm.getSliderModel(0, 1, 4)); - //// The separation of the tubes, 1.0 = touching each other - bs.setToolTipText(trans.get("InnerTubeCfg.lbl.ttip.TubeSep")); - subPanel.add(bs, "skip,w 100lp, wrap"); - - // Rotation: - l = new JLabel(trans.get("InnerTubeCfg.lbl.Rotation")); - //// Rotation angle of the cluster configuration - l.setToolTipText(trans.get("InnerTubeCfg.lbl.ttip.Rotation")); - subPanel.add(l); - dm = new DoubleModel(component, "ClusterRotation", 1, UnitGroup.UNITS_ANGLE, - -Math.PI, Math.PI); - - spin = new JSpinner(dm.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - //// Rotation angle of the cluster configuration - spin.setToolTipText(trans.get("InnerTubeCfg.lbl.ttip.Rotation")); - subPanel.add(spin, "growx"); - - subPanel.add(new UnitSelector(dm), "growx"); - bs = new BasicSlider(dm.getSliderModel(-Math.PI, 0, Math.PI)); - //// Rotation angle of the cluster configuration - bs.setToolTipText(trans.get("InnerTubeCfg.lbl.ttip.Rotation")); - subPanel.add(bs, "w 100lp, wrap para"); - - - - // Split button - //// Split cluster - JButton split = new JButton(trans.get("InnerTubeCfg.but.Splitcluster")); - //// Split the cluster into separate components.
- //// This also duplicates all components attached to this inner tube. - split.setToolTipText(trans.get("InnerTubeCfg.lbl.longA1") + - trans.get("InnerTubeCfg.lbl.longA2")); - split.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Do change in future for overall safety - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - RocketComponent parent = component.getParent(); - int index = parent.getChildPosition(component); - if (index < 0) { - throw new BugException("Inconsistent state: component=" + component + - " parent=" + parent + " parent.children=" + parent.getChildren()); - } - - InnerTube tube = (InnerTube) component; - if (tube.getClusterCount() <= 1) - return; - - document.addUndoPosition("Split cluster"); - - Coordinate[] coords = { Coordinate.NUL }; - coords = component.shiftCoordinates(coords); - parent.removeChild(index); - for (int i = 0; i < coords.length; i++) { - InnerTube copy = makeIndividualClusterComponent(coords[i], component.getName() + " #" + (i + 1), component); - - parent.addChild(copy, index + i); - } - } - }); - } - }); - subPanel.add(split, "spanx, split 2, gapright para, sizegroup buttons, right"); - - - // Reset button - ///// Reset settings - JButton reset = new JButton(trans.get("InnerTubeCfg.but.Resetsettings")); - //// Reset the separation and rotation to the default values - reset.setToolTipText(trans.get("InnerTubeCfg.but.ttip.Resetsettings")); - reset.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - ((InnerTube) component).setClusterScale(1.0); - ((InnerTube) component).setClusterRotation(0.0); - } - }); - subPanel.add(reset, "sizegroup buttons, right"); - - panel.add(subPanel, "grow"); - - - return panel; - } - - /** - * For a given coordinate that represents one tube in a cluster, create an instance of that tube. Must be called - * once for each tube in the cluster. - * - * @param coord the coordinate of the clustered tube to create - * @param splitName the name of the individual tube - * @param theInnerTube the 'parent' from which this tube will be created. - * - * @return an instance of an inner tube that represents ONE of the clustered tubes in the cluster represented - * by theInnerTube - */ - public static InnerTube makeIndividualClusterComponent(Coordinate coord, String splitName, RocketComponent theInnerTube) { - InnerTube copy = (InnerTube) theInnerTube.copy(); - copy.setClusterConfiguration(ClusterConfiguration.SINGLE); - copy.setClusterRotation(0.0); - copy.setClusterScale(1.0); - copy.setRadialShift(coord.y, coord.z); - copy.setName(splitName); - return copy; - } -} - - -class ClusterSelectionPanel extends JPanel { - private static final int BUTTON_SIZE = 50; - private static final int MOTOR_DIAMETER = 10; - - private static final Color SELECTED_COLOR = Color.RED; - private static final Color UNSELECTED_COLOR = Color.WHITE; - private static final Color MOTOR_FILL_COLOR = Color.GREEN; - private static final Color MOTOR_BORDER_COLOR = Color.BLACK; - - public ClusterSelectionPanel(Clusterable component) { - super(new MigLayout("gap 0 0", - "[" + BUTTON_SIZE + "!][" + BUTTON_SIZE + "!][" + BUTTON_SIZE + "!][" + BUTTON_SIZE + "!]", - "[" + BUTTON_SIZE + "!][" + BUTTON_SIZE + "!][" + BUTTON_SIZE + "!]")); - - for (int i = 0; i < ClusterConfiguration.CONFIGURATIONS.length; i++) { - ClusterConfiguration config = ClusterConfiguration.CONFIGURATIONS[i]; - - JComponent button = new ClusterButton(component, config); - if (i % 4 == 3) - add(button, "wrap"); - else - add(button); - } - - } - - - private class ClusterButton extends JPanel implements StateChangeListener, MouseListener, - Resettable { - private Clusterable component; - private ClusterConfiguration config; - - public ClusterButton(Clusterable c, ClusterConfiguration config) { - component = c; - this.config = config; - setMinimumSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE)); - setPreferredSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE)); - setMaximumSize(new Dimension(BUTTON_SIZE, BUTTON_SIZE)); - setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); - // setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); - component.addChangeListener(this); - addMouseListener(this); - } - - - @Override - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g; - Rectangle area = g2.getClipBounds(); - - if (component.getClusterConfiguration() == config) - g2.setColor(SELECTED_COLOR); - else - g2.setColor(UNSELECTED_COLOR); - - g2.fillRect(area.x, area.y, area.width, area.height); - - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - g2.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - List points = config.getPoints(); - Ellipse2D.Float circle = new Ellipse2D.Float(); - for (int i = 0; i < points.size() / 2; i++) { - double x = points.get(i * 2); - double y = points.get(i * 2 + 1); - - double px = BUTTON_SIZE / 2 + x * MOTOR_DIAMETER; - double py = BUTTON_SIZE / 2 - y * MOTOR_DIAMETER; - circle.setFrameFromCenter(px, py, px + MOTOR_DIAMETER / 2, py + MOTOR_DIAMETER / 2); - - g2.setColor(MOTOR_FILL_COLOR); - g2.fill(circle); - g2.setColor(MOTOR_BORDER_COLOR); - g2.draw(circle); - } - } - - - @Override - public void stateChanged(EventObject e) { - repaint(); - } - - - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - component.setClusterConfiguration(config); - } - } - - @Override - public void mouseEntered(MouseEvent e) { - } - - @Override - public void mouseExited(MouseEvent e) { - } - - @Override - public void mousePressed(MouseEvent e) { - } - - @Override - public void mouseReleased(MouseEvent e) { - } - - - @Override - public void resetModel() { - component.removeChangeListener(this); - removeMouseListener(this); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java b/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java deleted file mode 100644 index 07248d11..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java +++ /dev/null @@ -1,161 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class LaunchLugConfig extends RocketComponentConfig { - - private MotorConfig motorConfigPane = null; - private static final Translator trans = Application.getTranslator(); - - public LaunchLugConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel primary = new JPanel(new MigLayout("fill")); - - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - //// Body tube length - //// Length: - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.Length"))); - - DoubleModel m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.02, 0.1)), "w 100lp, wrap para"); - - - //// Body tube diameter - //// Outer diameter: - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.Outerdiam"))); - - DoubleModel od = new DoubleModel(component, "OuterRadius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap rel"); - - - //// Inner diameter: - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.Innerdiam"))); - - // Diameter = 2*Radius - m = new DoubleModel(component, "InnerRadius", 2, UnitGroup.UNITS_LENGTH, 0); - - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(new DoubleModel(0), od)), "w 100lp, wrap rel"); - - - //// Wall thickness - //// Thickness: - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.Thickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap 20lp"); - - - //// Radial position: - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.Radialpos"))); - - m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - - - primary.add(panel, "grow, gapright 20lp"); - panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - - - //// Position relative to: - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.Posrelativeto"))); - - JComboBox combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx, growx, wrap"); - - //// plus - panel.add(new JLabel(trans.get("LaunchLugCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap para"); - - - - //// Material - materialPanel(panel, Material.Type.BULK); - - - primary.add(panel, "grow"); - - //// General and General properties - tabbedPane.insertTab(trans.get("LaunchLugCfg.tab.General"), null, primary, - trans.get("LaunchLugCfg.tab.Generalprop"), 0); - tabbedPane.setSelectedIndex(0); - } - - @Override - public void updateFields() { - super.updateFields(); - if (motorConfigPane != null) - motorConfigPane.updateFields(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java b/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java deleted file mode 100644 index cf70d463..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java +++ /dev/null @@ -1,172 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - - -public class MassComponentConfig extends RocketComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public MassComponentConfig(OpenRocketDocument d, RocketComponent component) { - super(d, component); - - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - - - //// Mass - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.Mass"))); - - DoubleModel m = new DoubleModel(component, "ComponentMass", UnitGroup.UNITS_MASS, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.5)), "w 100lp, wrap"); - - - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.Density"))); - - m = new DoubleModel(component, "Density", UnitGroup.UNITS_DENSITY_BULK, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(500, 2000, 10000)), "w 100lp, wrap"); - - - - //// Mass length - //// Length - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.Length"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 0.5)), "w 100lp, wrap"); - - - //// Tube diameter - //// Diameter: - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.Diameter"))); - - DoubleModel od = new DoubleModel(component, "Radius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap"); - - - //// Position - //// Position relative to: - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.PosRelativeto"))); - - JComboBox combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx, growx, wrap"); - //// plus - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap"); - - //// General and General properties - tabbedPane.insertTab(trans.get("MassComponentCfg.tab.General"), null, panel, - trans.get("MassComponentCfg.tab.ttip.General"), 0); - //// Radial position and Radial position configuration - tabbedPane.insertTab(trans.get("MassComponentCfg.tab.Radialpos"), null, positionTab(), - trans.get("MassComponentCfg.tab.ttip.Radialpos"), 1); - tabbedPane.setSelectedIndex(0); - } - - - protected JPanel positionTab() { - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - //// Radial position - //// Radial distance: - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.Radialdistance"))); - - DoubleModel m = new DoubleModel(component, "RadialPosition", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 1.0)), "w 100lp, wrap"); - - - //// Radial direction: - panel.add(new JLabel(trans.get("MassComponentCfg.lbl.Radialdirection"))); - - m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - //// Reset button - JButton button = new JButton(trans.get("MassComponentCfg.but.Reset")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ((MassComponent) component).setRadialDirection(0.0); - ((MassComponent) component).setRadialPosition(0.0); - } - }); - panel.add(button, "spanx, right"); - - return panel; - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java b/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java deleted file mode 100644 index 45eca30f..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java +++ /dev/null @@ -1,243 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.Component; -import java.awt.Container; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SwingUtilities; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.BooleanModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.MotorConfigurationModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.dialogs.motor.MotorChooserDialog; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class MotorConfig extends JPanel { - - private final Rocket rocket; - private final MotorMount mount; - private final Configuration configuration; - private JPanel panel; - private JLabel motorLabel; - private static final Translator trans = Application.getTranslator(); - - public MotorConfig(MotorMount motorMount) { - super(new MigLayout("fill")); - - this.rocket = ((RocketComponent) motorMount).getRocket(); - this.mount = motorMount; - this.configuration = ((RocketComponent) motorMount).getRocket().getDefaultConfiguration(); - - BooleanModel model; - - model = new BooleanModel(motorMount, "MotorMount"); - JCheckBox check = new JCheckBox(model); - ////This component is a motor mount - check.setText(trans.get("MotorCfg.checkbox.compmotormount")); - this.add(check, "wrap"); - - - panel = new JPanel(new MigLayout("fill")); - this.add(panel, "grow, wrap"); - - - // Motor configuration selector - //// Motor configuration: - panel.add(new JLabel(trans.get("MotorCfg.lbl.Motorcfg")), "shrink"); - - JComboBox combo = new JComboBox(new MotorConfigurationModel(configuration)); - panel.add(combo, "growx"); - - configuration.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - updateFields(); - } - }); - - //// New button - JButton button = new JButton(trans.get("MotorCfg.but.New")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String id = rocket.newMotorConfigurationID(); - configuration.setMotorConfigurationID(id); - } - }); - panel.add(button, "wrap unrel"); - - - // Current motor: - panel.add(new JLabel(trans.get("MotorCfg.lbl.Currentmotor")), "shrink"); - - motorLabel = new JLabel(); - motorLabel.setFont(motorLabel.getFont().deriveFont(Font.BOLD)); - updateFields(); - panel.add(motorLabel, "wrap unrel"); - - - - // Overhang - //// Motor overhang: - panel.add(new JLabel(trans.get("MotorCfg.lbl.Motoroverhang"))); - - DoubleModel dm = new DoubleModel(motorMount, "MotorOverhang", UnitGroup.UNITS_LENGTH); - - JSpinner spin = new JSpinner(dm.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "span, split, width :65lp:"); - - panel.add(new UnitSelector(dm), "width :30lp:"); - panel.add(new BasicSlider(dm.getSliderModel(-0.02, 0.06)), "w 100lp, wrap unrel"); - - - - // Select ignition event - //// Ignition at: - panel.add(new JLabel(trans.get("MotorCfg.lbl.Ignitionat")), ""); - - combo = new JComboBox(new EnumModel(mount, "IgnitionEvent")); - panel.add(combo, "growx, wrap"); - - // ... and delay - //// plus - panel.add(new JLabel(trans.get("MotorCfg.lbl.plus")), "gap indent, skip 1, span, split"); - - dm = new DoubleModel(mount, "IgnitionDelay", 0); - spin = new JSpinner(dm.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin,3)); - panel.add(spin, "gap rel rel"); - - //// seconds - panel.add(new JLabel(trans.get("MotorCfg.lbl.seconds")), "wrap unrel"); - - - - // Check stage count - RocketComponent c = (RocketComponent) mount; - c = c.getRocket(); - int stages = c.getChildCount(); - - if (stages == 1) { - //// The current design has only one stage. - //// Stages can be added by clicking \"New stage\". - - panel.add(new StyledLabel(trans.get("MotorCfg.lbl.longA1") + " " + - trans.get("MotorCfg.lbl.longA2"), -1), - "spanx, right, wrap para"); - } else { - //// The current design has - //// stages. - panel.add(new StyledLabel(trans.get("MotorCfg.lbl.longB1") + " " + stages + " " + - trans.get("MotorCfg.lbl.longB2"), -1), - "skip 1, spanx, wrap para"); - } - - - // Select etc. buttons - //// Select motor - button = new JButton(trans.get("MotorCfg.but.Selectmotor")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String id = configuration.getMotorConfigurationID(); - - MotorChooserDialog dialog = new MotorChooserDialog(mount.getMotor(id), - mount.getMotorDelay(id), mount.getMotorMountDiameter(), - SwingUtilities.getWindowAncestor(MotorConfig.this)); - dialog.setVisible(true); - Motor m = dialog.getSelectedMotor(); - double d = dialog.getSelectedDelay(); - - if (m != null) { - if (id == null) { - id = rocket.newMotorConfigurationID(); - configuration.setMotorConfigurationID(id); - } - mount.setMotor(id, m); - mount.setMotorDelay(id, d); - } - updateFields(); - } - }); - panel.add(button, "span, split, growx"); - - //// Remove motor - button = new JButton(trans.get("MotorCfg.but.Removemotor")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - mount.setMotor(configuration.getMotorConfigurationID(), null); - updateFields(); - } - }); - panel.add(button, "growx, wrap"); - - - - - - // Set enabled status - - setDeepEnabled(panel, motorMount.isMotorMount()); - check.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - setDeepEnabled(panel, mount.isMotorMount()); - } - }); - - } - - public void updateFields() { - String id = configuration.getMotorConfigurationID(); - Motor m = mount.getMotor(id); - if (m == null) { - //// None - motorLabel.setText(trans.get("MotorCfg.lbl.motorLabel")); - } else { - String str = ""; - if (m instanceof ThrustCurveMotor) - str = ((ThrustCurveMotor) m).getManufacturer() + " "; - str += m.getDesignation(mount.getMotorDelay(id)); - motorLabel.setText(str); - } - } - - - private static void setDeepEnabled(Component component, boolean enabled) { - component.setEnabled(enabled); - if (component instanceof Container) { - for (Component c : ((Container) component).getComponents()) { - setDeepEnabled(c, enabled); - } - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java b/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java deleted file mode 100644 index b1b8d55a..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java +++ /dev/null @@ -1,182 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.ComponentPresetDatabase; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.BooleanModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.PresetModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class NoseConeConfig extends RocketComponentConfig { - - private JComboBox typeBox; - - private DescriptionArea description; - - private JLabel shapeLabel; - private JSpinner shapeSpinner; - private JSlider shapeSlider; - private static final Translator trans = Application.getTranslator(); - - // Prepended to the description from NoseCone.DESCRIPTIONS - private static final String PREDESC = ""; - - public NoseConeConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - DoubleModel m; - JPanel panel = new JPanel(new MigLayout("", "[][65lp::][30lp::]")); - - //// Shape selection - //// Nose cone shape: - panel.add(new JLabel(trans.get("NoseConeCfg.lbl.Noseconeshape"))); - - Transition.Shape selected = ((NoseCone) component).getType(); - Transition.Shape[] typeList = Transition.Shape.values(); - - typeBox = new JComboBox(typeList); - typeBox.setEditable(false); - typeBox.setSelectedItem(selected); - typeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Transition.Shape s = (Transition.Shape) typeBox.getSelectedItem(); - ((NoseCone) component).setType(s); - description.setText(PREDESC + s.getNoseConeDescription()); - updateEnabled(); - } - }); - panel.add(typeBox, "span, wrap rel"); - - - - - //// Shape parameter - //// Shape parameter: - shapeLabel = new JLabel(trans.get("NoseConeCfg.lbl.Shapeparam")); - panel.add(shapeLabel); - - m = new DoubleModel(component, "ShapeParameter"); - - shapeSpinner = new JSpinner(m.getSpinnerModel()); - shapeSpinner.setEditor(new SpinnerEditor(shapeSpinner)); - panel.add(shapeSpinner, "growx"); - - DoubleModel min = new DoubleModel(component, "ShapeParameterMin"); - DoubleModel max = new DoubleModel(component, "ShapeParameterMax"); - shapeSlider = new BasicSlider(m.getSliderModel(min, max)); - panel.add(shapeSlider, "skip, w 100lp, wrap para"); - - updateEnabled(); - - - //// Length - //// Nose cone length: - panel.add(new JLabel(trans.get("NoseConeCfg.lbl.Noseconelength"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 0.7)), "w 100lp, wrap"); - - //// Diameter - //// Base diameter: - panel.add(new JLabel(trans.get("NoseConeCfg.lbl.Basediam"))); - - m = new DoubleModel(component, "AftRadius", 2.0, UnitGroup.UNITS_LENGTH, 0); // Diameter = 2*Radius - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap 0px"); - - JCheckBox check = new JCheckBox(m.getAutomaticAction()); - //// Automatic - check.setText(trans.get("NoseConeCfg.checkbox.Automatic")); - panel.add(check, "skip, span 2, wrap"); - - - //// Wall thickness: - panel.add(new JLabel(trans.get("NoseConeCfg.lbl.Wallthickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap 0px"); - - - check = new JCheckBox(new BooleanModel(component, "Filled")); - //// Filled - check.setText(trans.get("NoseConeCfg.checkbox.Filled")); - panel.add(check, "skip, span 2, wrap"); - - - panel.add(new JLabel(""), "growy"); - - - - //// Description - - JPanel panel2 = new JPanel(new MigLayout("ins 0")); - - description = new DescriptionArea(5); - description.setText(PREDESC + ((NoseCone) component).getType().getNoseConeDescription()); - panel2.add(description, "wmin 250lp, spanx, growx, wrap para"); - - - //// Material - - - materialPanel(panel2, Material.Type.BULK); - panel.add(panel2, "cell 4 0, gapleft paragraph, aligny 0%, spany"); - - - //// General and General properties - tabbedPane.insertTab(trans.get("NoseConeCfg.tab.General"), null, panel, - trans.get("NoseConeCfg.tab.ttip.General"), 0); - //// Shoulder and Shoulder properties - tabbedPane.insertTab(trans.get("NoseConeCfg.tab.Shoulder"), null, shoulderTab(), - trans.get("NoseConeCfg.tab.ttip.Shoulder"), 1); - tabbedPane.setSelectedIndex(0); - } - - - private void updateEnabled() { - boolean e = ((NoseCone) component).getType().usesParameter(); - shapeLabel.setEnabled(e); - shapeSpinner.setEnabled(e); - shapeSlider.setEnabled(e); - } - - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java b/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java deleted file mode 100644 index 1e767a78..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java +++ /dev/null @@ -1,288 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.IntegerModel; -import net.sf.openrocket.gui.adaptors.MaterialModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.HtmlLabel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class ParachuteConfig extends RecoveryDeviceConfig { - private static final Translator trans = Application.getTranslator(); - - public ParachuteConfig(OpenRocketDocument d, final RocketComponent component) { - super(d, component); - - JPanel primary = new JPanel(new MigLayout()); - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - - //// Canopy - panel.add(new StyledLabel(trans.get("ParachuteCfg.lbl.Canopy"), Style.BOLD), "wrap unrel"); - - //// Diameter: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Diameter"))); - - DoubleModel m = new DoubleModel(component, "Diameter", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.4, 1.5)), "w 100lp, wrap"); - - // CD - JLabel label = new HtmlLabel(trans.get("ParachuteCfg.lbl.longA1")); - String tip = trans.get("ParachuteCfg.lbl.longB1") + - trans.get("ParachuteCfg.lbl.longB2") + " " + - trans.get("ParachuteCfg.lbl.longB3"); - label.setToolTipText(tip); - panel.add(label); - - m = new DoubleModel(component, "CD", UnitGroup.UNITS_COEFFICIENT, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setToolTipText(tip); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - //// Reset button - JButton button = new JButton(trans.get("ParachuteCfg.but.Reset")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Parachute p = (Parachute) component; - p.setCD(Parachute.DEFAULT_CD); - } - }); - panel.add(button, "spanx, wrap para"); - - //// Material: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Material"))); - - JComboBox combo = new JComboBox(new MaterialModel(panel, component, - Material.Type.SURFACE)); - combo.setToolTipText(trans.get("ParachuteCfg.combo.MaterialModel")); - panel.add(combo, "spanx 3, growx, wrap 30lp"); - - - - - //// Shroud lines - panel.add(new StyledLabel(trans.get("ParachuteCfg.lbl.Shroudlines"), Style.BOLD), "wrap unrel"); - - //// Number of lines: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Numberoflines"))); - IntegerModel im = new IntegerModel(component, "LineCount", 0); - - spin = new JSpinner(im.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx, wrap"); - - //// Line length: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Linelength"))); - - m = new DoubleModel(component, "LineLength", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.4, 1.5)), "w 100lp, wrap"); - - //// Material: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Material"))); - - combo = new JComboBox(new MaterialModel(panel, component, Material.Type.LINE, - "LineMaterial")); - panel.add(combo, "spanx 3, growx, wrap"); - - - - primary.add(panel, "grow, gapright 20lp"); - panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - - - - //// Position - //// Position relative to: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Posrelativeto"))); - - combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx, growx, wrap"); - - //// plus - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap"); - - - //// Spatial length - //// Packed length: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Packedlength"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 0.5)), "w 100lp, wrap"); - - - //// Tube diameter - //// Packed diameter: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Packeddiam"))); - - DoubleModel od = new DoubleModel(component, "Radius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap 30lp"); - - - //// Deployment - //// Deploys at: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Deploysat")), ""); - - combo = new JComboBox(new EnumModel(component, "DeployEvent")); - panel.add(combo, "spanx 3, growx, wrap"); - - // ... and delay - //// plus - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.plusdelay")), "right"); - - m = new DoubleModel(component, "DeployDelay", 0); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin,3)); - panel.add(spin, "spanx, split"); - - //// seconds - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.seconds")), "wrap paragraph"); - - // Altitude: - label = new JLabel(trans.get("ParachuteCfg.lbl.Altitude")); - altitudeComponents.add(label); - panel.add(label); - - m = new DoubleModel(component, "DeployAltitude", UnitGroup.UNITS_DISTANCE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - altitudeComponents.add(spin); - panel.add(spin, "growx"); - UnitSelector unit = new UnitSelector(m); - altitudeComponents.add(unit); - panel.add(unit, "growx"); - BasicSlider slider = new BasicSlider(m.getSliderModel(100, 1000)); - altitudeComponents.add(slider); - panel.add(slider, "w 100lp, wrap"); - - - primary.add(panel, "grow"); - - updateFields(); - - //// General and General properties - tabbedPane.insertTab(trans.get("ParachuteCfg.tab.General"), null, primary, trans.get("ParachuteCfg.tab.ttip.General"), 0); - //// Radial position and Radial position configuration - tabbedPane.insertTab(trans.get("ParachuteCfg.tab.Radialpos"), null, positionTab(), - trans.get("ParachuteCfg.tab.ttip.Radialpos"), 1); - tabbedPane.setSelectedIndex(0); - } - - - - - - protected JPanel positionTab() { - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - //// Radial position - //// Radial distance: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Radialdistance"))); - - DoubleModel m = new DoubleModel(component, "RadialPosition", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 1.0)), "w 100lp, wrap"); - - - //// Radial direction: - panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Radialdirection"))); - - m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - //// Reset button - JButton button = new JButton(trans.get("ParachuteCfg.but.Reset")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ((MassObject) component).setRadialDirection(0.0); - ((MassObject) component).setRadialPosition(0.0); - } - }); - panel.add(button, "spanx, right"); - - return panel; - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/RecoveryDeviceConfig.java b/core/src/net/sf/openrocket/gui/configdialog/RecoveryDeviceConfig.java deleted file mode 100644 index f93613c9..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/RecoveryDeviceConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JComponent; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RocketComponent; - - -public abstract class RecoveryDeviceConfig extends RocketComponentConfig { - - protected final List altitudeComponents = new ArrayList(); - - public RecoveryDeviceConfig(OpenRocketDocument d, RocketComponent component) { - super(d, component); - } - - - - @Override - public void updateFields() { - super.updateFields(); - - if (altitudeComponents == null) - return; - - boolean enabled = (((RecoveryDevice) component).getDeployEvent() - == RecoveryDevice.DeployEvent.ALTITUDE); - - for (JComponent c : altitudeComponents) { - c.setEnabled(enabled); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java b/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java deleted file mode 100644 index 80363300..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java +++ /dev/null @@ -1,243 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class RingComponentConfig extends RocketComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public RingComponentConfig(OpenRocketDocument d, RocketComponent component) { - super(d, component); - } - - - protected JPanel generalTab(String outer, String inner, String thickness, String length) { - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - DoubleModel m; - JSpinner spin; - DoubleModel od = null; - - - //// Outer diameter - if (outer != null) { - panel.add(new JLabel(outer)); - - //// OuterRadius - od = new DoubleModel(component, "OuterRadius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap"); - - if (od.isAutomaticAvailable()) { - JCheckBox check = new JCheckBox(od.getAutomaticAction()); - //// Automatic - check.setText(trans.get("ringcompcfg.Automatic")); - panel.add(check, "skip, span 2, wrap"); - } - } - - - //// Inner diameter - if (inner != null) { - panel.add(new JLabel(inner)); - - //// InnerRadius - m = new DoubleModel(component, "InnerRadius", 2, UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - if (od == null) - panel.add(new BasicSlider(m.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap"); - else - panel.add(new BasicSlider(m.getSliderModel(new DoubleModel(0), od)), - "w 100lp, wrap"); - - if (m.isAutomaticAvailable()) { - JCheckBox check = new JCheckBox(m.getAutomaticAction()); - //// Automatic - check.setText(trans.get("ringcompcfg.Automatic")); - panel.add(check, "skip, span 2, wrap"); - } - } - - - //// Wall thickness - if (thickness != null) { - panel.add(new JLabel(thickness)); - - //// Thickness - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap"); - } - - - //// Inner tube length - if (length != null) { - panel.add(new JLabel(length)); - - //// Length - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 1.0)), "w 100lp, wrap"); - } - - - //// Position - - //// Position relative to: - panel.add(new JLabel(trans.get("ringcompcfg.Positionrelativeto"))); - - JComboBox combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx 3, growx, wrap"); - - //// plus - panel.add(new JLabel(trans.get("ringcompcfg.plus")), "right"); - - //// PositionValue - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap"); - - - //// Material - JPanel sub = materialPanel(new JPanel(new MigLayout()), Material.Type.BULK); - - if (component instanceof EngineBlock) { - final DescriptionArea desc = new DescriptionArea(6); - //// An engine block stops the motor from moving forwards in the motor mount tube.

In order to add a motor, create a body tube or inner tube and mark it as a motor mount in the Motor tab. - desc.setText(trans.get("ringcompcfg.EngineBlock.desc")); - sub.add(desc, "width 1px, growx, wrap"); - } - panel.add(sub, "cell 4 0, gapleft paragraph, aligny 0%, spany"); - - return panel; - } - - - protected JPanel positionTab() { - JPanel panel = new JPanel(new MigLayout("align 20% 20%, gap rel unrel", - "[][65lp::][30lp::]", "")); - - //// Radial position - JLabel l = new JLabel(trans.get("ringcompcfg.Radialdistance")); - //// Distance from the rocket centerline - l.setToolTipText(trans.get("ringcompcfg.Distancefrom")); - panel.add(l); - - DoubleModel m = new DoubleModel(component, "RadialPosition", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - //// Distance from the rocket centerline - spin.setToolTipText(trans.get("ringcompcfg.Distancefrom")); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - BasicSlider bs = new BasicSlider(m.getSliderModel(0, 0.1, 1.0)); - //// Distance from the rocket centerline - bs.setToolTipText(trans.get("ringcompcfg.Distancefrom")); - panel.add(bs, "w 100lp, wrap"); - - - //// Radial direction - l = new JLabel(trans.get("ringcompcfg.Radialdirection")); - //// The radial direction from the rocket centerline - l.setToolTipText(trans.get("ringcompcfg.radialdirectionfrom")); - panel.add(l); - - m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - //// The radial direction from the rocket centerline - spin.setToolTipText(trans.get("ringcompcfg.radialdirectionfrom")); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - bs = new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)); - //// The radial direction from the rocket centerline - bs.setToolTipText(trans.get("ringcompcfg.radialdirectionfrom")); - panel.add(bs, "w 100lp, wrap"); - - - //// Reset button - JButton button = new JButton(trans.get("ringcompcfg.but.Reset")); - //// Reset the component to the rocket centerline - button.setToolTipText(trans.get("ringcompcfg.but.Resetcomponant")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ((RingComponent) component).setRadialDirection(0.0); - ((RingComponent) component).setRadialPosition(0.0); - } - }); - panel.add(button, "spanx, right, wrap para"); - - - DescriptionArea note = new DescriptionArea(3); - //// Note: An inner tube will not affect the aerodynamics of the rocket even if it is located outside of the body tube. - note.setText(trans.get("ringcompcfg.note.desc")); - panel.add(note, "spanx, growx"); - - - return panel; - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/RocketComponentConfig.java b/core/src/net/sf/openrocket/gui/configdialog/RocketComponentConfig.java deleted file mode 100644 index c2fbd63e..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/RocketComponentConfig.java +++ /dev/null @@ -1,663 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JColorChooser; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTabbedPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.ComponentPresetDatabase; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.BooleanModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.MaterialModel; -import net.sf.openrocket.gui.adaptors.PresetModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.ColorIcon; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.util.ColorConversion; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.ComponentAssembly; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Invalidatable; -import net.sf.openrocket.util.LineStyle; - -public class RocketComponentConfig extends JPanel { - - private static final Translator trans = Application.getTranslator(); - - protected final OpenRocketDocument document; - protected final RocketComponent component; - protected final JTabbedPane tabbedPane; - - private final List invalidatables = new ArrayList(); - - private JComboBox presetComboBox; - private PresetModel presetModel; - - protected final JTextField componentNameField; - protected JTextArea commentTextArea; - private final TextFieldListener textFieldListener; - private JButton colorButton; - private JCheckBox colorDefault; - private JPanel buttonPanel; - - private JLabel infoLabel; - - - public RocketComponentConfig(OpenRocketDocument document, RocketComponent component) { - setLayout(new MigLayout("fill", "[min,align right]:10[fill, grow]")); - this.document = document; - this.component = component; - - //// Component name: - JLabel label = new JLabel(trans.get("RocketCompCfg.lbl.Componentname")); - //// The component name. - label.setToolTipText(trans.get("RocketCompCfg.ttip.Thecomponentname")); - this.add(label, "spanx, split"); - - componentNameField = new JTextField(15); - textFieldListener = new TextFieldListener(); - componentNameField.addActionListener(textFieldListener); - componentNameField.addFocusListener(textFieldListener); - //// The component name. - componentNameField.setToolTipText(trans.get("RocketCompCfg.ttip.Thecomponentname")); - this.add(componentNameField, "growx"); - - if (component.getPresetType() != null) { - // If the component supports a preset, show the preset selection box. - presetModel = new PresetModel(this, document, component); - ((ComponentPresetDatabase) Application.getComponentPresetDao()).addDatabaseListener(presetModel); - presetComboBox = new JComboBox(presetModel); - presetComboBox.setEditable(false); - this.add(presetComboBox, ""); - } - - - tabbedPane = new JTabbedPane(); - this.add(tabbedPane, "newline, span, growx, growy 1, wrap"); - - //// Override and Mass and CG override options - tabbedPane.addTab(trans.get("RocketCompCfg.tab.Override"), null, overrideTab(), - trans.get("RocketCompCfg.tab.MassandCGoverride")); - if (component.isMassive()) - //// Figure and Figure style options - tabbedPane.addTab(trans.get("RocketCompCfg.tab.Figure"), null, figureTab(), - trans.get("RocketCompCfg.tab.Figstyleopt")); - //// Comment and Specify a comment for the component - tabbedPane.addTab(trans.get("RocketCompCfg.tab.Comment"), null, commentTab(), - trans.get("RocketCompCfg.tab.Specifyacomment")); - - addButtons(); - - updateFields(); - } - - - protected void addButtons(JButton... buttons) { - if (buttonPanel != null) { - this.remove(buttonPanel); - } - - buttonPanel = new JPanel(new MigLayout("fill, ins 0")); - - //// Mass: - infoLabel = new StyledLabel(" ", -1); - buttonPanel.add(infoLabel, "growx"); - - for (JButton b : buttons) { - buttonPanel.add(b, "right, gap para"); - } - - //// Close button - JButton closeButton = new JButton(trans.get("dlg.but.close")); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - ComponentConfigDialog.hideDialog(); - } - }); - buttonPanel.add(closeButton, "right, gap 30lp"); - - updateFields(); - - this.add(buttonPanel, "spanx, growx"); - } - - - /** - * Called when a change occurs, so that the fields can be updated if necessary. - * When overriding this method, the supermethod must always be called. - */ - public void updateFields() { - // Component name - componentNameField.setText(component.getName()); - - // Component color and "Use default color" checkbox - if (colorButton != null && colorDefault != null) { - colorButton.setIcon(new ColorIcon(getColor())); - - if ((component.getColor() == null) != colorDefault.isSelected()) - colorDefault.setSelected(component.getColor() == null); - } - - // Info label - StringBuilder sb = new StringBuilder(); - - if (component.getPresetComponent() != null) { - ComponentPreset preset = component.getPresetComponent(); - sb.append(preset.getManufacturer() + " " + preset.getPartNo() + " "); - } - - if (component.isMassive()) { - sb.append(trans.get("RocketCompCfg.lbl.Componentmass") + " "); - sb.append(UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit( - component.getComponentMass())); - - String overridetext = null; - if (component.isMassOverridden()) { - overridetext = trans.get("RocketCompCfg.lbl.overriddento") + " " + UnitGroup.UNITS_MASS.getDefaultUnit(). - toStringUnit(component.getOverrideMass()) + ")"; - } - - for (RocketComponent c = component.getParent(); c != null; c = c.getParent()) { - if (c.isMassOverridden() && c.getOverrideSubcomponents()) { - overridetext = trans.get("RocketCompCfg.lbl.overriddenby") + " " + c.getName() + ")"; - } - } - - if (overridetext != null) { - sb.append(" " + overridetext); - } - - infoLabel.setText(sb.toString()); - } else { - infoLabel.setText(""); - } - } - - - protected JPanel materialPanel(JPanel panel, Material.Type type) { - ////Component material: and Component finish: - return materialPanel(panel, type, trans.get("RocketCompCfg.lbl.Componentmaterial"), - trans.get("RocketCompCfg.lbl.Componentfinish")); - } - - protected JPanel materialPanel(JPanel panel, Material.Type type, - String materialString, String finishString) { - - JLabel label = new JLabel(materialString); - //// The component material affects the weight of the component. - label.setToolTipText(trans.get("RocketCompCfg.lbl.ttip.componentmaterialaffects")); - panel.add(label, "spanx 4, wrap rel"); - - JComboBox combo = new JComboBox(new MaterialModel(panel, component, type)); - //// The component material affects the weight of the component. - combo.setToolTipText(trans.get("RocketCompCfg.combo.ttip.componentmaterialaffects")); - panel.add(combo, "spanx 4, growx, wrap paragraph"); - - - if (component instanceof ExternalComponent) { - label = new JLabel(finishString); - ////The component finish affects the aerodynamic drag of the component.
- String tip = trans.get("RocketCompCfg.lbl.longA1") - //// The value indicated is the average roughness height of the surface. - + trans.get("RocketCompCfg.lbl.longA2"); - label.setToolTipText(tip); - panel.add(label, "spanx 4, wmin 220lp, wrap rel"); - - combo = new JComboBox(new EnumModel(component, "Finish")); - combo.setToolTipText(tip); - panel.add(combo, "spanx 4, growx, split"); - - //// Set for all - JButton button = new JButton(trans.get("RocketCompCfg.but.Setforall")); - //// Set this finish for all components of the rocket. - button.setToolTipText(trans.get("RocketCompCfg.but.ttip.Setforall")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Finish f = ((ExternalComponent) component).getFinish(); - try { - document.startUndo("Set rocket finish"); - - // Do changes - Iterator iter = component.getRoot().iterator(); - while (iter.hasNext()) { - RocketComponent c = iter.next(); - if (c instanceof ExternalComponent) { - ((ExternalComponent) c).setFinish(f); - } - } - } finally { - document.stopUndo(); - } - } - }); - panel.add(button, "wrap paragraph"); - } - - return panel; - } - - - private JPanel overrideTab() { - JPanel panel = new JPanel(new MigLayout("align 50% 20%, fillx, gap rel unrel", - "[][65lp::][30lp::][]", "")); - //// Override the mass or center of gravity of the - panel.add(new StyledLabel(trans.get("RocketCompCfg.lbl.Overridemassorcenter") + " " + - component.getComponentName() + ":", Style.BOLD), "spanx, wrap 20lp"); - - JCheckBox check; - BooleanModel bm; - UnitSelector us; - BasicSlider bs; - - //// Mass - bm = new BooleanModel(component, "MassOverridden"); - check = new JCheckBox(bm); - //// Override mass: - check.setText(trans.get("RocketCompCfg.checkbox.Overridemass")); - panel.add(check, "growx 1, gapright 20lp"); - - DoubleModel m = new DoubleModel(component, "OverrideMass", UnitGroup.UNITS_MASS, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - bm.addEnableComponent(spin, true); - panel.add(spin, "growx 1"); - - us = new UnitSelector(m); - bm.addEnableComponent(us, true); - panel.add(us, "growx 1"); - - bs = new BasicSlider(m.getSliderModel(0, 0.03, 1.0)); - bm.addEnableComponent(bs); - panel.add(bs, "growx 5, w 100lp, wrap"); - - - //// CG override - bm = new BooleanModel(component, "CGOverridden"); - check = new JCheckBox(bm); - //// Override center of gravity:" - check.setText(trans.get("RocketCompCfg.checkbox.Overridecenterofgrav")); - panel.add(check, "growx 1, gapright 20lp"); - - m = new DoubleModel(component, "OverrideCGX", UnitGroup.UNITS_LENGTH, 0); - // Calculate suitable length for slider - DoubleModel length; - if (component instanceof ComponentAssembly) { - double l = 0; - - Iterator iterator = component.iterator(false); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - if (c.getRelativePosition() == RocketComponent.Position.AFTER) - l += c.getLength(); - } - length = new DoubleModel(l); - } else { - length = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - } - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - bm.addEnableComponent(spin, true); - panel.add(spin, "growx 1"); - - us = new UnitSelector(m); - bm.addEnableComponent(us, true); - panel.add(us, "growx 1"); - - bs = new BasicSlider(m.getSliderModel(new DoubleModel(0), length)); - bm.addEnableComponent(bs); - panel.add(bs, "growx 5, w 100lp, wrap 35lp"); - - - // Override subcomponents checkbox - bm = new BooleanModel(component, "OverrideSubcomponents"); - check = new JCheckBox(bm); - //// Override mass and CG of all subcomponents - check.setText(trans.get("RocketCompCfg.checkbox.OverridemassandCG")); - panel.add(check, "gap para, spanx, wrap para"); - - //// The overridden mass does not include motors.
- panel.add(new StyledLabel(trans.get("RocketCompCfg.lbl.longB1") + - //// The center of gravity is measured from the front end of the - trans.get("RocketCompCfg.lbl.longB2") + " " + - component.getComponentName().toLowerCase(Locale.getDefault()) + ".", -1), - "spanx, wrap, gap para, height 0::30lp"); - - return panel; - } - - - private JPanel commentTab() { - JPanel panel = new JPanel(new MigLayout("fill")); - - //// Comments on the - panel.add(new StyledLabel(trans.get("RocketCompCfg.lbl.Commentsonthe") + " " + component.getComponentName() + ":", - Style.BOLD), "wrap"); - - // TODO: LOW: Changes in comment from other sources not reflected in component - commentTextArea = new JTextArea(component.getComment()); - commentTextArea.setLineWrap(true); - commentTextArea.setWrapStyleWord(true); - commentTextArea.setEditable(true); - GUIUtil.setTabToFocusing(commentTextArea); - commentTextArea.addFocusListener(textFieldListener); - - panel.add(new JScrollPane(commentTextArea), "width 10px, height 10px, growx, growy"); - - return panel; - } - - - - private JPanel figureTab() { - JPanel panel = new JPanel(new MigLayout("align 20% 20%")); - - //// Figure style: - panel.add(new StyledLabel(trans.get("RocketCompCfg.lbl.Figurestyle"), Style.BOLD), "wrap para"); - - //// Component color: - panel.add(new JLabel(trans.get("RocketCompCfg.lbl.Componentcolor")), "gapleft para, gapright 10lp"); - - colorButton = new JButton(new ColorIcon(getColor())); - colorButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - net.sf.openrocket.util.Color c = component.getColor(); - if (c == null) { - c = Application.getPreferences().getDefaultColor(component.getClass()); - } - - //// Choose color - Color awtColor = ColorConversion.toAwtColor(c); - awtColor = JColorChooser.showDialog(tabbedPane, trans.get("RocketCompCfg.lbl.Choosecolor"), awtColor); - c = ColorConversion.fromAwtColor(awtColor); - if (c != null) { - component.setColor(c); - } - } - }); - panel.add(colorButton, "gapright 10lp"); - - //// Use default color - colorDefault = new JCheckBox(trans.get("RocketCompCfg.checkbox.Usedefaultcolor")); - if (component.getColor() == null) - colorDefault.setSelected(true); - colorDefault.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (colorDefault.isSelected()) - component.setColor(null); - else - component.setColor(((SwingPreferences) Application.getPreferences()).getDefaultColor(component.getClass())); - } - }); - panel.add(colorDefault, "wrap para"); - - //// Component line style: - panel.add(new JLabel(trans.get("RocketCompCfg.lbl.Complinestyle")), "gapleft para, gapright 10lp"); - - LineStyle[] list = new LineStyle[LineStyle.values().length + 1]; - System.arraycopy(LineStyle.values(), 0, list, 1, LineStyle.values().length); - - JComboBox combo = new JComboBox(new EnumModel(component, "LineStyle", - //// Default style - list, trans.get("LineStyle.Defaultstyle"))); - panel.add(combo, "spanx 2, growx, wrap 50lp"); - - //// Save as default style - JButton button = new JButton(trans.get("RocketCompCfg.but.Saveasdefstyle")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (component.getColor() != null) { - ((SwingPreferences) Application.getPreferences()).setDefaultColor(component.getClass(), component.getColor()); - component.setColor(null); - } - if (component.getLineStyle() != null) { - Application.getPreferences().setDefaultLineStyle(component.getClass(), component.getLineStyle()); - component.setLineStyle(null); - } - } - }); - panel.add(button, "gapleft para, spanx 3, growx, wrap"); - - return panel; - } - - - private Color getColor() { - net.sf.openrocket.util.Color c = component.getColor(); - if (c == null) { - c = Application.getPreferences().getDefaultColor(component.getClass()); - } - return ColorConversion.toAwtColor(c); - } - - - - protected JPanel shoulderTab() { - JPanel panel = new JPanel(new MigLayout("fill")); - JPanel sub; - DoubleModel m, m2; - DoubleModel m0 = new DoubleModel(0); - BooleanModel bm; - JCheckBox check; - JSpinner spin; - - - //// Fore shoulder, not for NoseCone - - if (!(component instanceof NoseCone)) { - sub = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - //// Fore shoulder - sub.setBorder(BorderFactory.createTitledBorder(trans.get("RocketCompCfg.border.Foreshoulder"))); - - - //// Radius - //// Diameter: - sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Diameter"))); - - m = new DoubleModel(component, "ForeShoulderRadius", 2, UnitGroup.UNITS_LENGTH, 0); - m2 = new DoubleModel(component, "ForeRadius", 2, UnitGroup.UNITS_LENGTH); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - sub.add(spin, "growx"); - - sub.add(new UnitSelector(m), "growx"); - sub.add(new BasicSlider(m.getSliderModel(m0, m2)), "w 100lp, wrap"); - - - //// Length: - sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Length"))); - - m = new DoubleModel(component, "ForeShoulderLength", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - sub.add(spin, "growx"); - - sub.add(new UnitSelector(m), "growx"); - sub.add(new BasicSlider(m.getSliderModel(0, 0.02, 0.2)), "w 100lp, wrap"); - - - //// Thickness: - sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Thickness"))); - - m = new DoubleModel(component, "ForeShoulderThickness", UnitGroup.UNITS_LENGTH, 0); - m2 = new DoubleModel(component, "ForeShoulderRadius", UnitGroup.UNITS_LENGTH); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - sub.add(spin, "growx"); - - sub.add(new UnitSelector(m), "growx"); - sub.add(new BasicSlider(m.getSliderModel(m0, m2)), "w 100lp, wrap"); - - - //// Capped - bm = new BooleanModel(component, "ForeShoulderCapped"); - check = new JCheckBox(bm); - //// End capped - check.setText(trans.get("RocketCompCfg.checkbox.Endcapped")); - //// Whether the end of the shoulder is capped. - check.setToolTipText(trans.get("RocketCompCfg.ttip.Endcapped")); - sub.add(check, "spanx"); - - - panel.add(sub); - } - - - //// Aft shoulder - sub = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - if (component instanceof NoseCone) - //// Nose cone shoulder - sub.setBorder(BorderFactory.createTitledBorder(trans.get("RocketCompCfg.title.Noseconeshoulder"))); - else - //// Aft shoulder - sub.setBorder(BorderFactory.createTitledBorder(trans.get("RocketCompCfg.title.Aftshoulder"))); - - - //// Radius - //// Diameter: - sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Diameter"))); - - m = new DoubleModel(component, "AftShoulderRadius", 2, UnitGroup.UNITS_LENGTH, 0); - m2 = new DoubleModel(component, "AftRadius", 2, UnitGroup.UNITS_LENGTH); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - sub.add(spin, "growx"); - - sub.add(new UnitSelector(m), "growx"); - sub.add(new BasicSlider(m.getSliderModel(m0, m2)), "w 100lp, wrap"); - - - //// Length: - sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Length"))); - - m = new DoubleModel(component, "AftShoulderLength", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - sub.add(spin, "growx"); - - sub.add(new UnitSelector(m), "growx"); - sub.add(new BasicSlider(m.getSliderModel(0, 0.02, 0.2)), "w 100lp, wrap"); - - - //// Thickness: - sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Thickness"))); - - m = new DoubleModel(component, "AftShoulderThickness", UnitGroup.UNITS_LENGTH, 0); - m2 = new DoubleModel(component, "AftShoulderRadius", UnitGroup.UNITS_LENGTH); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - sub.add(spin, "growx"); - - sub.add(new UnitSelector(m), "growx"); - sub.add(new BasicSlider(m.getSliderModel(m0, m2)), "w 100lp, wrap"); - - - //// Capped - bm = new BooleanModel(component, "AftShoulderCapped"); - check = new JCheckBox(bm); - //// End capped - check.setText(trans.get("RocketCompCfg.checkbox.Endcapped")); - //// Whether the end of the shoulder is capped. - check.setToolTipText(trans.get("RocketCompCfg.ttip.Endcapped")); - sub.add(check, "spanx"); - - - panel.add(sub); - - - return panel; - } - - - - - /* - * Private inner class to handle events in componentNameField. - */ - private class TextFieldListener implements ActionListener, FocusListener { - @Override - public void actionPerformed(ActionEvent e) { - setName(); - } - - @Override - public void focusGained(FocusEvent e) { - } - - @Override - public void focusLost(FocusEvent e) { - setName(); - } - - private void setName() { - if (!component.getName().equals(componentNameField.getText())) { - component.setName(componentNameField.getText()); - } - if (!component.getComment().equals(commentTextArea.getText())) { - component.setComment(commentTextArea.getText()); - } - } - } - - - protected void register(Invalidatable model) { - this.invalidatables.add(model); - } - - public void invalidateModels() { - for (Invalidatable i : invalidatables) { - i.invalidate(); - } - ((ComponentPresetDatabase) Application.getComponentPresetDao()).removeChangeListener(presetModel); - - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/configdialog/RocketConfig.java b/core/src/net/sf/openrocket/gui/configdialog/RocketConfig.java deleted file mode 100644 index c692f498..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/RocketConfig.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; - -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - -public class RocketConfig extends RocketComponentConfig { - private static final Translator trans = Application.getTranslator(); - - private TextFieldListener textFieldListener; - - private JTextArea designerTextArea; - private JTextArea revisionTextArea; - - private final Rocket rocket; - - public RocketConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - rocket = (Rocket) c; - - this.removeAll(); - setLayout(new MigLayout("fill")); - - //// Design name: - this.add(new JLabel(trans.get("RocketCfg.lbl.Designname")), "top, pad 4lp, gapright 10lp"); - this.add(componentNameField, "growx, wrap para"); - - //// Designer: - this.add(new JLabel(trans.get("RocketCfg.lbl.Designer")), "top, pad 4lp, gapright 10lp"); - - textFieldListener = new TextFieldListener(); - designerTextArea = new JTextArea(rocket.getDesigner()); - designerTextArea.setLineWrap(true); - designerTextArea.setWrapStyleWord(true); - designerTextArea.setEditable(true); - GUIUtil.setTabToFocusing(designerTextArea); - designerTextArea.addFocusListener(textFieldListener); - this.add(new JScrollPane(designerTextArea), "wmin 400lp, height 60lp:60lp:, grow 30, wrap para"); - - //// Comments: - this.add(new JLabel(trans.get("RocketCfg.lbl.Comments")), "top, pad 4lp, gapright 10lp"); - this.add(new JScrollPane(commentTextArea), "wmin 400lp, height 155lp:155lp:, grow 100, wrap para"); - - //// Revision history: - this.add(new JLabel(trans.get("RocketCfg.lbl.Revisionhistory")), "top, pad 4lp, gapright 10lp"); - revisionTextArea = new JTextArea(rocket.getRevision()); - revisionTextArea.setLineWrap(true); - revisionTextArea.setWrapStyleWord(true); - revisionTextArea.setEditable(true); - GUIUtil.setTabToFocusing(revisionTextArea); - revisionTextArea.addFocusListener(textFieldListener); - - this.add(new JScrollPane(revisionTextArea), "wmin 400lp, height 60lp:60lp:, grow 30, wrap para"); - - - addButtons(); - } - - - - private class TextFieldListener implements ActionListener, FocusListener { - @Override - public void actionPerformed(ActionEvent e) { - setName(); - } - - @Override - public void focusGained(FocusEvent e) { - } - - @Override - public void focusLost(FocusEvent e) { - setName(); - } - - private void setName() { - if (!rocket.getDesigner().equals(designerTextArea.getText())) { - rocket.setDesigner(designerTextArea.getText()); - } - if (!rocket.getRevision().equals(revisionTextArea.getText())) { - rocket.setRevision(revisionTextArea.getText()); - } - } - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/ShockCordConfig.java b/core/src/net/sf/openrocket/gui/configdialog/ShockCordConfig.java deleted file mode 100644 index fbc99f85..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/ShockCordConfig.java +++ /dev/null @@ -1,130 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class ShockCordConfig extends RocketComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public ShockCordConfig(OpenRocketDocument d, RocketComponent component) { - super(d, component); - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - JLabel label; - DoubleModel m; - JSpinner spin; - String tip; - - - ////// Left side - - // Cord length - //// Shock cord length - label = new JLabel(trans.get("ShockCordCfg.lbl.Shockcordlength")); - panel.add(label); - - m = new DoubleModel(component, "CordLength", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 1, 10)), "w 100lp, wrap"); - - - // Material - //// Shock cord material: - materialPanel(panel, Material.Type.LINE, trans.get("ShockCordCfg.lbl.Shockcordmaterial"), null); - - - - ///// Right side - JPanel panel2 = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - panel.add(panel2, "cell 4 0, gapleft paragraph, aligny 0%, spany"); - - - //// Position - //// Position relative to: - panel2.add(new JLabel(trans.get("ShockCordCfg.lbl.Posrelativeto"))); - - JComboBox combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel2.add(combo, "spanx, growx, wrap"); - - //// plus - panel2.add(new JLabel(trans.get("ShockCordCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel2.add(spin, "growx"); - - panel2.add(new UnitSelector(m), "growx"); - panel2.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap"); - - - //// Spatial length - //// Packed length: - panel2.add(new JLabel(trans.get("ShockCordCfg.lbl.Packedlength"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel2.add(spin, "growx"); - - panel2.add(new UnitSelector(m), "growx"); - panel2.add(new BasicSlider(m.getSliderModel(0, 0.1, 0.5)), "w 100lp, wrap"); - - - //// Tube diameter - //// Packed diameter: - panel2.add(new JLabel(trans.get("ShockCordCfg.lbl.Packeddiam"))); - - DoubleModel od = new DoubleModel(component, "Radius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel2.add(spin, "growx"); - - panel2.add(new UnitSelector(od), "growx"); - panel2.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap"); - - - - //// General and General properties - tabbedPane.insertTab(trans.get("ShockCordCfg.tab.General"), null, panel, trans.get("ShockCordCfg.tab.ttip.General"), 0); - // tabbedPane.insertTab("Radial position", null, positionTab(), - // "Radial position configuration", 1); - tabbedPane.setSelectedIndex(0); - } - - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/SleeveConfig.java b/core/src/net/sf/openrocket/gui/configdialog/SleeveConfig.java deleted file mode 100644 index 32192765..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/SleeveConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JPanel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - - - -public class SleeveConfig extends RingComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public SleeveConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel tab; - //// Outer diameter: - //// Inner diameter: - //// Wall thickness: - //// Length: - tab = generalTab(trans.get("SleeveCfg.tab.Outerdiam"), trans.get("SleeveCfg.tab.Innerdiam"), - trans.get("SleeveCfg.tab.Wallthickness"), trans.get("SleeveCfg.tab.Length")); - //// General and General properties - tabbedPane.insertTab(trans.get("SleeveCfg.tab.General"), null, tab, - trans.get("SleeveCfg.tab.Generalproperties"), 0); - tabbedPane.setSelectedIndex(0); - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/configdialog/StageConfig.java b/core/src/net/sf/openrocket/gui/configdialog/StageConfig.java deleted file mode 100644 index 21817297..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/StageConfig.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Stage.SeparationEvent; -import net.sf.openrocket.startup.Application; - -public class StageConfig extends RocketComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public StageConfig(OpenRocketDocument document, RocketComponent component) { - super(document, component); - - // Stage separation config (for non-first stage) - if (component.getStageNumber() > 0) { - JPanel tab = separationTab((Stage) component); - tabbedPane.insertTab(trans.get("tab.Separation"), null, tab, - trans.get("tab.Separation.ttip"), 1); - } - - } - - - private JPanel separationTab(Stage stage) { - JPanel panel = new JPanel(new MigLayout("fill")); - - // Select separation event - panel.add(new StyledLabel(trans.get("separation.lbl.title"), Style.BOLD), "spanx, wrap rel"); - - JComboBox combo = new JComboBox(new EnumModel(stage, "SeparationEvent")); - panel.add(combo, ""); - - // ... and delay - panel.add(new JLabel(trans.get("separation.lbl.plus")), ""); - - DoubleModel dm = new DoubleModel(stage, "SeparationDelay", 0); - JSpinner spin = new JSpinner(dm.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, ""); - - //// seconds - panel.add(new JLabel(trans.get("separation.lbl.seconds")), "wrap unrel"); - - return panel; - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/StreamerConfig.java b/core/src/net/sf/openrocket/gui/configdialog/StreamerConfig.java deleted file mode 100644 index 49137045..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/StreamerConfig.java +++ /dev/null @@ -1,291 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.MaterialModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.HtmlLabel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class StreamerConfig extends RecoveryDeviceConfig { - private static final Translator trans = Application.getTranslator(); - - public StreamerConfig(OpenRocketDocument d, final RocketComponent component) { - super(d, component); - - JPanel primary = new JPanel(new MigLayout()); - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - - //// Strip length: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Striplength"))); - - DoubleModel m = new DoubleModel(component, "StripLength", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.6, 1.5)), "w 100lp, wrap"); - - //// Strip width: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Stripwidth"))); - - m = new DoubleModel(component, "StripWidth", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.2)), "w 100lp, wrap 20lp"); - - - - //// Strip area: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Striparea"))); - - m = new DoubleModel(component, "Area", UnitGroup.UNITS_AREA, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.04, 0.25)), "w 100lp, wrap"); - - //// Aspect ratio: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Aspectratio"))); - - m = new DoubleModel(component, "AspectRatio", UnitGroup.UNITS_NONE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - // panel.add(new UnitSelector(m),"growx"); - panel.add(new BasicSlider(m.getSliderModel(2, 15)), "skip, w 100lp, wrap 20lp"); - - - //// Material: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Material"))); - - JComboBox combo = new JComboBox(new MaterialModel(panel, component, - Material.Type.SURFACE)); - //// The component material affects the weight of the component. - combo.setToolTipText(trans.get("StreamerCfg.combo.ttip.MaterialModel")); - panel.add(combo, "spanx 3, growx, wrap 20lp"); - - - - // CD - //// Drag coefficient CD: - JLabel label = new HtmlLabel(trans.get("StreamerCfg.lbl.longA1")); - //// The drag coefficient relative to the total area of the streamer.
- String tip = trans.get("StreamerCfg.lbl.longB1") + - //// "A larger drag coefficient yields a slowed descent rate. - trans.get("StreamerCfg.lbl.longB2"); - label.setToolTipText(tip); - panel.add(label); - - m = new DoubleModel(component, "CD", UnitGroup.UNITS_COEFFICIENT, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setToolTipText(tip); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - JCheckBox check = new JCheckBox(m.getAutomaticAction()); - //// Automatic - check.setText(trans.get("StreamerCfg.lbl.Automatic")); - panel.add(check, "skip, span, wrap"); - - //// The drag coefficient is relative to the area of the streamer. - panel.add(new StyledLabel(trans.get("StreamerCfg.lbl.longC1"), - -2), "span, wrap"); - - - - primary.add(panel, "grow, gapright 20lp"); - panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - - - - - //// Position - //// Position relative to: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Posrelativeto"))); - - combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx, growx, wrap"); - - //// plus - panel.add(new JLabel(trans.get("StreamerCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap"); - - - //// Spatial length: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Packedlength"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 0.5)), "w 100lp, wrap"); - - - //// Tube diameter - //// Packed diameter: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Packeddiam"))); - - DoubleModel od = new DoubleModel(component, "Radius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap 30lp"); - - - //// Deployment - //// Deploys at: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Deploysat")), ""); - - combo = new JComboBox(new EnumModel(component, "DeployEvent")); - panel.add(combo, "spanx 3, growx, wrap"); - - // ... and delay - //// plus - panel.add(new JLabel(trans.get("StreamerCfg.lbl.plusdelay")), "right"); - - m = new DoubleModel(component, "DeployDelay", 0); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin,3)); - panel.add(spin, "spanx, split"); - - //// seconds - panel.add(new JLabel(trans.get("StreamerCfg.lbl.seconds")), "wrap paragraph"); - - // Altitude: - label = new JLabel(trans.get("StreamerCfg.lbl.Altitude")); - altitudeComponents.add(label); - panel.add(label); - - m = new DoubleModel(component, "DeployAltitude", UnitGroup.UNITS_DISTANCE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - altitudeComponents.add(spin); - panel.add(spin, "growx"); - UnitSelector unit = new UnitSelector(m); - altitudeComponents.add(unit); - panel.add(unit, "growx"); - BasicSlider slider = new BasicSlider(m.getSliderModel(100, 1000)); - altitudeComponents.add(slider); - panel.add(slider, "w 100lp, wrap"); - - - primary.add(panel, "grow"); - - updateFields(); - - //// General and General properties - tabbedPane.insertTab(trans.get("StreamerCfg.tab.General"), null, primary, - trans.get("StreamerCfg.tab.ttip.General"), 0); - //// Radial position and Radial position configuration - tabbedPane.insertTab(trans.get("StreamerCfg.tab.Radialpos"), null, positionTab(), - trans.get("StreamerCfg.tab.ttip.Radialpos"), 1); - tabbedPane.setSelectedIndex(0); - } - - - - - - protected JPanel positionTab() { - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - //// Radial position - //// Radial distance: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Radialdistance"))); - - DoubleModel m = new DoubleModel(component, "RadialPosition", UnitGroup.UNITS_LENGTH, 0); - - JSpinner spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 1.0)), "w 100lp, wrap"); - - - //// Radial direction - //// Radial direction: - panel.add(new JLabel(trans.get("StreamerCfg.lbl.Radialdirection"))); - - m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - //// Reset button - JButton button = new JButton(trans.get("StreamerCfg.but.Reset")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ((MassComponent) component).setRadialDirection(0.0); - ((MassComponent) component).setRadialPosition(0.0); - } - }); - panel.add(button, "spanx, right"); - - return panel; - } -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/ThicknessRingComponentConfig.java b/core/src/net/sf/openrocket/gui/configdialog/ThicknessRingComponentConfig.java deleted file mode 100644 index 3013b7c9..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/ThicknessRingComponentConfig.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JPanel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - - - -public class ThicknessRingComponentConfig extends RingComponentConfig { - private static final Translator trans = Application.getTranslator(); - - public ThicknessRingComponentConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - JPanel tab; - - //// Outer diameter: - //// Inner diameter: - //// Wall thickness: - //// Length: - tab = generalTab(trans.get("ThicknessRingCompCfg.tab.Outerdiam"), - trans.get("ThicknessRingCompCfg.tab.Innerdiam"), - trans.get("ThicknessRingCompCfg.tab.Wallthickness"), trans.get("ThicknessRingCompCfg.tab.Length")); - //// General and General properties - tabbedPane.insertTab(trans.get("ThicknessRingCompCfg.tab.General"), null, tab, - trans.get("ThicknessRingCompCfg.tab.Generalprop"), 0); - tabbedPane.setSelectedIndex(0); - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/configdialog/TransitionConfig.java b/core/src/net/sf/openrocket/gui/configdialog/TransitionConfig.java deleted file mode 100644 index 5e0286d8..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/TransitionConfig.java +++ /dev/null @@ -1,209 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.BooleanModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -public class TransitionConfig extends RocketComponentConfig { - - private static final Translator trans = Application.getTranslator(); - private JComboBox typeBox; - //private JLabel description; - - private JLabel shapeLabel; - private JSpinner shapeSpinner; - private BasicSlider shapeSlider; - private DescriptionArea description; - - - // Prepended to the description from Transition.DESCRIPTIONS - private static final String PREDESC = ""; - - - public TransitionConfig(OpenRocketDocument d, RocketComponent c) { - super(d, c); - - DoubleModel m; - JSpinner spin; - JCheckBox checkbox; - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - - - //// Shape selection - //// Transition shape: - panel.add(new JLabel(trans.get("TransitionCfg.lbl.Transitionshape"))); - - Transition.Shape selected = ((Transition) component).getType(); - Transition.Shape[] typeList = Transition.Shape.values(); - - typeBox = new JComboBox(typeList); - typeBox.setEditable(false); - typeBox.setSelectedItem(selected); - typeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Transition.Shape s = (Transition.Shape) typeBox.getSelectedItem(); - ((Transition) component).setType(s); - description.setText(PREDESC + s.getTransitionDescription()); - updateEnabled(); - } - }); - panel.add(typeBox, "span, split 2"); - - //// Clipped - checkbox = new JCheckBox(new BooleanModel(component, "Clipped")); - //// Clipped - checkbox.setText(trans.get("TransitionCfg.checkbox.Clipped")); - panel.add(checkbox, "wrap"); - - - //// Shape parameter: - shapeLabel = new JLabel(trans.get("TransitionCfg.lbl.Shapeparam")); - panel.add(shapeLabel); - - m = new DoubleModel(component, "ShapeParameter"); - - shapeSpinner = new JSpinner(m.getSpinnerModel()); - shapeSpinner.setEditor(new SpinnerEditor(shapeSpinner)); - panel.add(shapeSpinner, "growx"); - - DoubleModel min = new DoubleModel(component, "ShapeParameterMin"); - DoubleModel max = new DoubleModel(component, "ShapeParameterMax"); - shapeSlider = new BasicSlider(m.getSliderModel(min, max)); - panel.add(shapeSlider, "skip, w 100lp, wrap"); - - updateEnabled(); - - - //// Length - //// Transition length: - panel.add(new JLabel(trans.get("TransitionCfg.lbl.Transitionlength"))); - - m = new DoubleModel(component, "Length", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.3)), "w 100lp, wrap"); - - - //// Transition diameter 1 - //// Fore diameter: - panel.add(new JLabel(trans.get("TransitionCfg.lbl.Forediam"))); - - DoubleModel od = new DoubleModel(component, "ForeRadius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap 0px"); - - checkbox = new JCheckBox(od.getAutomaticAction()); - //// Automatic - checkbox.setText(trans.get("TransitionCfg.checkbox.Automatic")); - panel.add(checkbox, "skip, span 2, wrap"); - - - //// Transition diameter 2 - //// Aft diameter: - panel.add(new JLabel(trans.get("TransitionCfg.lbl.Aftdiam"))); - - od = new DoubleModel(component, "AftRadius", 2, UnitGroup.UNITS_LENGTH, 0); - // Diameter = 2*Radius - - spin = new JSpinner(od.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(od), "growx"); - panel.add(new BasicSlider(od.getSliderModel(0, 0.04, 0.2)), "w 100lp, wrap 0px"); - - checkbox = new JCheckBox(od.getAutomaticAction()); - //// Automatic - checkbox.setText(trans.get("TransitionCfg.checkbox.Automatic")); - panel.add(checkbox, "skip, span 2, wrap"); - - - //// Wall thickness: - panel.add(new JLabel(trans.get("TransitionCfg.lbl.Wallthickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap 0px"); - - //// Filled - checkbox = new JCheckBox(new BooleanModel(component, "Filled")); - //// Filled - checkbox.setText(trans.get("TransitionCfg.checkbox.Filled")); - panel.add(checkbox, "skip, span 2, wrap"); - - - - //// Description - - JPanel panel2 = new JPanel(new MigLayout("ins 0")); - - description = new DescriptionArea(5); - description.setText(PREDESC + ((Transition) component).getType(). - getTransitionDescription()); - panel2.add(description, "wmin 250lp, spanx, growx, wrap para"); - - - //// Material - - - materialPanel(panel2, Material.Type.BULK); - panel.add(panel2, "cell 4 0, gapleft paragraph, aligny 0%, spany"); - - //// General and General properties - tabbedPane.insertTab(trans.get("TransitionCfg.tab.General"), null, panel, - trans.get("TransitionCfg.tab.Generalproperties"), 0); - //// Shoulder and Shoulder properties - tabbedPane.insertTab(trans.get("TransitionCfg.tab.Shoulder"), null, shoulderTab(), - trans.get("TransitionCfg.tab.Shoulderproperties"), 1); - tabbedPane.setSelectedIndex(0); - } - - - - private void updateEnabled() { - boolean e = ((Transition) component).getType().usesParameter(); - shapeLabel.setEnabled(e); - shapeSpinner.setEnabled(e); - shapeSlider.setEnabled(e); - } - -} diff --git a/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java b/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java deleted file mode 100644 index 7c343fbf..00000000 --- a/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java +++ /dev/null @@ -1,244 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - - -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JSpinner; -import javax.swing.SwingConstants; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.IntegerModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - - -public class TrapezoidFinSetConfig extends FinSetConfig { - private static final Translator trans = Application.getTranslator(); - - public TrapezoidFinSetConfig(OpenRocketDocument d, final RocketComponent component) { - super(d, component); - - DoubleModel m; - JSpinner spin; - JComboBox combo; - - JPanel mainPanel = new JPanel(new MigLayout()); - - - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - //// Number of fins: - JLabel label = new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Nbroffins")); - //// The number of fins in the fin set. - label.setToolTipText(trans.get("TrapezoidFinSetCfg.lbl.ttip.Nbroffins")); - panel.add(label); - - IntegerModel im = new IntegerModel(component, "FinCount", 1, 8); - - spin = new JSpinner(im.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - //// The number of fins in the fin set. - spin.setToolTipText(trans.get("TrapezoidFinSetCfg.lbl.ttip.Nbroffins")); - panel.add(spin, "growx, wrap"); - - - //// Base rotation - //// Fin rotation: - label = new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Finrotation")); - //// The angle of the first fin in the fin set. - label.setToolTipText(trans.get("TrapezoidFinSetCfg.lbl.ttip.Finrotation")); - panel.add(label); - - m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)), "w 100lp, wrap"); - - - //// Fin cant: - label = new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Fincant")); - //// The angle that the fins are canted with respect to the rocket - label.setToolTipText(trans.get("TrapezoidFinSetCfg.lbl.ttip.Fincant")); - panel.add(label); - - m = new DoubleModel(component, "CantAngle", UnitGroup.UNITS_ANGLE, - -FinSet.MAX_CANT, FinSet.MAX_CANT); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-FinSet.MAX_CANT, FinSet.MAX_CANT)), - "w 100lp, wrap"); - - - //// Root chord: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Rootchord"))); - - m = new DoubleModel(component, "RootChord", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.2)), "w 100lp, wrap"); - - - - //// Tip chord: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Tipchord"))); - - m = new DoubleModel(component, "TipChord", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.2)), "w 100lp, wrap"); - - - //// Height: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Height"))); - - m = new DoubleModel(component, "Height", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.05, 0.2)), "w 100lp, wrap"); - - - - //// Sweep length: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Sweeplength"))); - - m = new DoubleModel(component, "Sweep", UnitGroup.UNITS_LENGTH); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - - // sweep slider from -1.1*TipChord to 1.1*RootChord - DoubleModel tc = new DoubleModel(component, "TipChord", -1.1, UnitGroup.UNITS_LENGTH); - DoubleModel rc = new DoubleModel(component, "RootChord", 1.1, UnitGroup.UNITS_LENGTH); - panel.add(new BasicSlider(m.getSliderModel(tc, rc)), "w 100lp, wrap"); - - - //// Sweep angle: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Sweepangle"))); - - m = new DoubleModel(component, "SweepAngle", UnitGroup.UNITS_ANGLE, - -TrapezoidFinSet.MAX_SWEEP_ANGLE, TrapezoidFinSet.MAX_SWEEP_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(-Math.PI / 4, Math.PI / 4)), - "w 100lp, wrap paragraph"); - - - - - - mainPanel.add(panel, "aligny 20%"); - - mainPanel.add(new JSeparator(SwingConstants.VERTICAL), "growy"); - - - - panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); - - - - //// Fin cross section: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.FincrossSection"))); - combo = new JComboBox( - new EnumModel(component, "CrossSection")); - panel.add(combo, "span, growx, wrap"); - - - //// Thickness: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Thickness"))); - - m = new DoubleModel(component, "Thickness", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap para"); - - - //// Position - //// Position relative to: - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.Posrelativeto"))); - - combo = new JComboBox( - new EnumModel(component, "RelativePosition", - new RocketComponent.Position[] { - RocketComponent.Position.TOP, - RocketComponent.Position.MIDDLE, - RocketComponent.Position.BOTTOM, - RocketComponent.Position.ABSOLUTE - })); - panel.add(combo, "spanx, growx, wrap"); - //// plus - panel.add(new JLabel(trans.get("TrapezoidFinSetCfg.lbl.plus")), "right"); - - m = new DoubleModel(component, "PositionValue", UnitGroup.UNITS_LENGTH); - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - panel.add(spin, "growx"); - - panel.add(new UnitSelector(m), "growx"); - panel.add(new BasicSlider(m.getSliderModel( - new DoubleModel(component.getParent(), "Length", -1.0, UnitGroup.UNITS_NONE), - new DoubleModel(component.getParent(), "Length"))), - "w 100lp, wrap para"); - - - - //// Material - materialPanel(panel, Material.Type.BULK); - - - - - mainPanel.add(panel, "aligny 20%"); - - //// General and General properties - tabbedPane.insertTab(trans.get("TrapezoidFinSetCfg.tab.General"), null, mainPanel, - trans.get("TrapezoidFinSetCfg.tab.Generalproperties"), 0); - tabbedPane.setSelectedIndex(0); - - addFinSetButtons(); - - } -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionDialog.java b/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionDialog.java deleted file mode 100644 index b8dee9fb..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionDialog.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.gui.customexpression; - -import java.awt.Window; - -import javax.swing.BorderFactory; -import javax.swing.JDialog; -import javax.swing.JPanel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; - -public class CustomExpressionDialog extends JDialog { - private static final Translator trans = Application.getTranslator(); - private static final LogHelper log = Application.getLogger(); - - private final Window parentWindow; - private final OpenRocketDocument doc; - - public CustomExpressionDialog(OpenRocketDocument doc, Window parent){ - super(parent, trans.get("customExpressionPanel.lbl.CustomExpressions")); - - this.doc = doc; - this.parentWindow = parent; - - JPanel panel = new CustomExpressionPanel(doc, this); - this.add( panel ); - - GUIUtil.setDisposableDialogOptions(this, null); - } -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionPanel.java b/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionPanel.java deleted file mode 100644 index ba928482..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionPanel.java +++ /dev/null @@ -1,261 +0,0 @@ -package net.sf.openrocket.gui.customexpression; - -import java.awt.Color; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.Collections; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.SwingUtilities; -import javax.swing.border.Border; -import javax.swing.filechooser.FileNameExtensionFilter; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.DatabaseMotorFinder; -import net.sf.openrocket.file.GeneralRocketLoader; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.startup.Application; - -public class CustomExpressionPanel extends JPanel { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private JPanel expressionSelectorPanel; - private OpenRocketDocument doc; - - public CustomExpressionPanel(final OpenRocketDocument doc, final JDialog parentDialog) { - super(new MigLayout("fill")); - this.doc = doc; - - expressionSelectorPanel = new JPanel(new MigLayout("gapy rel")); - expressionSelectorPanel.setToolTipText(trans.get("customExpressionPanel.lbl.CalcNote")); - - JScrollPane scroll = new JScrollPane(expressionSelectorPanel); - - //Border bdr = BorderFactory.createTitledBorder(trans.get("customExpressionPanel.lbl.CustomExpressions")); - //scroll.setBorder(bdr); - //expressionSelectorPanel.add(scroll); - - //this.add(expressionSelectorPanel, "spany 1, height 10px, wmin 600lp, grow 100, gapright para"); - this.add(scroll, "hmin 200lp, wmin 700lp, grow 100, wrap"); - - //DescriptionArea desc = new DescriptionArea(trans.get("customExpressionPanel.lbl.UpdateNote")+"\n\n"+trans.get("customExpressionPanel.lbl.CalcNote"), 8, -2f); - //desc.setViewportBorder(BorderFactory.createEmptyBorder()); - //this.add(desc, "width 1px, growx 1, wrap unrel, wrap"); - - //// New expression - JButton button = new JButton(trans.get("customExpressionPanel.but.NewExpression")); - button.setToolTipText(trans.get("customExpressionPanel.but.ttip.NewExpression")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Open window to configure expression - log.info("Opening window to configure new expression"); - Window parent = SwingUtilities.getWindowAncestor(CustomExpressionPanel.this); - new ExpressionBuilderDialog(parent, doc).setVisible(true); - updateExpressions(); - } - }); - this.add(button, "split 4, width :100:200"); - - //// Import - final JButton importButton = new JButton(trans.get("customExpressionPanel.but.Import")); - importButton.setToolTipText(trans.get("customExpressionPanel.but.ttip.Import")); - importButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - - //Create a file chooser - final JFileChooser fc = new JFileChooser(); - if (doc.getFile() != null){ - fc.setCurrentDirectory(doc.getFile().getParentFile()); - } - fc.setFileFilter(new FileNameExtensionFilter("Openrocket file", "ork")); - fc.setAcceptAllFileFilterUsed(false); - - int returnVal = fc.showOpenDialog(CustomExpressionPanel.this); - if (returnVal == JFileChooser.APPROVE_OPTION){ - File importFile = fc.getSelectedFile(); - log.info("User selected a file to import expressions from "+fc.getSelectedFile().toString()); - - //TODO: This should probably be somewhere else and ideally we would use an alternative minimal rocket loader. Still, it doesn't seem particularly slow this way. - - // Load expressions from selected document - GeneralRocketLoader loader = new GeneralRocketLoader(); - try { - OpenRocketDocument importedDocument = loader.load(importFile, new DatabaseMotorFinder()); - for (CustomExpression exp : importedDocument.getCustomExpressions()){ - doc.addCustomExpression(exp); - } - } catch (RocketLoadException e1) { - log.user("Error opening document to import expressions from."); - } - updateExpressions(); - } - } - }); - this.add(importButton, "width :100:200"); - - //// Close button - final JButton closeButton = new JButton(trans.get("dlg.but.close")); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - parentDialog.dispose(); - } - }); - this.add(new JPanel(), "growx"); - this.add(closeButton, "width :100:200"); - - updateExpressions(); - } - - /* - * Update the expressionSelectorPanel - */ - private void updateExpressions(){ - - expressionSelectorPanel.removeAll(); - int totalExpressions = doc.getCustomExpressions().size(); - for (int i=0; i expressions = doc.getCustomExpressions(); - int i = expressions.indexOf(expression); - if (i+move == expressions.size() || i+move < 0) - return; - else - Collections.swap(expressions, i, i+move); - } - - - /* - * A JPanel which configures a single expression - */ - private class SingleExpression extends JPanel { - - // Convenience method to make the labels consistent - private JLabel setLabelStyle(JLabel l){ - l.setBackground(Color.WHITE); - l.setOpaque(true); - l.setBorder(BorderFactory.createRaisedBevelBorder() ); - l.setText(" " + l.getText() + " "); - return l; - } - - private SingleExpression(final CustomExpression expression, boolean showUp, boolean showDown) { - super(new MigLayout("ins 0")); - // name: aName symbol: a Unit: m/s - //super(new MigLayout("","[::100][:200:400][::100][:100:200][::100][:100:200]","")); - - JLabel nameLabel = new JLabel( trans.get("customExpression.Name")+ " :"); - JLabel name = new JLabel ( expression.getName() ); - name = setLabelStyle(name); - JLabel symbolLabel = new JLabel( trans.get("customExpression.Symbol")+ " :" ); - JLabel symbol = new JLabel ( expression.getSymbol()); - symbol = setLabelStyle(symbol); - symbol.setBackground(Color.WHITE); - - JLabel unitLabel = new JLabel( trans.get("customExpression.Units")+ " :"); - UnitSelector unitSelector = new UnitSelector(expression.getType().getUnitGroup()); - //JLabel unitSelector = new JLabel ( expression.getUnit() ); - //unitSelector = setLabelStyle(unitSelector); - //unitSelector.setBackground(Color.WHITE); - - JButton editButton = new JButton(Icons.EDIT); - editButton.setToolTipText(trans.get("customExpression.Units.but.ttip.Edit")); - editButton.setBorderPainted(false); - editButton.addActionListener( new ActionListener() { - @Override - public void actionPerformed(ActionEvent e){ - Window parent = SwingUtilities.getWindowAncestor(CustomExpressionPanel.this); - new ExpressionBuilderDialog(parent, doc, expression).setVisible(true); - updateExpressions(); - } - }); - - JButton upButton = new JButton(Icons.UP); - upButton.setToolTipText(trans.get("customExpression.Units.but.ttip.MoveUp")); - upButton.setBorderPainted(false); - upButton.setVisible(showUp); - upButton.addActionListener( new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - moveExpression(expression, -1); - updateExpressions(); - } - }); - - JButton downButton = new JButton(Icons.DOWN); - downButton.setToolTipText(trans.get("customExpression.Units.but.ttip.MoveDown")); - downButton.setBorderPainted(false); - downButton.setVisible(showDown); - downButton.addActionListener( new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - moveExpression(expression, 1); - updateExpressions(); - } - }); - - - JButton deleteButton = new JButton(Icons.DELETE); - //// Remove this expression - deleteButton.setToolTipText(trans.get("customExpression.Units.but.ttip.Remove")); - deleteButton.setBorderPainted(false); - deleteButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - deleteExpression(expression); - updateExpressions(); - } - }); - - this.add(nameLabel); - this.add(name, "width 200:200:400, growx"); - this.add(new JPanel()); - this.add(symbolLabel); - this.add(symbol, "width :50:200"); - this.add(new JPanel()); - this.add(unitLabel); - this.add(unitSelector, "width :50:100"); - this.add(new JPanel(), "growx"); - this.add(upButton, "right"); - this.add(downButton, "right"); - this.add(editButton, "right"); - this.add(deleteButton, "right"); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/ExpressionBuilderDialog.java b/core/src/net/sf/openrocket/gui/customexpression/ExpressionBuilderDialog.java deleted file mode 100644 index 615fdc14..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/ExpressionBuilderDialog.java +++ /dev/null @@ -1,272 +0,0 @@ -package net.sf.openrocket.gui.customexpression; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.SwingConstants; -import javax.swing.SwingUtilities; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.startup.Application; - -/** - * Dialog box for making a custom expression - * @author Richard Graham - * - */ - -public class ExpressionBuilderDialog extends JDialog { - - private static final Translator trans = Application.getTranslator(); - private static final LogHelper log = Application.getLogger(); - - private static final ImageIcon GreenIcon = Icons.loadImageIcon("pix/spheres/green-16x16.png", "OK"); - private static final ImageIcon RedIcon = Icons.loadImageIcon("pix/spheres/red-16x16.png", "Bad"); - - private CustomExpression expression; - private CustomExpression previousExpressionCopy; - - private final Window parentWindow; - private final OpenRocketDocument doc; - - // Define these check indicators to show if fields are OK - private final JLabel nameCheck = new JLabel(RedIcon); - private final JLabel expressionCheck = new JLabel(RedIcon); - private final JLabel unitCheck = new JLabel(RedIcon); - private final JButton okButton = new JButton(trans.get("dlg.but.ok")); - private final JTextField expressionField = new JTextField(20); - - public ExpressionBuilderDialog(Window parent, OpenRocketDocument doc){ - this(parent, doc, new CustomExpression(doc)); - } - - public ExpressionBuilderDialog(Window parent, final OpenRocketDocument doc, final CustomExpression previousExpression){ - - super(parent, trans.get("ExpressionBuilderDialog.title"), JDialog.ModalityType.DOCUMENT_MODAL); - - this.doc = doc; - this.parentWindow = parent; - this.previousExpressionCopy = (CustomExpression) previousExpression.clone(); - this.expression = previousExpression; - - //// Name box -- Check input when focus changes and transfer focus to next box on enter key - JLabel nameLabel = new JLabel(trans.get("customExpression.Name")); - final JTextField nameField = new JTextField(20); - nameField.setText(expression.getName()); - nameField.setFocusTraversalKeysEnabled(true); - nameField.addFocusListener(new FocusListener() { - @Override - public void focusGained(FocusEvent e) { } - - @Override - public void focusLost(FocusEvent e) { - expression.setName(nameField.getText()); - ExpressionBuilderDialog.this.updateOK(); - } - }); - nameField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - nameField.transferFocus(); - } - }); - - //// Expression box -- for this one we check after each keypress using a keyListener. Enter transfers to next field - JLabel expressionLabel = new JLabel(trans.get("customExpression.Expression")); - expressionField.setText(expression.getExpressionString()); - expressionField.addKeyListener(new KeyListener() { - @Override - public void keyReleased(KeyEvent arg0) { - expression.setExpression( expressionField.getText() ); - ExpressionBuilderDialog.this.updateOK(); - } - - @Override - public void keyPressed(KeyEvent e) {} - - @Override - public void keyTyped(KeyEvent e) {} - }); - expressionField.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - expressionField.transferFocus(); - } - }); - - //// Units box -- with action listeners checking input after change in focus or enter press - JLabel unitLabel = new JLabel(trans.get("customExpression.Units")); - final JTextField unitField = new JTextField(5); - unitField.setText(expression.getUnit()); - unitField.addFocusListener(new FocusListener(){ - @Override - public void focusLost(FocusEvent arg0) { - expression.setUnit(unitField.getText()) ; - ExpressionBuilderDialog.this.updateOK(); - } - @Override - public void focusGained(FocusEvent arg0) {} - }); - unitField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - unitField.transferFocus(); - } - }); - - //// Symbol box - JLabel symbolLabel = new JLabel(trans.get("customExpression.Symbol")); - final JTextField symbolField = new JTextField(5); - symbolField.setText(expression.getSymbol()); - symbolField.addFocusListener(new FocusListener(){ - @Override - public void focusLost(FocusEvent arg0) { - expression.setSymbol(symbolField.getText()) ; - ExpressionBuilderDialog.this.updateOK(); - } - @Override - public void focusGained(FocusEvent arg0) {} - }); - symbolField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - symbolField.transferFocus(); - } - }); - - - //// Insert variable button - final JButton insertVariableButton = new JButton(trans.get("ExpressionBuilderDialog.InsertVariable")); - insertVariableButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.debug("Opening insert variable window"); - Window parentWindow = SwingUtilities.getWindowAncestor(ExpressionBuilderDialog.this); - new VariableSelector(parentWindow, ExpressionBuilderDialog.this, doc).setVisible(true); - } - }); - - //// Insert operator button - final JButton insertOperatorButton = new JButton(trans.get("ExpressionBuilderDialog.InsertOperator")); - insertOperatorButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.debug("Opening insert operator window"); - Window parentWindow = SwingUtilities.getWindowAncestor(ExpressionBuilderDialog.this); - new OperatorSelector(parentWindow, ExpressionBuilderDialog.this).setVisible(true); - } - }); - - //// OK Button - okButton.setEnabled(false); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // add to this simulation - expression.addToDocument(); - - // close window - ExpressionBuilderDialog.this.dispose(); - } - }); - - //// Cancel button - final JButton cancelButton = new JButton(trans.get("dlg.but.cancel")); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - expression.overwrite(previousExpressionCopy); - ExpressionBuilderDialog.this.dispose(); - } - }); - - //// Set to tips - nameCheck.setToolTipText(trans.get("ExpressionBuilderDialog.led.ttip.Name")); - unitCheck.setToolTipText(trans.get("ExpressionBuilderDialog.led.ttip.Symbol")); - expressionCheck.setToolTipText(trans.get("ExpressionBuilderDialog.led.ttip.Expression")); - - //// Do the layout - JPanel mainPanel = new JPanel(new MigLayout()); - mainPanel.add(nameLabel); - mainPanel.add(nameField); - mainPanel.add(nameCheck, "wrap, center"); - mainPanel.add(symbolLabel); - mainPanel.add(symbolField, "split 4, growx"); - mainPanel.add(new JPanel()); - mainPanel.add(unitLabel, "right"); - mainPanel.add(unitField, "right, growx"); - mainPanel.add(unitCheck, "wrap, center"); - mainPanel.add(expressionLabel); - mainPanel.add(expressionField); - mainPanel.add(expressionCheck, "wrap, center"); - mainPanel.add(insertOperatorButton, "span 2, right, split 2"); - mainPanel.add(insertVariableButton, "right, wrap"); - mainPanel.add(cancelButton, "span 2, right, width :50:100"); - mainPanel.add(okButton, "right, width :50:100, wrap"); - - this.add(mainPanel); - this.validate(); - this.pack(); - this.setLocationByPlatform(true); - this.updateOK(); - - } - - /** - * Enable OK button only if all the fields are ok - * @param okButton - */ - protected void updateOK() { - - boolean nameOK = expression.checkName(); - boolean unitOK = expression.checkUnit(); - boolean symbolOK = expression.checkSymbol(); - boolean expressionOK = expression.checkExpression(); - - if (nameOK) { nameCheck.setIcon(GreenIcon); } else { nameCheck.setIcon(RedIcon); } - if (unitOK && symbolOK) { unitCheck.setIcon(GreenIcon); } else { unitCheck.setIcon(RedIcon); } - if (expressionOK) { expressionCheck.setIcon(GreenIcon); } else { expressionCheck.setIcon(RedIcon); } - - okButton.setEnabled( nameOK && unitOK && symbolOK && expressionOK ); - } - - /** - * Inserts a string into the expression box at the position of the cursor. - * String will be padded with spaces either side - * Expression box will be focused after this is called. - * For strings containing an ( , cursor will be moved to the point after that, otherwise, cursor will move to the end of the inserted string. - * @param str - */ - public void pasteIntoExpression(String str) { - int pos = expressionField.getCaretPosition(); - String current = expressionField.getText(); - expressionField.setText(current.subSequence(0, pos) + " " + str + " " + current.subSequence(pos, current.length())); - expressionField.requestFocus(); - int bracketPos = str.indexOf("("); - if (bracketPos != -1){ - expressionField.setCaretPosition(pos+2+bracketPos); - } - else { - expressionField.setCaretPosition(pos+2+str.length()); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/OperatorSelector.java b/core/src/net/sf/openrocket/gui/customexpression/OperatorSelector.java deleted file mode 100644 index d51af30c..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/OperatorSelector.java +++ /dev/null @@ -1,157 +0,0 @@ -package net.sf.openrocket.gui.customexpression; - -import java.awt.Point; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionAdapter; - -import javax.swing.AbstractAction; -import javax.swing.ActionMap; -import javax.swing.InputMap; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.TextUtil; - -public class OperatorSelector extends JDialog { - - private static final Translator trans = Application.getTranslator(); - private static final LogHelper log = Application.getLogger(); - - private final Window parentWindow; - - private final JTable table; - private final OperatorTableModel tableModel; - private final ExpressionBuilderDialog parentBuilder; - - public OperatorSelector(Window parent, final ExpressionBuilderDialog parentBuilder){ - - super(parent, trans.get("CustomOperatorSelector.title"), JDialog.ModalityType.DOCUMENT_MODAL); - - this.parentWindow = parent; - this.parentBuilder = parentBuilder; - - final JButton insertButton = new JButton(trans.get("ExpressionBuilderDialog.InsertOperator")); - - JPanel mainPanel = new JPanel(new MigLayout()); - - //// Table of variables and model - tableModel = new OperatorTableModel(); - table = new JTable(tableModel); - - table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - int width = table.getColumnModel().getTotalColumnWidth(); - table.getColumnModel().getColumn(0).setPreferredWidth( (int) (.1 * width)); - table.getColumnModel().getColumn(1).setPreferredWidth( (int) (.9 * width)); - table.setAutoCreateRowSorter(true); - - table.addMouseMotionListener(new MouseMotionAdapter(){ - @Override - public void mouseMoved(MouseEvent e){ - Point p = e.getPoint(); - int row = table.rowAtPoint(p); - int col = table.columnAtPoint(p); - if (col == 1 && row > -1){ - String description = String.valueOf(table.getValueAt(row, 1)); - description = TextUtil.wrap(description, 60); - table.setToolTipText(description); - } else { - table.setToolTipText(null); - } - } - }); - - table.addMouseListener(new MouseListener(){ - @Override - public void mouseClicked(MouseEvent e){ - if (e.getClickCount() == 2){ - log.debug("Selected operator by double clicking."); - selectOperator(); - } - } - @Override - public void mouseEntered(MouseEvent e) {} - @Override - public void mouseExited(MouseEvent e) {} - @Override - public void mousePressed(MouseEvent e) {} - @Override - public void mouseReleased(MouseEvent e) {} - } ); - - InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - ActionMap actionMap = table.getActionMap(); - KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); - inputMap.put(enter, "select"); - actionMap.put("select", new AbstractAction(){ - @Override - public void actionPerformed(ActionEvent arg0) { - log.debug("Selected operator by enter key"); - selectOperator(); - } - }); - - JScrollPane scrollPane = new JScrollPane(table); - table.setFillsViewportHeight(true); - table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e){ - if (table.getSelectedRowCount() == 1){ - insertButton.setEnabled(true); - } - else { - insertButton.setEnabled(false); - } - } - }); - - mainPanel.add(scrollPane, "wrap, push, grow"); - - //// Cancel button - final JButton cancelButton = new JButton(trans.get("dlg.but.cancel")); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - OperatorSelector.this.dispose(); - } - }); - mainPanel.add(cancelButton, "right, width :100:200, split 2"); - - //// Insert button - insertButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - selectOperator(); - } - }); - insertButton.setEnabled(false); // disabled by default, only enable when a variable selected - mainPanel.add(insertButton, "right, width :100:200, wrap"); - - this.add(mainPanel); - this.validate(); - this.pack(); - this.setLocationByPlatform(true); - } - - private void selectOperator(){ - int row = table.getSelectedRow(); - String str = table.getValueAt(row, 0).toString(); - parentBuilder.pasteIntoExpression(str); - OperatorSelector.this.dispose(); - } -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/OperatorTableModel.java b/core/src/net/sf/openrocket/gui/customexpression/OperatorTableModel.java deleted file mode 100644 index 3b084da5..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/OperatorTableModel.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.sf.openrocket.gui.customexpression; - -import javax.swing.table.AbstractTableModel; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.customexpression.Functions; -import net.sf.openrocket.startup.Application; - -public class OperatorTableModel extends AbstractTableModel { - - private static final Translator trans = Application.getTranslator(); - - private static final String[] columnNames = {trans.get("customExpression.Operator"), trans.get("customExpression.Description")}; - - private final Object[] operators = Functions.AVAILABLE_OPERATORS.keySet().toArray(); - private final Object[] descriptions = Functions.AVAILABLE_OPERATORS.values().toArray(); - - public OperatorTableModel(){ - - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public int getRowCount() { - return Functions.AVAILABLE_OPERATORS.size(); - } - - @Override - public Object getValueAt(int row, int col) { - if (col == 0){ - return operators[row].toString(); - } - else if (col == 1){ - return descriptions[row].toString(); - } - return null; - } - - @Override - public String getColumnName(int col) { - return columnNames[col]; - } - - public String getOperatorAt(int row) { - return operators[row].toString(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/VariableSelector.java b/core/src/net/sf/openrocket/gui/customexpression/VariableSelector.java deleted file mode 100644 index 90130e63..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/VariableSelector.java +++ /dev/null @@ -1,149 +0,0 @@ -package net.sf.openrocket.gui.customexpression; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; - -import javax.swing.AbstractAction; -import javax.swing.ActionMap; -import javax.swing.InputMap; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.JTableHeader; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; - -/** - * Dialog to select from available custom variables - * @author Richard Graham - * - */ - -public class VariableSelector extends JDialog { - - private static final Translator trans = Application.getTranslator(); - private static final LogHelper log = Application.getLogger(); - - private final JTable table; - private final VariableTableModel tableModel; - private final ExpressionBuilderDialog parentBuilder; - - public VariableSelector(Window parent, final ExpressionBuilderDialog parentBuilder, final OpenRocketDocument doc){ - - super(parent, trans.get("CustomVariableSelector.title"), JDialog.ModalityType.DOCUMENT_MODAL); - - this.parentBuilder = parentBuilder; - final JButton insertButton = new JButton(trans.get("ExpressionBuilderDialog.InsertVariable")); - - JPanel mainPanel = new JPanel(new MigLayout()); - - //// Table of variables and model - tableModel = new VariableTableModel(doc); - table = new JTable(tableModel); - - table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); - table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); - int width = table.getColumnModel().getTotalColumnWidth(); - table.getColumnModel().getColumn(0).setPreferredWidth( (int) (.7 * width)); - table.getColumnModel().getColumn(1).setPreferredWidth( (int) (.15 * width)); - table.getColumnModel().getColumn(2).setPreferredWidth( (int) (.15 * width)); - table.setAutoCreateRowSorter(true); - - table.addMouseListener(new MouseListener(){ - @Override - public void mouseClicked(MouseEvent e){ - if (e.getClickCount() == 2){ - log.debug("Selected variable by double clicking."); - selectVariable(); - } - } - @Override - public void mouseEntered(MouseEvent e) {} - @Override - public void mouseExited(MouseEvent e) {} - @Override - public void mousePressed(MouseEvent e) {} - @Override - public void mouseReleased(MouseEvent e) {} - } ); - - InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - ActionMap actionMap = table.getActionMap(); - KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); - inputMap.put(enter, "select"); - actionMap.put("select", new AbstractAction(){ - @Override - public void actionPerformed(ActionEvent arg0) { - log.debug("Selected variable by enter key"); - selectVariable(); - } - }); - - - JScrollPane scrollPane = new JScrollPane(table); - table.setFillsViewportHeight(true); - table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e){ - if (table.getSelectedRowCount() == 1){ - insertButton.setEnabled(true); - } - else { - insertButton.setEnabled(false); - } - } - }); - - mainPanel.add(scrollPane, "wrap, push, grow"); - - //// Cancel button - final JButton cancelButton = new JButton(trans.get("dlg.but.cancel")); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - VariableSelector.this.dispose(); - } - }); - mainPanel.add(cancelButton, "right, width :100:200, split 2"); - - //// Insert button - insertButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - selectVariable(); - } - }); - insertButton.setEnabled(false); // disabled by default, only enable when a variable selected - mainPanel.add(insertButton, "right, width :100:200, wrap"); - - this.add(mainPanel); - this.validate(); - this.pack(); - this.setLocationByPlatform(true); - } - - private void selectVariable(){ - int row = table.getSelectedRow(); - String str = table.getValueAt(row, 1).toString(); - parentBuilder.pasteIntoExpression(str); - VariableSelector.this.dispose(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/customexpression/VariableTableModel.java b/core/src/net/sf/openrocket/gui/customexpression/VariableTableModel.java deleted file mode 100644 index f9d64978..00000000 --- a/core/src/net/sf/openrocket/gui/customexpression/VariableTableModel.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * - */ -package net.sf.openrocket.gui.customexpression; - -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.Vector; - -import javax.swing.JTable; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.startup.Application; - -/** - * @author Richard Graham - * - */ -public class VariableTableModel extends AbstractTableModel { - - private static final Translator trans = Application.getTranslator(); - - private List types; // = new ArrayList(); - private static final String[] columnNames = {trans.get("customExpression.Name"), trans.get("customExpression.Symbol"), trans.get("customExpression.Units")}; - - /* - * Table model will be constructed with all the built in variables and any custom variables defined - */ - public VariableTableModel(OpenRocketDocument doc){ - - types = new ArrayList( doc.getFlightDataTypes() ); - - //Collections.addAll(types, FlightDataType.ALL_TYPES); - //for (CustomExpression expression : doc.getCustomExpressions()){ - // types.add(expression.getType()); - //} - } - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public int getRowCount() { - return types.size(); - } - - @Override - public Object getValueAt(int row, int col) { - if (col == 0) - return types.get(row).getName(); - else if (col == 1) - return types.get(row).getSymbol(); - else if (col == 2) - return types.get(row).getUnitGroup().getSIUnit().toString(); - - return null; - } - - @Override - public String getColumnName(int col) { - return columnNames[col]; - } - - public String getSymbolAt(int row) { - if (row < 0 || row > types.size()){ - return ""; - } - else { - return types.get(row).getSymbol(); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/AboutDialog.java b/core/src/net/sf/openrocket/gui/dialogs/AboutDialog.java deleted file mode 100644 index 5b7d6cc9..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/AboutDialog.java +++ /dev/null @@ -1,134 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.components.URLLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.Chars; - -public class AboutDialog extends JDialog { - - public static final String OPENROCKET_URL = "http://openrocket.sourceforge.net/"; - private static final Translator trans = Application.getTranslator(); - - private static final String CREDITS = "

" + - "OpenRocket has been developed by:

" + - "Sampo Niskanen (main developer)
" + - "Doug Pedrick (RockSim file format, printing)
" + - "Kevin Ruland (Android version)
" + - "Bill Kuker (3D visualization)
" + - "Boris du Reau (internationalization, translation lead)
" + - "Richard Graham (geodetic computations)
" + - "Jason Blood (finset import)

" + - "Translations by:

" + - "Tripoli France (French)
" + - "Stefan Lobas / ERIG e.V. (German)
" + - "Tripoli Spain (Spanish)
" + - "Sky Dart Team (Russian)
" + - "Mauro Biasutti (Italian)

" + - "Vladimir Beran (Czech)

" + - "Polish Rocketry Society / \u0141ukasz & Alex kazanski (Polish)

" + - "OpenRocket utilizes the following libraries:

" + - "MiG Layout (http://www.miglayout.com/)
" + - "JFreeChart (http://www.jfree.org/jfreechart/)
" + - "iText (http://www.itextpdf.com/)
" + - "exp4j (http://projects.congrace.de/exp4j/index.html)
" + - "JOGL (http://jogamp.org/jogl/www/)"; - - - public AboutDialog(JFrame parent) { - super(parent, true); - - final String version = BuildProperties.getVersion(); - - JPanel panel = new JPanel(new MigLayout("fill")); - JPanel sub; - - - // OpenRocket logo - panel.add(new JLabel(Icons.loadImageIcon("pix/icon/icon-about.png", "OpenRocket")), "top"); - - - // OpenRocket version info + copyright - sub = new JPanel(new MigLayout("fill")); - - sub.add(new StyledLabel("OpenRocket", 20), "ax 50%, growy, wrap para"); - sub.add(new StyledLabel(trans.get("lbl.version").trim() + " " + version, 3), "ax 50%, growy, wrap rel"); - sub.add(new StyledLabel("Copyright " + Chars.COPY + " 2007-2012 Sampo Niskanen and others"), "ax 50%, growy, wrap para"); - - sub.add(new URLLabel(OPENROCKET_URL), "ax 50%, growy, wrap para"); - panel.add(sub, "grow"); - - - // Translation information (if present) - String translation = trans.get("lbl.translation").trim(); - String translator = trans.get("lbl.translator").trim(); - String translatorWebsite = trans.get("lbl.translatorWebsite").trim(); - String translatorIcon = trans.get("lbl.translatorIcon").trim(); - - if (translator.length() > 0 || translatorWebsite.length() > 0 || translatorIcon.length() > 0) { - sub = new JPanel(new MigLayout("fill")); - - sub.add(new StyledLabel(translation, Style.BOLD), "ax 50%, growy, wrap para"); - - if (translatorIcon.length() > 0) { - sub.add(new JLabel(Icons.loadImageIcon("pix/translators/" + translatorIcon, translator)), - "ax 50%, growy, wrap para"); - } - if (translator.length() > 0) { - sub.add(new JLabel(translator), "ax 50%, growy, wrap rel"); - } - if (translatorWebsite.length() > 0) { - sub.add(new URLLabel(translatorWebsite), "ax 50%, growy, wrap para"); - } - - panel.add(sub); - } - - - DescriptionArea info = new DescriptionArea(5); - info.setText(CREDITS); - panel.add(info, "newline, width 10px, height 150lp, grow, spanx, wrap para"); - - // JTextArea area = new JTextArea(CREATORS); - // area.setEditable(false); - // area.setLineWrap(true); - // area.setWrapStyleWord(true); - // panel.add(new JScrollPane(area), "width 10px, height 100lp, grow, spanx, wrap para"); - - - //Close button - JButton close = new JButton(trans.get("button.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - AboutDialog.this.dispose(); - } - }); - panel.add(close, "spanx, right"); - - this.add(panel); - this.setTitle("OpenRocket " + version); - this.pack(); - this.setResizable(false); - this.setLocationRelativeTo(parent); - - GUIUtil.setDisposableDialogOptions(this, close); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/BugReportDialog.java b/core/src/net/sf/openrocket/gui/dialogs/BugReportDialog.java deleted file mode 100644 index 9f203f36..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/BugReportDialog.java +++ /dev/null @@ -1,352 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Desktop; -import java.awt.Dialog; -import java.awt.Dimension; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.util.List; -import java.util.Locale; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.communication.BugReporter; -import net.sf.openrocket.gui.components.SelectableLabel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogLevelBufferLogger; -import net.sf.openrocket.logging.LogLine; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.JarUtil; - -public class BugReportDialog extends JDialog { - - private static final String REPORT_EMAIL = "openrocket-bugs@lists.sourceforge.net"; - private static final Translator trans = Application.getTranslator(); - - - public BugReportDialog(Window parent, String labelText, final String message, final boolean sendIfUnchanged) { - //// Bug report - super(parent, trans.get("bugreport.dlg.title"), Dialog.ModalityType.APPLICATION_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill")); - - // Some fscking Swing bug that makes html labels initially way too high - JLabel label = new JLabel(labelText); - Dimension d = label.getPreferredSize(); - d.width = 100000; - label.setMaximumSize(d); - panel.add(label, "gapleft para, wrap para"); - - //// If connected to the Internet, you can simply click - //// Send bug report. - label = new JLabel(trans.get("bugreport.dlg.connectedInternet")); - d = label.getPreferredSize(); - d.width = 100000; - label.setMaximumSize(d); - panel.add(label, "gapleft para, wrap"); - - //// Otherwise, send the text below to the address: - panel.add(new JLabel(trans.get("bugreport.dlg.otherwise") + " "), - "gapleft para, split 2, gapright rel"); - panel.add(new SelectableLabel(REPORT_EMAIL), "growx, wrap para"); - - - final JTextArea textArea = new JTextArea(message, 20, 70); - textArea.setEditable(true); - panel.add(new JScrollPane(textArea), "grow, wrap"); - - - panel.add(new StyledLabel(trans.get("bugreport.lbl.Theinformation"), -1), "wrap para"); - - - - ////Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - BugReportDialog.this.dispose(); - } - }); - panel.add(close, "right, sizegroup buttons, split"); - - - //// Mail button - // if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.MAIL)) { - // JButton mail = new JButton("Open email"); - // mail.setToolTipText("Open email client with the suitable email ready."); - // mail.addActionListener(new ActionListener() { - // @Override - // public void actionPerformed(ActionEvent e) { - // String text = textArea.getText(); - // openEmail(text); - // } - // }); - // panel.add(mail, "right, sizegroup buttons"); - // } - - - //// Send bug report button - JButton send = new JButton(trans.get("bugreport.dlg.but.Sendbugreport")); - //// Automatically send the bug report to the OpenRocket developers. - send.setToolTipText(trans.get("bugreport.dlg.but.Sendbugreport.Ttip")); - send.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String text = textArea.getText(); - if (text.equals(message) && !sendIfUnchanged) { - JOptionPane.showMessageDialog(BugReportDialog.this, - trans.get("bugreport.dlg.provideDescription"), - trans.get("bugreport.dlg.provideDescription.title"), JOptionPane.ERROR_MESSAGE); - return; - } - - try { - - BugReporter.sendBugReport(text); - - // Success if we came here - //bugreport.dlg.successmsg - /*JOptionPane.showMessageDialog(BugReportDialog.this, - new Object[] { "Bug report successfully sent.", - "Thank you for helping make OpenRocket better!" }, - "Bug report sent", JOptionPane.INFORMATION_MESSAGE);*/ - JOptionPane.showMessageDialog(BugReportDialog.this, - new Object[] { trans.get("bugreport.dlg.successmsg1"), - trans.get("bugreport.dlg.successmsg2") }, - trans.get("bugreport.dlg.successmsg3"), JOptionPane.INFORMATION_MESSAGE); - - } catch (Exception ex) { - // Sending the message failed. - JOptionPane.showMessageDialog(BugReportDialog.this, - //// OpenRocket was unable to send the bug report: - new Object[] { trans.get("bugreport.dlg.failedmsg1"), - ex.getClass().getSimpleName() + ": " + ex.getMessage(), " ", - //// Please send the report manually to - trans.get("bugreport.dlg.failedmsg2") + " " + REPORT_EMAIL }, - //// Error sending report - trans.get("bugreport.dlg.failedmsg3"), JOptionPane.ERROR_MESSAGE); - } - } - }); - panel.add(send, "right, sizegroup buttons"); - - this.add(panel); - - this.validate(); - this.pack(); - this.pack(); - this.setLocationRelativeTo(parent); - - GUIUtil.setDisposableDialogOptions(this, send); - } - - - - /** - * Show a general bug report dialog allowing the user to input information about - * the bug they encountered. - * - * @param parent the parent window (may be null). - */ - public static void showBugReportDialog(Window parent) { - - StringBuilder sb = new StringBuilder(); - - sb.append("---------- Bug report ----------\n"); - sb.append('\n'); - sb.append("Include detailed steps on how to trigger the bug:\n"); - sb.append('\n'); - sb.append("1. \n"); - sb.append("2. \n"); - sb.append("3. \n"); - sb.append('\n'); - - sb.append("What does the software do and what in your opinion should it do in the " + - "case described above:\n"); - sb.append('\n'); - sb.append('\n'); - sb.append('\n'); - - sb.append("Include your email address (optional; it helps if we can " + - "contact you in case we need additional information):\n"); - sb.append('\n'); - sb.append('\n'); - sb.append('\n'); - - - sb.append("(Do not modify anything below this line.)\n"); - sb.append("---------- System information ----------\n"); - addSystemInformation(sb); - sb.append("---------- Error log ----------\n"); - addErrorLog(sb); - sb.append("---------- End of bug report ----------\n"); - sb.append('\n'); - - BugReportDialog reportDialog = new BugReportDialog(parent, - trans.get("bugreport.reportDialog.txt"), sb.toString(), false); - reportDialog.setVisible(true); - } - - - /** - * Show a dialog presented when an uncaught exception occurs. - * - * @param parent the parent window (may be null). - * @param t the thread that encountered the exception (may be null). - * @param e the exception. - */ - public static void showExceptionDialog(Window parent, Thread t, Throwable e) { - StringBuilder sb = new StringBuilder(); - - sb.append("---------- Bug report ----------\n"); - sb.append('\n'); - sb.append("Please include a description about what actions you were " + - "performing when the exception occurred:\n"); - sb.append('\n'); - sb.append('\n'); - sb.append('\n'); - sb.append('\n'); - - - sb.append("Include your email address (optional; it helps if we can " + - "contact you in case we need additional information):\n"); - sb.append('\n'); - sb.append('\n'); - sb.append('\n'); - sb.append('\n'); - - sb.append("(Do not modify anything below this line.)\n"); - sb.append("---------- Exception stack trace ----------\n"); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - e.printStackTrace(pw); - sb.append(sw.getBuffer()); - sb.append('\n'); - - - sb.append("---------- Thread information ----------\n"); - if (t == null) { - sb.append("Thread is not specified."); - } else { - sb.append(t + "\n"); - } - sb.append('\n'); - - - sb.append("---------- System information ----------\n"); - addSystemInformation(sb); - sb.append("---------- Error log ----------\n"); - addErrorLog(sb); - sb.append("---------- End of bug report ----------\n"); - sb.append('\n'); - - BugReportDialog reportDialog = - //// Please include a short description about what you were doing when the exception occurred. - new BugReportDialog(parent, trans.get("bugreport.reportDialog.txt2"), sb.toString(), true); - reportDialog.setVisible(true); - } - - - private static void addSystemInformation(StringBuilder sb) { - sb.append("OpenRocket version: " + BuildProperties.getVersion() + "\n"); - sb.append("OpenRocket source: " + BuildProperties.getBuildSource() + "\n"); - sb.append("OpenRocket location: " + JarUtil.getCurrentJarFile() + "\n"); - sb.append("Current default locale: " + Locale.getDefault() + "\n"); - sb.append("System properties:\n"); - - // Sort the keys - SortedSet keys = new TreeSet(); - for (Object key : System.getProperties().keySet()) { - keys.add((String) key); - } - - for (String key : keys) { - String value = System.getProperty(key); - sb.append(" " + key + "="); - if (key.equals("line.separator")) { - for (char c : value.toCharArray()) { - sb.append(String.format("\\u%04x", (int) c)); - } - } else { - sb.append(value); - } - sb.append('\n'); - } - } - - - private static void addErrorLog(StringBuilder sb) { - LogLevelBufferLogger buffer = Application.getLogBuffer(); - List logs = buffer.getLogs(); - for (LogLine l : logs) { - sb.append(l.toString()).append('\n'); - } - } - - - - /** - * Open the default email client with the suitable bug report. - * Note that this does not work on some systems even if Desktop.isSupported() - * claims so. - * - * @param text the bug report text. - * @return whether opening the client succeeded. - */ - private boolean openEmail(String text) { - String version; - - try { - text = URLEncoder.encode(text, "UTF-8"); - version = URLEncoder.encode(BuildProperties.getVersion(), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new BugException(e); - } - - - - String mailto = "mailto:" + REPORT_EMAIL - + "?subject=Bug%20report%20for%20OpenRocket%20" + version - + "?body=" + text; - URI uri; - try { - uri = new URI(mailto); - } catch (URISyntaxException e) { - e.printStackTrace(); - return false; - } - - Desktop desktop = Desktop.getDesktop(); - try { - desktop.mail(uri); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - - return true; - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java b/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java deleted file mode 100644 index 9f5064ed..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java +++ /dev/null @@ -1,653 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import static net.sf.openrocket.unit.Unit.NOUNIT2; -import static net.sf.openrocket.util.Chars.ALPHA; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.JTable; -import javax.swing.JToggleButton; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.SwingUtilities; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.table.TableCellRenderer; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.gui.adaptors.Column; -import net.sf.openrocket.gui.adaptors.ColumnTableModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.MotorConfigurationModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.StageSelector; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.scalefigure.RocketPanel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -public class ComponentAnalysisDialog extends JDialog implements ChangeListener { - - private static ComponentAnalysisDialog singletonDialog = null; - private static final Translator trans = Application.getTranslator(); - - - private final FlightConditions conditions; - private final Configuration configuration; - private final DoubleModel theta, aoa, mach, roll; - private final JToggleButton worstToggle; - private boolean fakeChange = false; - private AerodynamicCalculator aerodynamicCalculator; - private final MassCalculator massCalculator = new BasicMassCalculator(); - - private final ColumnTableModel cpTableModel; - private final ColumnTableModel dragTableModel; - private final ColumnTableModel rollTableModel; - - private final JList warningList; - - - private final List cpData = new ArrayList(); - private final List cgData = new ArrayList(); - private final List dragData = new ArrayList(); - private double totalCD = 0; - private final List rollData = new ArrayList(); - - - public ComponentAnalysisDialog(final RocketPanel rocketPanel) { - ////Component analysis - super(SwingUtilities.getWindowAncestor(rocketPanel), - trans.get("componentanalysisdlg.componentanalysis")); - - JTable table; - - JPanel panel = new JPanel(new MigLayout("fill", "[][35lp::][fill][fill]")); - add(panel); - - this.configuration = rocketPanel.getConfiguration(); - this.aerodynamicCalculator = rocketPanel.getAerodynamicCalculator().newInstance(); - - - conditions = new FlightConditions(configuration); - - rocketPanel.setCPAOA(0); - aoa = new DoubleModel(rocketPanel, "CPAOA", UnitGroup.UNITS_ANGLE, 0, Math.PI); - rocketPanel.setCPMach(Application.getPreferences().getDefaultMach()); - mach = new DoubleModel(rocketPanel, "CPMach", UnitGroup.UNITS_COEFFICIENT, 0); - rocketPanel.setCPTheta(rocketPanel.getFigure().getRotation()); - theta = new DoubleModel(rocketPanel, "CPTheta", UnitGroup.UNITS_ANGLE, 0, 2 * Math.PI); - rocketPanel.setCPRoll(0); - roll = new DoubleModel(rocketPanel, "CPRoll", UnitGroup.UNITS_ROLL); - - //// Wind direction: - panel.add(new JLabel(trans.get("componentanalysisdlg.lbl.winddir")), "width 120lp!"); - panel.add(new UnitSelector(theta, true), "width 50lp!"); - BasicSlider slider = new BasicSlider(theta.getSliderModel(0, 2 * Math.PI)); - panel.add(slider, "growx, split 2"); - //// Worst button - worstToggle = new JToggleButton(trans.get("componentanalysisdlg.ToggleBut.worst")); - worstToggle.setSelected(true); - worstToggle.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - stateChanged(null); - } - }); - slider.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (!fakeChange) - worstToggle.setSelected(false); - } - }); - panel.add(worstToggle, ""); - - - warningList = new JList(); - JScrollPane scrollPane = new JScrollPane(warningList); - ////Warnings: - scrollPane.setBorder(BorderFactory.createTitledBorder(trans.get("componentanalysisdlg.TitledBorder.warnings"))); - panel.add(scrollPane, "gap paragraph, spany 4, width 300lp!, growy 1, height :100lp:, wrap"); - - ////Angle of attack: - panel.add(new JLabel(trans.get("componentanalysisdlg.lbl.angleofattack")), "width 120lp!"); - panel.add(new UnitSelector(aoa, true), "width 50lp!"); - panel.add(new BasicSlider(aoa.getSliderModel(0, Math.PI)), "growx, wrap"); - - //// Mach number: - panel.add(new JLabel(trans.get("componentanalysisdlg.lbl.machnumber")), "width 120lp!"); - panel.add(new UnitSelector(mach, true), "width 50lp!"); - panel.add(new BasicSlider(mach.getSliderModel(0, 3)), "growx, wrap"); - - //// Roll rate: - panel.add(new JLabel(trans.get("componentanalysisdlg.lbl.rollrate")), "width 120lp!"); - panel.add(new UnitSelector(roll, true), "width 50lp!"); - panel.add(new BasicSlider(roll.getSliderModel(-20 * 2 * Math.PI, 20 * 2 * Math.PI)), - "growx, wrap paragraph"); - - - // Stage and motor selection: - //// Active stages: - panel.add(new JLabel(trans.get("componentanalysisdlg.lbl.activestages")), "spanx, split, gapafter rel"); - panel.add(new StageSelector(configuration), "gapafter paragraph"); - - //// Motor configuration: - JLabel label = new JLabel(trans.get("componentanalysisdlg.lbl.motorconf")); - label.setHorizontalAlignment(JLabel.RIGHT); - panel.add(label, "growx, right"); - panel.add(new JComboBox(new MotorConfigurationModel(configuration)), "wrap"); - - - - // Tabbed pane - - JTabbedPane tabbedPane = new JTabbedPane(); - panel.add(tabbedPane, "spanx, growx, growy"); - - - // Create the CP data table - cpTableModel = new ColumnTableModel( - - //// Component - new Column(trans.get("componentanalysisdlg.TabStability.Col.Component")) { - @Override - public Object getValueAt(int row) { - RocketComponent c = cpData.get(row).getComponent(); - if (c instanceof Rocket) { - return trans.get("componentanalysisdlg.TOTAL"); - } - return c.toString(); - } - - @Override - public int getDefaultWidth() { - return 200; - } - }, - new Column(trans.get("componentanalysisdlg.TabStability.Col.CG") + " / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().getUnit()) { - private Unit unit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - - @Override - public Object getValueAt(int row) { - return unit.toString(cgData.get(row).x); - } - }, - new Column(trans.get("componentanalysisdlg.TabStability.Col.Mass") + " / " + UnitGroup.UNITS_MASS.getDefaultUnit().getUnit()) { - private Unit unit = UnitGroup.UNITS_MASS.getDefaultUnit(); - - @Override - public Object getValueAt(int row) { - return unit.toString(cgData.get(row).weight); - } - }, - new Column(trans.get("componentanalysisdlg.TabStability.Col.CP") + " / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().getUnit()) { - private Unit unit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - - @Override - public Object getValueAt(int row) { - return unit.toString(cpData.get(row).getCP().x); - } - }, - new Column("CN" + ALPHA + "") { - @Override - public Object getValueAt(int row) { - return NOUNIT2.toString(cpData.get(row).getCP().weight); - } - } - - ) { - @Override - public int getRowCount() { - return cpData.size(); - } - }; - - table = new JTable(cpTableModel); - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - table.setSelectionBackground(Color.LIGHT_GRAY); - table.setSelectionForeground(Color.BLACK); - cpTableModel.setColumnWidths(table.getColumnModel()); - - table.setDefaultRenderer(Object.class, new CustomCellRenderer()); - // table.setShowHorizontalLines(false); - // table.setShowVerticalLines(true); - - JScrollPane scrollpane = new JScrollPane(table); - scrollpane.setPreferredSize(new Dimension(600, 200)); - - //// Stability and Stability information - tabbedPane.addTab(trans.get("componentanalysisdlg.TabStability"), - null, scrollpane, trans.get("componentanalysisdlg.TabStability.ttip")); - - - - // Create the drag data table - dragTableModel = new ColumnTableModel( - //// Component - new Column(trans.get("componentanalysisdlg.dragTableModel.Col.Component")) { - @Override - public Object getValueAt(int row) { - RocketComponent c = dragData.get(row).getComponent(); - if (c instanceof Rocket) { - return trans.get("componentanalysisdlg.TOTAL"); - } - return c.toString(); - } - - @Override - public int getDefaultWidth() { - return 200; - } - }, - //// Pressure CD - new Column(trans.get("componentanalysisdlg.dragTableModel.Col.Pressure")) { - @Override - public Object getValueAt(int row) { - return dragData.get(row).getPressureCD(); - } - }, - //// Base CD - new Column(trans.get("componentanalysisdlg.dragTableModel.Col.Base")) { - @Override - public Object getValueAt(int row) { - return dragData.get(row).getBaseCD(); - } - }, - //// Friction CD - new Column(trans.get("componentanalysisdlg.dragTableModel.Col.friction")) { - @Override - public Object getValueAt(int row) { - return dragData.get(row).getFrictionCD(); - } - }, - //// Total CD - new Column(trans.get("componentanalysisdlg.dragTableModel.Col.total")) { - @Override - public Object getValueAt(int row) { - return dragData.get(row).getCD(); - } - } - ) { - @Override - public int getRowCount() { - return dragData.size(); - } - }; - - - table = new JTable(dragTableModel); - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - table.setSelectionBackground(Color.LIGHT_GRAY); - table.setSelectionForeground(Color.BLACK); - dragTableModel.setColumnWidths(table.getColumnModel()); - - table.setDefaultRenderer(Object.class, new DragCellRenderer(new Color(0.5f, 1.0f, 0.5f))); - // table.setShowHorizontalLines(false); - // table.setShowVerticalLines(true); - - scrollpane = new JScrollPane(table); - scrollpane.setPreferredSize(new Dimension(600, 200)); - - //// Drag characteristics and Drag characteristics tooltip - tabbedPane.addTab(trans.get("componentanalysisdlg.dragTabchar"), null, scrollpane, - trans.get("componentanalysisdlg.dragTabchar.ttip")); - - - - - // Create the roll data table - rollTableModel = new ColumnTableModel( - //// Component - new Column(trans.get("componentanalysisdlg.rollTableModel.Col.component")) { - @Override - public Object getValueAt(int row) { - RocketComponent c = rollData.get(row).getComponent(); - if (c instanceof Rocket) { - return trans.get("componentanalysisdlg.TOTAL"); - } - return c.toString(); - } - }, - //// Roll forcing coefficient - new Column(trans.get("componentanalysisdlg.rollTableModel.Col.rollforc")) { - @Override - public Object getValueAt(int row) { - return rollData.get(row).getCrollForce(); - } - }, - //// Roll damping coefficient - new Column(trans.get("componentanalysisdlg.rollTableModel.Col.rolldamp")) { - @Override - public Object getValueAt(int row) { - return rollData.get(row).getCrollDamp(); - } - }, - //// Total Cl - new Column(trans.get("componentanalysisdlg.rollTableModel.Col.total")) { - @Override - public Object getValueAt(int row) { - return rollData.get(row).getCroll(); - } - } - ) { - @Override - public int getRowCount() { - return rollData.size(); - } - }; - - - table = new JTable(rollTableModel); - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - table.setSelectionBackground(Color.LIGHT_GRAY); - table.setSelectionForeground(Color.BLACK); - rollTableModel.setColumnWidths(table.getColumnModel()); - - scrollpane = new JScrollPane(table); - scrollpane.setPreferredSize(new Dimension(600, 200)); - - //// Roll dynamics and Roll dynamics tooltip - tabbedPane.addTab(trans.get("componentanalysisdlg.rollTableModel"), null, scrollpane, - trans.get("componentanalysisdlg.rollTableModel.ttip")); - - - - - - // Add the data updater to listen to changes in aoa and theta - mach.addChangeListener(this); - theta.addChangeListener(this); - aoa.addChangeListener(this); - roll.addChangeListener(this); - configuration.addChangeListener(this); - this.stateChanged(null); - - - - // Remove listeners when closing window - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent e) { - //System.out.println("Closing method called: " + this); - theta.removeChangeListener(ComponentAnalysisDialog.this); - aoa.removeChangeListener(ComponentAnalysisDialog.this); - mach.removeChangeListener(ComponentAnalysisDialog.this); - roll.removeChangeListener(ComponentAnalysisDialog.this); - configuration.removeChangeListener(ComponentAnalysisDialog.this); - //System.out.println("SETTING NAN VALUES"); - rocketPanel.setCPAOA(Double.NaN); - rocketPanel.setCPTheta(Double.NaN); - rocketPanel.setCPMach(Double.NaN); - rocketPanel.setCPRoll(Double.NaN); - singletonDialog = null; - } - }); - - //// Reference length: - panel.add(new StyledLabel(trans.get("componentanalysisdlg.lbl.reflenght"), -1), - "span, split, gapleft para, gapright rel"); - DoubleModel dm = new DoubleModel(conditions, "RefLength", UnitGroup.UNITS_LENGTH); - UnitSelector sel = new UnitSelector(dm, true); - sel.resizeFont(-1); - panel.add(sel, "gapright para"); - - //// Reference area: - panel.add(new StyledLabel(trans.get("componentanalysisdlg.lbl.refarea"), -1), "gapright rel"); - dm = new DoubleModel(conditions, "RefArea", UnitGroup.UNITS_AREA); - sel = new UnitSelector(dm, true); - sel.resizeFont(-1); - panel.add(sel, "wrap"); - - - - // Buttons - JButton button; - - // TODO: LOW: printing - // button = new JButton("Print"); - // button.addActionListener(new ActionListener() { - // public void actionPerformed(ActionEvent e) { - // try { - // table.print(); - // } catch (PrinterException e1) { - // JOptionPane.showMessageDialog(ComponentAnalysisDialog.this, - // "An error occurred while printing.", "Print error", - // JOptionPane.ERROR_MESSAGE); - // } - // } - // }); - // panel.add(button,"tag ok"); - - //button = new JButton("Close"); - //Close button - button = new JButton(trans.get("dlg.but.close")); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - ComponentAnalysisDialog.this.dispose(); - } - }); - panel.add(button, "span, split, tag cancel"); - - - this.setLocationByPlatform(true); - setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - pack(); - - GUIUtil.setDisposableDialogOptions(this, null); - } - - - - /** - * Updates the data in the table and fires a table data change event. - */ - @Override - public void stateChanged(ChangeEvent e) { - AerodynamicForces forces; - WarningSet set = new WarningSet(); - conditions.setAOA(aoa.getValue()); - conditions.setTheta(theta.getValue()); - conditions.setMach(mach.getValue()); - conditions.setRollRate(roll.getValue()); - conditions.setReference(configuration); - - if (worstToggle.isSelected()) { - aerodynamicCalculator.getWorstCP(configuration, conditions, null); - if (!MathUtil.equals(conditions.getTheta(), theta.getValue())) { - fakeChange = true; - theta.setValue(conditions.getTheta()); // Fires a stateChanged event - fakeChange = false; - return; - } - } - - Map aeroData = - aerodynamicCalculator.getForceAnalysis(configuration, conditions, set); - Map massData = - massCalculator.getCGAnalysis(configuration, MassCalcType.LAUNCH_MASS); - - - cpData.clear(); - cgData.clear(); - dragData.clear(); - rollData.clear(); - for (RocketComponent c : configuration) { - forces = aeroData.get(c); - Coordinate cg = massData.get(c); - - if (forces == null) - continue; - if (forces.getCP() != null) { - cpData.add(forces); - cgData.add(cg); - } - if (!Double.isNaN(forces.getCD())) { - dragData.add(forces); - } - if (c instanceof FinSet) { - rollData.add(forces); - } - } - forces = aeroData.get(configuration.getRocket()); - if (forces != null) { - cpData.add(forces); - cgData.add(massData.get(configuration.getRocket())); - dragData.add(forces); - rollData.add(forces); - totalCD = forces.getCD(); - } else { - totalCD = 0; - } - - // Set warnings - if (set.isEmpty()) { - warningList.setListData(new String[] { - trans.get("componentanalysisdlg.noWarnings") - }); - } else { - warningList.setListData(new Vector(set)); - } - - cpTableModel.fireTableDataChanged(); - dragTableModel.fireTableDataChanged(); - rollTableModel.fireTableDataChanged(); - } - - - private class CustomCellRenderer extends JLabel implements TableCellRenderer { - private final Font normalFont; - private final Font boldFont; - - public CustomCellRenderer() { - super(); - normalFont = getFont(); - boldFont = normalFont.deriveFont(Font.BOLD); - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - - this.setText(value.toString()); - - if ((row < 0) || (row >= cpData.size())) - return this; - - if (cpData.get(row).getComponent() instanceof Rocket) { - this.setFont(boldFont); - } else { - this.setFont(normalFont); - } - return this; - } - } - - - - private class DragCellRenderer extends JLabel implements TableCellRenderer { - private final Font normalFont; - private final Font boldFont; - - - public DragCellRenderer(Color baseColor) { - super(); - normalFont = getFont(); - boldFont = normalFont.deriveFont(Font.BOLD); - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - - if (value instanceof Double) { - - // A drag coefficient - double cd = (Double) value; - this.setText(String.format("%.2f (%.0f%%)", cd, 100 * cd / totalCD)); - - float r = (float) (cd / 1.5); - - float hue = MathUtil.clamp(0.3333f * (1 - 2.0f * r), 0, 0.3333f); - float sat = MathUtil.clamp(0.8f * r + 0.1f * (1 - r), 0, 1); - float val = 1.0f; - - this.setBackground(Color.getHSBColor(hue, sat, val)); - this.setOpaque(true); - this.setHorizontalAlignment(SwingConstants.CENTER); - - } else { - - // Other - this.setText(value.toString()); - this.setOpaque(false); - this.setHorizontalAlignment(SwingConstants.LEFT); - - } - - if ((row < 0) || (row >= dragData.size())) - return this; - - if ((dragData.get(row).getComponent() instanceof Rocket) || (column == 4)) { - this.setFont(boldFont); - } else { - this.setFont(normalFont); - } - return this; - } - } - - - ///////// Singleton implementation - - public static void showDialog(RocketPanel rocketpanel) { - if (singletonDialog != null) - singletonDialog.dispose(); - singletonDialog = new ComponentAnalysisDialog(rocketpanel); - singletonDialog.setVisible(true); - } - - public static void hideDialog() { - if (singletonDialog != null) - singletonDialog.dispose(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java b/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java deleted file mode 100644 index 9ef95a9b..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java +++ /dev/null @@ -1,184 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Dialog; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.JTextField; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.startup.Application; - -public class CustomMaterialDialog extends JDialog { - private static final Translator trans = Application.getTranslator(); - - private final Material originalMaterial; - - private boolean okClicked = false; - private JComboBox typeBox; - private JTextField nameField; - private DoubleModel density; - private JSpinner densitySpinner; - private UnitSelector densityUnit; - private JCheckBox addBox; - - public CustomMaterialDialog(Window parent, Material material, boolean saveOption, - String title) { - this(parent, material, saveOption, title, null); - } - - - public CustomMaterialDialog(Window parent, Material material, boolean saveOption, - String title, String note) { - //// Custom material - super(parent, trans.get("custmatdlg.title.Custommaterial"), Dialog.ModalityType.APPLICATION_MODAL); - - this.originalMaterial = material; - - JPanel panel = new JPanel(new MigLayout("fill, gap rel unrel")); - - - // Add title and note - if (title != null) { - panel.add(new JLabel("" + title + ":"), - "gapleft para, span, wrap" + (note == null ? " para" : "")); - } - if (note != null) { - panel.add(new StyledLabel(note, -1), "span, wrap para"); - } - - - //// Material name - panel.add(new JLabel(trans.get("custmatdlg.lbl.Materialname"))); - nameField = new JTextField(15); - if (material != null) { - nameField.setText(material.getName()); - } - panel.add(nameField, "span, growx, wrap"); - - - // Material type (if not known) - panel.add(new JLabel(trans.get("custmatdlg.lbl.Materialtype"))); - if (material == null) { - typeBox = new JComboBox(Material.Type.values()); - typeBox.setSelectedItem(Material.Type.BULK); - typeBox.setEditable(false); - typeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateDensityModel(); - } - }); - panel.add(typeBox, "span, growx, wrap"); - } else { - panel.add(new JLabel(material.getType().toString()), "span, growx, wrap"); - } - - - // Material density: - panel.add(new JLabel(trans.get("custmatdlg.lbl.Materialdensity"))); - densitySpinner = new JSpinner(); - panel.add(densitySpinner, "w 70lp"); - densityUnit = new UnitSelector((DoubleModel) null); - panel.add(densityUnit, "w 30lp"); - panel.add(new JPanel(), "growx, wrap"); - updateDensityModel(); - - - // Save option - if (saveOption) { - //// Add material to database - addBox = new JCheckBox(trans.get("custmatdlg.checkbox.Addmaterial")); - panel.add(addBox, "span, wrap"); - } - - //// OK button - JButton okButton = new JButton(trans.get("dlg.but.ok")); - - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - okClicked = true; - CustomMaterialDialog.this.setVisible(false); - } - }); - panel.add(okButton, "span, split, tag ok"); - - //// Cancel - JButton closeButton = new JButton(trans.get("dlg.but.cancel")); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - okClicked = false; - CustomMaterialDialog.this.setVisible(false); - } - }); - panel.add(closeButton, "tag cancel"); - - this.setContentPane(panel); - this.pack(); - this.setLocationByPlatform(true); - GUIUtil.setDisposableDialogOptions(this, okButton); - } - - - public boolean getOkClicked() { - return okClicked; - } - - - public boolean isAddSelected() { - return addBox.isSelected(); - } - - - public Material getMaterial() { - Material.Type type; - String name; - double materialDensity; - - if (typeBox != null) { - type = (Material.Type) typeBox.getSelectedItem(); - } else { - type = originalMaterial.getType(); - } - - name = nameField.getText().trim(); - - materialDensity = this.density.getValue(); - - return Databases.findMaterial(type, name, materialDensity); - } - - - private void updateDensityModel() { - if (originalMaterial != null) { - if (density == null) { - density = new DoubleModel(originalMaterial.getDensity(), - originalMaterial.getType().getUnitGroup(), 0); - densitySpinner.setModel(density.getSpinnerModel()); - densityUnit.setModel(density); - } - } else { - Material.Type type = (Material.Type) typeBox.getSelectedItem(); - density = new DoubleModel(0, type.getUnitGroup(), 0); - densitySpinner.setModel(density.getSpinnerModel()); - densityUnit.setModel(density); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/DebugLogDialog.java b/core/src/net/sf/openrocket/gui/dialogs/DebugLogDialog.java deleted file mode 100644 index 5c36f5d8..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/DebugLogDialog.java +++ /dev/null @@ -1,537 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Rectangle; -import java.awt.Toolkit; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTable; -import javax.swing.JTextArea; -import javax.swing.ListSelectionModel; -import javax.swing.RowFilter; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableModel; -import javax.swing.table.TableRowSorter; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.adaptors.Column; -import net.sf.openrocket.gui.adaptors.ColumnTableModel; -import net.sf.openrocket.gui.components.SelectableLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.DelegatorLogger; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.LogLevel; -import net.sf.openrocket.logging.LogLevelBufferLogger; -import net.sf.openrocket.logging.LogLine; -import net.sf.openrocket.logging.StackTraceWriter; -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.NumericComparator; - -public class DebugLogDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - - private static final int POLL_TIME = 250; - private static final String STACK_TRACE_MARK = "\uFF01"; - private static final Translator trans = Application.getTranslator(); - - private static final EnumMap backgroundColors = new EnumMap(LogLevel.class); - static { - for (LogLevel l : LogLevel.values()) { - // Just to ensure every level has a bg color - backgroundColors.put(l, Color.ORANGE); - } - final int hi = 255; - final int lo = 150; - backgroundColors.put(LogLevel.ERROR, new Color(hi, lo, lo)); - backgroundColors.put(LogLevel.WARN, new Color(hi, (hi + lo) / 2, lo)); - backgroundColors.put(LogLevel.USER, new Color(lo, lo, hi)); - backgroundColors.put(LogLevel.INFO, new Color(hi, hi, lo)); - backgroundColors.put(LogLevel.DEBUG, new Color(lo, hi, lo)); - backgroundColors.put(LogLevel.VBOSE, new Color(lo, hi, (hi + lo) / 2)); - } - - /** Buffer containing the log lines displayed */ - private final List buffer = new ArrayList(); - - /** Queue of log lines to be added to the displayed buffer */ - private final Queue queue = new ConcurrentLinkedQueue(); - - private final DelegatorLogger delegator; - private final LogListener logListener; - - private final EnumMap filterButtons = new EnumMap(LogLevel.class); - private final JCheckBox followBox; - private final Timer timer; - - - private final JTable table; - private final ColumnTableModel model; - private final TableRowSorter sorter; - - private final SelectableLabel numberLabel; - private final SelectableLabel timeLabel; - private final SelectableLabel levelLabel; - private final SelectableLabel locationLabel; - private final SelectableLabel messageLabel; - private final JTextArea stackTraceLabel; - - public DebugLogDialog(Window parent) { - //// OpenRocket debug log - super(parent, trans.get("debuglogdlg.OpenRocketdebuglog")); - - // Start listening to log lines - LogHelper applicationLog = Application.getLogger(); - if (applicationLog instanceof DelegatorLogger) { - log.info("Adding log listener"); - delegator = (DelegatorLogger) applicationLog; - logListener = new LogListener(); - delegator.addLogger(logListener); - } else { - log.warn("Application log is not a DelegatorLogger"); - delegator = null; - logListener = null; - } - - // Fetch old log lines - LogLevelBufferLogger bufferLogger = Application.getLogBuffer(); - if (bufferLogger != null) { - buffer.addAll(bufferLogger.getLogs()); - } else { - log.warn("Application does not have a log buffer"); - } - - - // Create the UI - JPanel mainPanel = new JPanel(new MigLayout("fill")); - this.add(mainPanel); - - - JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - split.setDividerLocation(0.7); - mainPanel.add(split, "grow"); - - // Top panel - JPanel panel = new JPanel(new MigLayout("fill")); - split.add(panel); - - //// Display log lines: - panel.add(new JLabel(trans.get("debuglogdlg.Displayloglines")), "gapright para, split"); - for (LogLevel l : LogLevel.values()) { - JCheckBox box = new JCheckBox(l.toString()); - // By default display DEBUG and above - box.setSelected(l.atLeast(LogLevel.DEBUG)); - box.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - sorter.setRowFilter(new LogFilter()); - } - }); - panel.add(box, "gapright unrel"); - filterButtons.put(l, box); - } - - //// Follow - followBox = new JCheckBox(trans.get("debuglogdlg.Follow")); - followBox.setSelected(true); - panel.add(followBox, "skip, gapright para, right"); - - //// Clear button - JButton clear = new JButton(trans.get("debuglogdlg.but.clear")); - clear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Clearing log buffer"); - buffer.clear(); - queue.clear(); - model.fireTableDataChanged(); - } - }); - panel.add(clear, "right, wrap"); - - - - // Create the table model - model = new ColumnTableModel( - - new Column("#") { - @Override - public Object getValueAt(int row) { - return buffer.get(row).getLogCount(); - } - - @Override - public int getDefaultWidth() { - return 60; - } - }, - //// Time - new Column(trans.get("debuglogdlg.col.Time")) { - @Override - public Object getValueAt(int row) { - return String.format("%.3f", buffer.get(row).getTimestamp() / 1000.0); - } - - @Override - public int getDefaultWidth() { - return 60; - } - }, - //// Level - new Column(trans.get("debuglogdlg.col.Level")) { - @Override - public Object getValueAt(int row) { - return buffer.get(row).getLevel(); - } - - @Override - public int getDefaultWidth() { - return 60; - } - }, - new Column("") { - @Override - public Object getValueAt(int row) { - if (buffer.get(row).getCause() != null) { - return STACK_TRACE_MARK; - } else { - return ""; - } - } - - @Override - public int getExactWidth() { - return 16; - } - }, - //// Location - new Column(trans.get("debuglogdlg.col.Location")) { - @Override - public Object getValueAt(int row) { - TraceException e = buffer.get(row).getTrace(); - if (e != null) { - return e.getMessage(); - } else { - return ""; - } - } - - @Override - public int getDefaultWidth() { - return 200; - } - }, - //// Message - new Column(trans.get("debuglogdlg.col.Message")) { - @Override - public Object getValueAt(int row) { - return buffer.get(row).getMessage(); - } - - @Override - public int getDefaultWidth() { - return 580; - } - } - - ) { - @Override - public int getRowCount() { - return buffer.size(); - } - }; - - table = new JTable(model); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setSelectionBackground(Color.LIGHT_GRAY); - table.setSelectionForeground(Color.BLACK); - model.setColumnWidths(table.getColumnModel()); - table.setDefaultRenderer(Object.class, new Renderer()); - - table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - int row = table.getSelectedRow(); - if (row >= 0) { - row = sorter.convertRowIndexToModel(row); - } - updateSelected(row); - } - }); - - sorter = new TableRowSorter(model); - sorter.setComparator(0, NumericComparator.INSTANCE); - sorter.setComparator(1, NumericComparator.INSTANCE); - sorter.setComparator(4, new LocationComparator()); - table.setRowSorter(sorter); - sorter.setRowFilter(new LogFilter()); - - - panel.add(new JScrollPane(table), "span, grow, width " + - (Toolkit.getDefaultToolkit().getScreenSize().width * 8 / 10) + - "px, height 400px"); - - - panel = new JPanel(new MigLayout("fill")); - split.add(panel); - - //// Log line number: - panel.add(new JLabel(trans.get("debuglogdlg.lbl.Loglinenbr")), "split, gapright rel"); - numberLabel = new SelectableLabel(); - panel.add(numberLabel, "width 70lp, gapright para"); - - //// Time: - panel.add(new JLabel(trans.get("debuglogdlg.lbl.Time")), "split, gapright rel"); - timeLabel = new SelectableLabel(); - panel.add(timeLabel, "width 70lp, gapright para"); - - //// Level: - panel.add(new JLabel(trans.get("debuglogdlg.lbl.Level")), "split, gapright rel"); - levelLabel = new SelectableLabel(); - panel.add(levelLabel, "width 70lp, gapright para"); - - //// Location: - panel.add(new JLabel(trans.get("debuglogdlg.lbl.Location")), "split, gapright rel"); - locationLabel = new SelectableLabel(); - panel.add(locationLabel, "growx, wrap unrel"); - - //// Log message: - panel.add(new JLabel(trans.get("debuglogdlg.lbl.Logmessage")), "split, gapright rel"); - messageLabel = new SelectableLabel(); - panel.add(messageLabel, "growx, wrap para"); - - //// Stack trace: - panel.add(new JLabel(trans.get("debuglogdlg.lbl.Stacktrace")), "wrap rel"); - stackTraceLabel = new JTextArea(8, 80); - stackTraceLabel.setEditable(false); - GUIUtil.changeFontSize(stackTraceLabel, -2); - panel.add(new JScrollPane(stackTraceLabel), "grow"); - - - //Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - DebugLogDialog.this.dispose(); - } - }); - mainPanel.add(close, "newline para, right, tag ok"); - - - // Use timer to purge the queue so as not to overwhelm the EDT with events - timer = new Timer(POLL_TIME, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - purgeQueue(); - } - }); - timer.setRepeats(true); - timer.start(); - - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent e) { - log.user("Closing debug log dialog"); - timer.stop(); - if (delegator != null) { - log.info("Removing log listener"); - delegator.removeLogger(logListener); - } - } - }); - - GUIUtil.setDisposableDialogOptions(this, close); - followBox.requestFocus(); - } - - - - private void updateSelected(int row) { - if (row < 0) { - - numberLabel.setText(""); - timeLabel.setText(""); - levelLabel.setText(""); - locationLabel.setText(""); - messageLabel.setText(""); - stackTraceLabel.setText(""); - - } else { - - LogLine line = buffer.get(row); - numberLabel.setText("" + line.getLogCount()); - timeLabel.setText(String.format("%.3f s", line.getTimestamp() / 1000.0)); - levelLabel.setText(line.getLevel().toString()); - TraceException e = line.getTrace(); - if (e != null) { - locationLabel.setText(e.getMessage()); - } else { - locationLabel.setText("-"); - } - messageLabel.setText(line.getMessage()); - Throwable t = line.getCause(); - if (t != null) { - StackTraceWriter stw = new StackTraceWriter(); - PrintWriter pw = new PrintWriter(stw); - t.printStackTrace(pw); - pw.flush(); - stackTraceLabel.setText(stw.toString()); - stackTraceLabel.setCaretPosition(0); - } else { - stackTraceLabel.setText(""); - } - - } - } - - - /** - * Check whether a row signifies a number of missing rows. This check is "heuristic" - * and checks whether the timestamp is zero and the message starts with "---". - */ - private boolean isExcludedRow(int row) { - LogLine line = buffer.get(row); - return (line.getTimestamp() == 0) && (line.getMessage().startsWith("---")); - } - - - /** - * Purge the queue of incoming log lines. This is called periodically from the EDT, and - * it adds any lines in the queue to the buffer, and fires a table event. - */ - private void purgeQueue() { - int start = buffer.size(); - - LogLine line; - while ((line = queue.poll()) != null) { - buffer.add(line); - } - - int end = buffer.size() - 1; - if (end >= start) { - model.fireTableRowsInserted(start, end); - if (followBox.isSelected()) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Rectangle rect = table.getCellRect(1000000000, 1, true); - table.scrollRectToVisible(rect); - } - }); - } - } - } - - - /** - * A logger that adds log lines to the queue. This method may be called from any - * thread, and therefore must be thread-safe. - */ - private class LogListener extends LogHelper { - @Override - public void log(LogLine line) { - queue.add(line); - } - } - - private class LogFilter extends RowFilter { - - @Override - public boolean include(RowFilter.Entry entry) { - int index = entry.getIdentifier(); - LogLine line = buffer.get(index); - return filterButtons.get(line.getLevel()).isSelected(); - } - - } - - - private class Renderer extends JLabel implements TableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable table1, Object value, boolean isSelected, boolean hasFocus, - int row, int column) { - Color fg, bg; - - row = sorter.convertRowIndexToModel(row); - - if (STACK_TRACE_MARK.equals(value)) { - fg = Color.RED; - } else { - fg = table1.getForeground(); - } - bg = backgroundColors.get(buffer.get(row).getLevel()); - - if (isSelected) { - bg = bg.darker(); - } else if (isExcludedRow(row)) { - bg = bg.brighter(); - } - - this.setForeground(fg); - this.setBackground(bg); - - this.setOpaque(true); - this.setText(value.toString()); - - return this; - } - } - - - private class LocationComparator implements Comparator { - private final Pattern splitPattern = Pattern.compile("^\\(([^:]*+):([0-9]++).*\\)$"); - - @Override - public int compare(Object o1, Object o2) { - String s1 = o1.toString(); - String s2 = o2.toString(); - - Matcher m1 = splitPattern.matcher(s1); - Matcher m2 = splitPattern.matcher(s2); - - if (m1.matches() && m2.matches()) { - String class1 = m1.group(1); - String pos1 = m1.group(2); - String class2 = m2.group(1); - String pos2 = m2.group(2); - - if (class1.equals(class2)) { - return NumericComparator.INSTANCE.compare(pos1, pos2); - } else { - return class1.compareTo(class2); - } - } - - return s1.compareTo(s2); - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/DetailDialog.java b/core/src/net/sf/openrocket/gui/dialogs/DetailDialog.java deleted file mode 100644 index d1f0f547..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/DetailDialog.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Component; - -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import net.sf.openrocket.gui.util.GUIUtil; - -public class DetailDialog { - - public static void showDetailedMessageDialog(Component parentComponent, Object message, - String details, String title, int messageType) { - - if (details != null) { - JTextArea textArea = null; - textArea = new JTextArea(5, 40); - textArea.setText(details); - textArea.setCaretPosition(0); - textArea.setEditable(false); - GUIUtil.changeFontSize(textArea, -2); - JOptionPane.showMessageDialog(parentComponent, - new Object[] { message, new JScrollPane(textArea) }, - title, messageType, null); - } else { - JOptionPane.showMessageDialog(parentComponent, message, title, messageType, null); - } - - } - - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java b/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java deleted file mode 100644 index 6735e0d3..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java +++ /dev/null @@ -1,498 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Iterator; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.dialogs.motor.MotorChooserDialog; -import net.sf.openrocket.gui.main.BasicFrame; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Chars; - -public class EditMotorConfigurationDialog extends JDialog { - - private final Rocket rocket; - - private final MotorMount[] mounts; - - private final JTable configurationTable; - private final MotorConfigurationTableModel configurationTableModel; - - - private final JButton newConfButton, removeConfButton; - private final JButton selectMotorButton, removeMotorButton; - private final JTextField configurationNameField; - - - private String currentID = null; - private MotorMount currentMount = null; - - // Positive when user is modifying configuration name - private int configurationNameModification = 0; - private static final Translator trans = Application.getTranslator(); - - public EditMotorConfigurationDialog(final Rocket rocket, Window parent) { - //// Edit motor configurations - super(parent, trans.get("edtmotorconfdlg.title.Editmotorconf")); - - if (parent != null) - this.setModalityType(ModalityType.DOCUMENT_MODAL); - else - this.setModalityType(ModalityType.APPLICATION_MODAL); - - this.rocket = rocket; - - mounts = rocket.getMotorMounts().toArray( new MotorMount[0]) ; - - - - JPanel panel = new JPanel(new MigLayout("fill, flowy")); - - - //// Motor mount selection - //// Motor mounts: - JLabel label = new JLabel(trans.get("edtmotorconfdlg.lbl.Motormounts")); - panel.add(label, "gapbottom para"); - - //// Select which components function as motor mounts: - label = new JLabel(trans.get("edtmotorconfdlg.selectcomp")); - panel.add(label, "ay 100%, w 1px, growx"); - - - JTable table = new JTable(new MotorMountTableModel()); - table.setTableHeader(null); - table.setShowVerticalLines(false); - table.setRowSelectionAllowed(false); - table.setColumnSelectionAllowed(false); - - TableColumnModel columnModel = table.getColumnModel(); - TableColumn col0 = columnModel.getColumn(0); - int w = table.getRowHeight() + 2; - col0.setMinWidth(w); - col0.setPreferredWidth(w); - col0.setMaxWidth(w); - - table.addMouseListener(new GUIUtil.BooleanTableClickListener(table)); - - JScrollPane scroll = new JScrollPane(table); - panel.add(scroll, "w 200lp, h 150lp, grow, wrap 20lp"); - - - - - - //// Motor selection - //// Motor configurations: - label = new JLabel(trans.get("edtmotorconfdlg.lbl.Motorconfig")); - panel.add(label, "spanx, gapbottom para"); - - //// Configuration name: - label = new JLabel(trans.get("edtmotorconfdlg.lbl.Configname")); - //// Leave name empty for default. - String tip = trans.get("edtmotorconfdlg.lbl.Leavenamedefault"); - label.setToolTipText(tip); - panel.add(label, ""); - - configurationNameField = new JTextField(10); - configurationNameField.setToolTipText(tip); - configurationNameField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void changedUpdate(DocumentEvent e) { - update(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - update(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - update(); - } - - private void update() { - if (configurationNameModification != 0) - return; - - String text = configurationNameField.getText(); - if (currentID != null) { - configurationNameModification++; - rocket.setMotorConfigurationName(currentID, text); - int row = configurationTable.getSelectedRow(); - configurationTableModel.fireTableCellUpdated(row, 0); - updateEnabled(); - configurationNameModification--; - } - } - }); - panel.add(configurationNameField, "cell 2 1, gapright para"); - - //// New configuration - newConfButton = new JButton(trans.get("edtmotorconfdlg.but.Newconfiguration")); - newConfButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String id = rocket.newMotorConfigurationID(); - rocket.getDefaultConfiguration().setMotorConfigurationID(id); - configurationTableModel.fireTableDataChanged(); - updateEnabled(); - } - }); - panel.add(newConfButton, "cell 3 1"); - - //// Remove configuration - removeConfButton = new JButton(trans.get("edtmotorconfdlg.but.Removeconfiguration")); - removeConfButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (currentID == null) - return; - rocket.removeMotorConfigurationID(currentID); - rocket.getDefaultConfiguration().setMotorConfigurationID(null); - configurationTableModel.fireTableDataChanged(); - updateEnabled(); - } - }); - panel.add(removeConfButton, "cell 4 1"); - - - - - configurationTableModel = new MotorConfigurationTableModel(); - configurationTable = new JTable(configurationTableModel); - configurationTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - configurationTable.setCellSelectionEnabled(true); - - configurationTable.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - - if (e.getClickCount() == 1) { - - // Single click updates selection - updateEnabled(); - - } else if (e.getClickCount() == 2) { - - // Double-click edits motor - selectMotor(); - - } - - } - }); - - - scroll = new JScrollPane(configurationTable); - panel.add(scroll, "cell 1 2, spanx, w 500lp, h 150lp, grow"); - - //// Select motor - selectMotorButton = new JButton(trans.get("edtmotorconfdlg.but.Selectmotor")); - selectMotorButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - selectMotor(); - } - }); - panel.add(selectMotorButton, "spanx, flowx, split 2, ax 50%"); - - //// Remove motor button - removeMotorButton = new JButton(trans.get("edtmotorconfdlg.but.removemotor")); - removeMotorButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - removeMotor(); - } - }); - panel.add(removeMotorButton, "ax 50%"); - - - - //// Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - EditMotorConfigurationDialog.this.dispose(); - } - }); - panel.add(close, "spanx, right"); - - this.add(panel); - this.validate(); - this.pack(); - - updateEnabled(); - - this.setLocationByPlatform(true); - GUIUtil.setDisposableDialogOptions(this, close); - - // Undo description - final OpenRocketDocument document = BasicFrame.findDocument(rocket); - if (document != null) { - //// Edit motor configurations - document.startUndo(trans.get("edtmotorconfdlg.title.Editmotorconf")); - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent e) { - document.stopUndo(); - } - }); - } - } - - - - - private void updateEnabled() { - int column = configurationTable.getSelectedColumn(); - int row = configurationTable.getSelectedRow(); - - if (column < 0 || row < 0) { - currentID = null; - currentMount = null; - } else { - - currentID = findID(row); - if (column == 0) { - currentMount = null; - } else { - currentMount = findMount(column); - } - rocket.getDefaultConfiguration().setMotorConfigurationID(currentID); - - } - - if (configurationNameModification == 0) { - // Don't update name field when user is modifying it - configurationNameModification++; - - configurationNameField.setEnabled(currentID != null); - if (currentID == null) { - configurationNameField.setText(""); - } else { - configurationNameField.setText(rocket.getMotorConfigurationName(currentID)); - } - - configurationNameModification--; - } - removeConfButton.setEnabled(currentID != null); - selectMotorButton.setEnabled(currentMount != null && currentID != null); - removeMotorButton.setEnabled(currentMount != null && currentID != null); - } - - - - - private void selectMotor() { - if (currentID == null || currentMount == null) - return; - - MotorChooserDialog dialog = new MotorChooserDialog(currentMount.getMotor(currentID), - currentMount.getMotorDelay(currentID), currentMount.getMotorMountDiameter(), this); - dialog.setVisible(true); - Motor m = dialog.getSelectedMotor(); - double d = dialog.getSelectedDelay(); - - if (m != null) { - currentMount.setMotor(currentID, m); - currentMount.setMotorDelay(currentID, d); - } - - int row = configurationTable.getSelectedRow(); - configurationTableModel.fireTableRowsUpdated(row, row); - updateEnabled(); - } - - - private void removeMotor() { - if (currentID == null || currentMount == null) - return; - - currentMount.setMotor(currentID, null); - - int row = configurationTable.getSelectedRow(); - configurationTableModel.fireTableRowsUpdated(row, row); - updateEnabled(); - } - - - private String findID(int row) { - return rocket.getMotorConfigurationIDs()[row + 1]; - } - - - private MotorMount findMount(int column) { - MotorMount mount = null; - - int count = column; - for (MotorMount m : mounts) { - if (m.isMotorMount()) - count--; - if (count <= 0) { - mount = m; - break; - } - } - - if (mount == null) { - throw new IndexOutOfBoundsException("motor mount not found, column=" + column); - } - return mount; - } - - - /** - * The table model for selecting whether components are motor mounts or not. - */ - private class MotorMountTableModel extends AbstractTableModel { - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public int getRowCount() { - return mounts.length; - } - - @Override - public Class getColumnClass(int column) { - switch (column) { - case 0: - return Boolean.class; - - case 1: - return String.class; - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - @Override - public Object getValueAt(int row, int column) { - switch (column) { - case 0: - return new Boolean(mounts[row].isMotorMount()); - - case 1: - return mounts[row].toString(); - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - @Override - public boolean isCellEditable(int row, int column) { - return column == 0; - } - - @Override - public void setValueAt(Object value, int row, int column) { - if (column != 0 || !(value instanceof Boolean)) { - throw new IllegalArgumentException("column=" + column + ", value=" + value); - } - - mounts[row].setMotorMount((Boolean) value); - configurationTableModel.fireTableStructureChanged(); - updateEnabled(); - } - } - - - - /** - * The table model for selecting and editing the motor configurations. - */ - private class MotorConfigurationTableModel extends AbstractTableModel { - - @Override - public int getColumnCount() { - int count = 1; - for (MotorMount m : mounts) { - if (m.isMotorMount()) - count++; - } - return count; - } - - @Override - public int getRowCount() { - return rocket.getMotorConfigurationIDs().length - 1; - } - - @Override - public Object getValueAt(int row, int column) { - - String id = findID(row); - - if (column == 0) { - return rocket.getMotorConfigurationNameOrDescription(id); - } - - MotorMount mount = findMount(column); - Motor motor = mount.getMotor(id); - if (motor == null) - //// None - return "None"; - - String str = motor.getDesignation(mount.getMotorDelay(id)); - int count = mount.getMotorCount(); - if (count > 1) { - str = "" + count + Chars.TIMES + " " + str; - } - return str; - } - - - @Override - public String getColumnName(int column) { - if (column == 0) { - //// Configuration name - return trans.get("edtmotorconfdlg.lbl.Configname"); - } - - MotorMount mount = findMount(column); - String name = mount.toString(); - int count = mount.getMotorCount(); - if (count > 1) { - name = name + " (" + Chars.TIMES + count + ")"; - } - return name; - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/ExampleDesignDialog.java b/core/src/net/sf/openrocket/gui/dialogs/ExampleDesignDialog.java deleted file mode 100644 index 95ad56df..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/ExampleDesignDialog.java +++ /dev/null @@ -1,266 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Dialog; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.JarUtil; - -public class ExampleDesignDialog extends JDialog { - - private static final String DIRECTORY = "datafiles/examples/"; - private static final String PATTERN = ".*\\.[oO][rR][kK]$"; - private static final Translator trans = Application.getTranslator(); - - private static final FilenameFilter FILTER = new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.matches(PATTERN); - } - }; - - - private boolean open = false; - private final JList designSelection; - - private ExampleDesignDialog(ExampleDesign[] designs, Window parent) { - //// Open example design - super(parent, trans.get("exdesigndlg.lbl.Openexampledesign"), Dialog.ModalityType.APPLICATION_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill")); - - //// Select example designs to open: - panel.add(new JLabel(trans.get("exdesigndlg.lbl.Selectexample")), "wrap"); - - designSelection = new JList(designs); - designSelection.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - designSelection.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() >= 2) { - open = true; - ExampleDesignDialog.this.setVisible(false); - } - } - }); - panel.add(new JScrollPane(designSelection), "grow, wmin 300lp, wrap para"); - - //// Open button - JButton openButton = new JButton(trans.get("exdesigndlg.but.open")); - openButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - open = true; - ExampleDesignDialog.this.setVisible(false); - } - }); - panel.add(openButton, "split 2, sizegroup buttons, growx"); - - //// Cancel button - JButton cancelButton = new JButton(trans.get("dlg.but.cancel")); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - open = false; - ExampleDesignDialog.this.setVisible(false); - } - }); - panel.add(cancelButton, "sizegroup buttons, growx"); - - this.add(panel); - this.pack(); - this.setLocationByPlatform(true); - - GUIUtil.setDisposableDialogOptions(this, openButton); - } - - - /** - * Open a dialog to allow opening the example designs. - * - * @param parent the parent window of the dialog. - * @return an array of URL's to open, or null if the operation - * was cancelled. - */ - public static URL[] selectExampleDesigns(Window parent) { - - ExampleDesign[] designs; - - designs = getJarFileNames(); - if (designs == null || designs.length == 0) { - designs = getDirFileNames(); - } - if (designs == null || designs.length == 0) { - //// Example designs could not be found. - JOptionPane.showMessageDialog(parent, trans.get("exdesigndlg.lbl.Exampledesignsnotfound"), - //// Examples not found - trans.get("exdesigndlg.lbl.Examplesnotfound"), JOptionPane.ERROR_MESSAGE); - return null; - } - - Arrays.sort(designs); - - ExampleDesignDialog dialog = new ExampleDesignDialog(designs, parent); - dialog.setVisible(true); - - if (!dialog.open) { - return null; - } - - Object[] selected = dialog.designSelection.getSelectedValues(); - URL[] urls = new URL[selected.length]; - for (int i=0; i list = new ArrayList(); - int dirLength = DIRECTORY.length(); - - // Find and open the jar file this class is contained in - File file = JarUtil.getCurrentJarFile(); - if (file == null) - return null; - - - // Generate URL pointing to JAR file - URL fileUrl; - try { - fileUrl = file.toURI().toURL(); - } catch (MalformedURLException e1) { - e1.printStackTrace(); - throw new BugException(e1); - } - - // Iterate over JAR entries searching for designs - JarFile jarFile = null; - try { - jarFile = new JarFile(file); - - // Loop through JAR entries searching for files to load - Enumeration entries = jarFile.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - String name = entry.getName(); - if (name.startsWith(DIRECTORY) && FILTER.accept(null, name)) { - String urlName = "jar:" + fileUrl + "!/" + name; - URL url = new URL(urlName); - list.add(new ExampleDesign(url, - name.substring(dirLength, name.length()-4))); - } - } - - } catch (IOException e) { - // Could be normal condition if not package in JAR - return null; - } finally { - if (jarFile != null) { - try { - jarFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return list.toArray(new ExampleDesign[0]); - } - - - - /** - * Data holder class. - */ - private static class ExampleDesign implements Comparable { - - private final URL url; - private final String name; - - public ExampleDesign(URL url, String name) { - this.url = url; - this.name = name; - } - - @Override - public String toString() { - return name; - } - - public URL getURL() { - return url; - } - - @Override - public int compareTo(ExampleDesign o) { - return this.name.compareTo(o.name); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/LicenseDialog.java b/core/src/net/sf/openrocket/gui/dialogs/LicenseDialog.java deleted file mode 100644 index c3e6141e..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/LicenseDialog.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; - -public class LicenseDialog extends JDialog { - private static final String LICENSE_FILENAME = "LICENSE.TXT"; - private static final Translator trans = Application.getTranslator(); - - private static final String DEFAULT_LICENSE_TEXT = - "\n" + - "Error: Unable to load " + LICENSE_FILENAME + "!\n" + - "\n" + - "OpenRocket is licensed under the GNU GPL version 3, with additional permissions.\n" + - "See http://openrocket.sourceforge.net/ for details."; - - public LicenseDialog(JFrame parent) { - super(parent, true); - - JPanel panel = new JPanel(new MigLayout("fill")); - - panel.add(new StyledLabel("OpenRocket license", 10), "ax 50%, wrap para"); - - String licenseText; - try { - - BufferedReader reader = new BufferedReader( - new InputStreamReader(ClassLoader.getSystemResourceAsStream(LICENSE_FILENAME))); - StringBuffer sb = new StringBuffer(); - for (String s = reader.readLine(); s != null; s = reader.readLine()) { - sb.append(s); - sb.append('\n'); - } - licenseText = sb.toString(); - - } catch (IOException e) { - - licenseText = DEFAULT_LICENSE_TEXT; - - } - - JTextArea text = new JTextArea(licenseText); - text.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); - text.setRows(20); - text.setColumns(80); - text.setEditable(false); - panel.add(new JScrollPane(text),"grow, wrap para"); - - //Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - LicenseDialog.this.dispose(); - } - }); - panel.add(close, "right"); - - this.add(panel); - this.setTitle("OpenRocket license"); - this.pack(); - this.setLocationRelativeTo(parent); - - GUIUtil.setDisposableDialogOptions(this, close); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/MotorDatabaseLoadingDialog.java b/core/src/net/sf/openrocket/gui/dialogs/MotorDatabaseLoadingDialog.java deleted file mode 100644 index f19e590d..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/MotorDatabaseLoadingDialog.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.SplashScreen; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.Timer; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * A progress dialog displayed while loading motors. - * - * @author Sampo Niskanen - */ -public class MotorDatabaseLoadingDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - private MotorDatabaseLoadingDialog(Window parent) { - //// Loading motors - super(parent, trans.get("MotorDbLoadDlg.title"), ModalityType.APPLICATION_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill")); - //// Loading motors... - panel.add(new JLabel(trans.get("MotorDbLoadDlg.Loadingmotors")), "wrap para"); - - JProgressBar progress = new JProgressBar(); - progress.setIndeterminate(true); - panel.add(progress, "growx"); - - this.add(panel); - this.pack(); - this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - this.setLocationByPlatform(true); - GUIUtil.setWindowIcons(this); - } - - - /** - * Check whether the motor database is loaded and block until it is. - * An uncloseable modal dialog window is opened while loading unless the splash screen - * is still being displayed. - * - * @param parent the parent window for the dialog, or null - */ - public static void check(Window parent) { - // TODO - ugly blind cast - final ThrustCurveMotorSetDatabase db = (ThrustCurveMotorSetDatabase) Application.getMotorSetDatabase(); - if (db.isLoaded()) - return; - - if (SplashScreen.getSplashScreen() == null) { - - log.info(1, "Motor database not loaded yet, displaying dialog"); - - final MotorDatabaseLoadingDialog dialog = new MotorDatabaseLoadingDialog(parent); - - final Timer timer = new Timer(100, new ActionListener() { - private int count = 0; - - @Override - public void actionPerformed(ActionEvent e) { - count++; - if (db.isLoaded()) { - log.debug("Database loaded, closing dialog"); - dialog.setVisible(false); - } else if (count % 10 == 0) { - log.debug("Database not loaded, count=" + count); - } - } - }); - - db.setInUse(); - timer.start(); - dialog.setVisible(true); - timer.stop(); - - } else { - - log.info(1, "Motor database not loaded yet, splash screen still present, delaying until loaded"); - - db.setInUse(); - int count = 0; - while (!db.isLoaded()) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // No-op - } - - count++; - if (count % 10 == 0) { - log.debug("Database not loaded, count=" + count); - } - } - - } - - log.info("Motor database now loaded"); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java b/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java deleted file mode 100644 index bf2249ce..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * PrintPanel.java - */ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Color; -import java.awt.Desktop; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Iterator; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.print.PrintController; -import net.sf.openrocket.gui.print.PrintSettings; -import net.sf.openrocket.gui.print.PrintableContext; -import net.sf.openrocket.gui.print.TemplateProperties; -import net.sf.openrocket.gui.print.components.CheckTreeManager; -import net.sf.openrocket.gui.print.components.RocketPrintTree; -import net.sf.openrocket.gui.util.FileHelper; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; - -/** - * This class isolates the Swing components used to create a panel that is added to a standard Java print dialog. - */ -public class PrintDialog extends JDialog implements TreeSelectionListener { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private final Desktop desktop; - - private final RocketPrintTree stagedTree; - private final RocketPrintTree noStagedTree; - private OpenRocketDocument document; - private RocketPrintTree currentTree; - - private JButton previewButton; - private JButton saveAsPDF; - private JButton cancel; - - private double rotation = 0d; - - private final static SwingPreferences prefs = (SwingPreferences) Application.getPreferences(); - - /** - * Constructor. - * - * @param parent the parent awt component - * @param orDocument the OR rocket container - * @param theRotation the angle of rocket figure rotation - */ - public PrintDialog(Window parent, OpenRocketDocument orDocument, double theRotation) { - super(parent, trans.get("title"), ModalityType.APPLICATION_MODAL); - - - JPanel panel = new JPanel(new MigLayout("fill, gap rel unrel")); - this.add(panel); - rotation = theRotation; - - // before any Desktop APIs are used, first check whether the API is - // supported by this particular VM on this particular host - if (Desktop.isDesktopSupported()) { - desktop = Desktop.getDesktop(); - } else { - desktop = null; - } - - document = orDocument; - Rocket rocket = orDocument.getRocket(); - - noStagedTree = RocketPrintTree.create(rocket.getName()); - noStagedTree.setShowsRootHandles(false); - CheckTreeManager ctm = new net.sf.openrocket.gui.print.components.CheckTreeManager(noStagedTree); - ctm.addTreeSelectionListener(this); - - final int stages = rocket.getStageCount(); - - - JLabel label = new JLabel(trans.get("lbl.selectElements")); - panel.add(label, "wrap unrel"); - - // Create the tree - if (stages > 1) { - stagedTree = RocketPrintTree.create(rocket.getName(), rocket.getChildren()); - ctm = new CheckTreeManager(stagedTree); - stagedTree.setShowsRootHandles(false); - ctm.addTreeSelectionListener(this); - } else { - stagedTree = noStagedTree; - } - currentTree = stagedTree; - - // Add the tree to the UI - final JScrollPane scrollPane = new JScrollPane(stagedTree); - panel.add(scrollPane, "width 400lp, height 200lp, grow, wrap para"); - - - // Checkboxes and buttons - final JCheckBox sortByStage = new JCheckBox(trans.get("checkbox.showByStage")); - sortByStage.setEnabled(stages > 1); - sortByStage.setSelected(stages > 1); - sortByStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (sortByStage.isEnabled()) { - if (((JCheckBox) e.getSource()).isSelected()) { - scrollPane.setViewportView(stagedTree); - stagedTree.setExpandsSelectedPaths(true); - currentTree = stagedTree; - } - else { - scrollPane.setViewportView(noStagedTree); - noStagedTree.setExpandsSelectedPaths(true); - currentTree = noStagedTree; - } - } - } - }); - panel.add(sortByStage, "aligny top, split"); - - - panel.add(new JPanel(), "growx"); - - - JButton settingsButton = new JButton(trans.get("printdlg.but.settings")); - settingsButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - PrintSettings settings = getPrintSettings(); - log.debug("settings=" + settings); - PrintSettingsDialog settingsDialog = new PrintSettingsDialog(PrintDialog.this, settings); - settingsDialog.setVisible(true); - setPrintSettings(settings); - } - }); - panel.add(settingsButton, "wrap para"); - - - previewButton = new JButton(trans.get("but.previewAndPrint")); - previewButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - onPreview(); - PrintDialog.this.setVisible(false); - } - }); - panel.add(previewButton, "split, right, gap para"); - - - saveAsPDF = new JButton(trans.get("printdlg.but.saveaspdf")); - saveAsPDF.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (onSavePDF()) { - PrintDialog.this.setVisible(false); - } - } - }); - panel.add(saveAsPDF, "right, gap para"); - - - cancel = new JButton(trans.get("button.cancel")); - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - PrintDialog.this.setVisible(false); - } - }); - panel.add(cancel, "right, gap para"); - - - expandAll(currentTree, true); - if (currentTree != noStagedTree) { - expandAll(noStagedTree, true); - } - - - GUIUtil.setDisposableDialogOptions(this, previewButton); - - } - - - @Override - public void valueChanged(final TreeSelectionEvent e) { - final TreePath path = e.getNewLeadSelectionPath(); - if (path != null) { - previewButton.setEnabled(true); - saveAsPDF.setEnabled(true); - } else { - previewButton.setEnabled(false); - saveAsPDF.setEnabled(false); - } - } - - /** - * If expand is true, expands all nodes in the tree. Otherwise, collapses all nodes in the theTree. - * - * @param theTree the tree to expand/contract - * @param expand expand if true, contract if not - */ - public void expandAll(RocketPrintTree theTree, boolean expand) { - TreeNode root = (TreeNode) theTree.getModel().getRoot(); - // Traverse theTree from root - expandAll(theTree, new TreePath(root), expand); - } - - /** - * Recursively walk a tree, and if expand is true, expands all nodes in the tree. Otherwise, collapses all nodes in - * the theTree. - * - * @param theTree the tree to expand/contract - * @param parent the node to iterate/recurse over - * @param expand expand if true, contract if not - */ - private void expandAll(RocketPrintTree theTree, TreePath parent, boolean expand) { - theTree.addSelectionPath(parent); - // Traverse children - TreeNode node = (TreeNode) parent.getLastPathComponent(); - if (node.getChildCount() >= 0) { - for (Enumeration e = node.children(); e.hasMoreElements();) { - TreeNode n = (TreeNode) e.nextElement(); - TreePath path = parent.pathByAddingChild(n); - expandAll(theTree, path, expand); - } - } - // Expansion or collapse must be done bottom-up - if (expand) { - theTree.expandPath(parent); - } else { - theTree.collapsePath(parent); - } - } - - - - /** - * Generate a report using a temporary file. The file will be deleted upon JVM exit. - * - * @param settings the container of different print settings - * - * @return a file, populated with the "printed" output (the rocket info) - * - * @throws IOException thrown if the file could not be generated - */ - private File generateReport(PrintSettings settings) throws IOException { - final File f = File.createTempFile("openrocket-", ".pdf"); - f.deleteOnExit(); - return generateReport(f, settings); - } - - /** - * Generate a report to a specified file. - * - * @param f the file to which rocket data will be written - * @param settings the container of different print settings - * - * @return a file, populated with the "printed" output (the rocket info) - * - * @throws IOException thrown if the file could not be generated - */ - private File generateReport(File f, PrintSettings settings) throws IOException { - Iterator toBePrinted = currentTree.getToBePrinted(); - new PrintController().print(document, toBePrinted, new FileOutputStream(f), settings, rotation); - return f; - } - - - /** - * Handler for when the Preview button is clicked. - */ - private void onPreview() { - if (desktop != null) { - try { - PrintSettings settings = getPrintSettings(); - // TODO: HIGH: Remove UIManager, and pass settings to the actual printing methods - TemplateProperties.setColors(settings); - File f = generateReport(settings); - desktop.open(f); - } catch (IOException e) { - log.error("Could not open preview.", e); - JOptionPane.showMessageDialog(this, new String[] { - trans.get("error.preview.desc1"), - trans.get("error.preview.desc2") }, - trans.get("error.preview.title"), - JOptionPane.ERROR_MESSAGE); - } - } else { - JOptionPane.showMessageDialog(this, new String[] { - trans.get("error.preview.desc1"), - trans.get("error.preview.desc2") }, - trans.get("error.preview.title"), - JOptionPane.INFORMATION_MESSAGE); - } - } - - /** - * Handler for when the "Save as PDF" button is clicked. - * - * @return true if the PDF was saved - */ - private boolean onSavePDF() { - - JFileChooser chooser = new JFileChooser(); - chooser.setFileFilter(FileHelper.PDF_FILTER); - - // Select initial directory - File dir = document.getFile(); - if (dir != null) { - dir = dir.getParentFile(); - } - if (dir == null) { - dir = prefs.getDefaultDirectory(); - } - chooser.setCurrentDirectory(dir); - - int returnVal = chooser.showSaveDialog(this); - File file = chooser.getSelectedFile(); - if (returnVal == JFileChooser.APPROVE_OPTION && file != null) { - - file = FileHelper.ensureExtension(file, "pdf"); - if (!FileHelper.confirmWrite(file, this)) { - return false; - } - - try { - - PrintSettings settings = getPrintSettings(); - // TODO: HIGH: Remove UIManager, and pass settings to the actual printing methods - TemplateProperties.setColors(settings); - generateReport(file, settings); - - } catch (IOException e) { - FileHelper.errorWriting(e, this); - return false; - } - return true; - } else { - return false; - } - } - - public PrintSettings getPrintSettings() { - PrintSettings settings = new PrintSettings(); - Color c; - - c = prefs.getColor("print.template.fillColor", (java.awt.Color) null); - if (c != null) { - settings.setTemplateFillColor(c); - } - - c = prefs.getColor("print.template.borderColor", (java.awt.Color) null); - if (c != null) { - settings.setTemplateBorderColor(c); - } - - settings.setPaperSize(prefs.getEnum("print.paper.size", settings.getPaperSize())); - settings.setPaperOrientation(prefs.getEnum("print.paper.orientation", settings.getPaperOrientation())); - - return settings; - } - - public void setPrintSettings(PrintSettings settings) { - prefs.putColor("print.template.fillColor", settings.getTemplateFillColor() ); - prefs.putColor("print.template.borderColor", settings.getTemplateBorderColor() ); - prefs.putEnum("print.paper.size", settings.getPaperSize()); - prefs.putEnum("print.paper.orientation", settings.getPaperOrientation()); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/PrintSettingsDialog.java b/core/src/net/sf/openrocket/gui/dialogs/PrintSettingsDialog.java deleted file mode 100644 index 53411709..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/PrintSettingsDialog.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Color; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.components.ColorChooserButton; -import net.sf.openrocket.gui.print.PaperOrientation; -import net.sf.openrocket.gui.print.PaperSize; -import net.sf.openrocket.gui.print.PrintSettings; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * This class is a dialog for displaying advanced settings for printing rocket related info. - */ -public class PrintSettingsDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - /** - * Construct a dialog for setting the advanced rocket print settings. - * - * @param parent the owning dialog - */ - public PrintSettingsDialog(Window parent, final PrintSettings settings) { - ////Print settings - super(parent, trans.get("title"), ModalityType.APPLICATION_MODAL); - - - JPanel panel = new JPanel(new MigLayout("fill")); - - ////Template fill color: - panel.add(new JLabel(trans.get("lbl.Templatefillcolor"))); - final ColorChooserButton fillColorButton = new ColorChooserButton(settings.getTemplateFillColor()); - fillColorButton.addColorPropertyChangeListener(new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - Color c = (Color) evt.getNewValue(); - log.info("Template fill color changed to " + c); - settings.setTemplateFillColor(c); - } - }); - panel.add(fillColorButton, "wrap para"); - - //// Template border color: - panel.add(new JLabel(trans.get("lbl.Templatebordercolor"))); - final ColorChooserButton borderColorButton = new ColorChooserButton(settings.getTemplateBorderColor()); - borderColorButton.addColorPropertyChangeListener(new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - Color c = (Color) evt.getNewValue(); - log.info("Template border color changed to " + c); - settings.setTemplateBorderColor(c); - } - }); - panel.add(borderColorButton, "wrap para*2"); - - - - JComboBox combo = new JComboBox(new EnumModel(settings, "PaperSize")); - ////Paper size: - panel.add(new JLabel(trans.get("lbl.Papersize"))); - panel.add(combo, "growx, wrap para"); - - - combo = new JComboBox(new EnumModel(settings, "PaperOrientation")); - //// Paper orientation: - panel.add(new JLabel(trans.get("lbl.Paperorientation"))); - panel.add(combo, "growx, wrap para*2"); - - - - - //// Reset - JButton button = new JButton(trans.get("but.Reset")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Resetting print setting values to defaults"); - PrintSettings defaults = new PrintSettings(); - settings.loadFrom(defaults); - fillColorButton.setSelectedColor(settings.getTemplateFillColor()); - borderColorButton.setSelectedColor(settings.getTemplateBorderColor()); - } - }); - panel.add(button, "spanx, split, right"); - - //// Close - JButton closeButton = new JButton(trans.get("but.Close")); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - PrintSettingsDialog.this.setVisible(false); - } - }); - panel.add(closeButton, "right"); - - this.add(panel); - GUIUtil.setDisposableDialogOptions(this, closeButton); - } - - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/ScaleDialog.java b/core/src/net/sf/openrocket/gui/dialogs/ScaleDialog.java deleted file mode 100644 index 3f5db045..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/ScaleDialog.java +++ /dev/null @@ -1,625 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.BodyComponent; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.IllegalFinPointException; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RadiusRingComponent; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.ShockCord; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.rocketcomponent.ThicknessRingComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.Reflection.Method; - -/** - * Dialog that allows scaling the rocket design. - * - * @author Sampo Niskanen - */ -public class ScaleDialog extends JDialog { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - /* - * Scaler implementations - * - * Each scaled value (except override cg/mass) is defined using a Scaler instance. - */ - private static final Map, List> SCALERS = - new HashMap, List>(); - static { - List list; - - // RocketComponent - addScaler(RocketComponent.class, "PositionValue"); - SCALERS.get(RocketComponent.class).add(new OverrideScaler()); - - // BodyComponent - addScaler(BodyComponent.class, "Length"); - - // SymmetricComponent - addScaler(SymmetricComponent.class, "Thickness", "isFilled"); - - // Transition + Nose cone - addScaler(Transition.class, "ForeRadius", "isForeRadiusAutomatic"); - addScaler(Transition.class, "AftRadius", "isAftRadiusAutomatic"); - addScaler(Transition.class, "ForeShoulderRadius"); - addScaler(Transition.class, "ForeShoulderThickness"); - addScaler(Transition.class, "ForeShoulderLength"); - addScaler(Transition.class, "AftShoulderRadius"); - addScaler(Transition.class, "AftShoulderThickness"); - addScaler(Transition.class, "AftShoulderLength"); - - // Body tube - addScaler(BodyTube.class, "OuterRadius", "isOuterRadiusAutomatic"); - addScaler(BodyTube.class, "MotorOverhang"); - - // Launch lug - addScaler(LaunchLug.class, "OuterRadius"); - addScaler(LaunchLug.class, "Thickness"); - addScaler(LaunchLug.class, "Length"); - - // FinSet - addScaler(FinSet.class, "Thickness"); - addScaler(FinSet.class, "TabHeight"); - addScaler(FinSet.class, "TabLength"); - addScaler(FinSet.class, "TabShift"); - - // TrapezoidFinSet - addScaler(TrapezoidFinSet.class, "Sweep"); - addScaler(TrapezoidFinSet.class, "RootChord"); - addScaler(TrapezoidFinSet.class, "TipChord"); - addScaler(TrapezoidFinSet.class, "Height"); - - // EllipticalFinSet - addScaler(EllipticalFinSet.class, "Length"); - addScaler(EllipticalFinSet.class, "Height"); - - // FreeformFinSet - list = new ArrayList(1); - list.add(new FreeformFinSetScaler()); - SCALERS.put(FreeformFinSet.class, list); - - // MassObject - addScaler(MassObject.class, "Length"); - addScaler(MassObject.class, "Radius"); - addScaler(MassObject.class, "RadialPosition"); - - // MassComponent - list = new ArrayList(1); - list.add(new MassComponentScaler()); - SCALERS.put(MassComponent.class, list); - - // Parachute - addScaler(Parachute.class, "Diameter"); - addScaler(Parachute.class, "LineLength"); - - // Streamer - addScaler(Streamer.class, "StripLength"); - addScaler(Streamer.class, "StripWidth"); - - // ShockCord - addScaler(ShockCord.class, "CordLength"); - - // RingComponent - addScaler(RingComponent.class, "Length"); - addScaler(RingComponent.class, "RadialPosition"); - - // ThicknessRingComponent - addScaler(ThicknessRingComponent.class, "OuterRadius", "isOuterRadiusAutomatic"); - addScaler(ThicknessRingComponent.class, "Thickness"); - - // InnerTube - addScaler(InnerTube.class, "MotorOverhang"); - - // RadiusRingComponent - addScaler(RadiusRingComponent.class, "OuterRadius", "isOuterRadiusAutomatic"); - addScaler(RadiusRingComponent.class, "InnerRadius", "isInnerRadiusAutomatic"); - } - - private static void addScaler(Class componentClass, String methodName) { - addScaler(componentClass, methodName, null); - } - - private static void addScaler(Class componentClass, String methodName, String autoMethodName) { - List list = SCALERS.get(componentClass); - if (list == null) { - list = new ArrayList(); - SCALERS.put(componentClass, list); - } - list.add(new GeneralScaler(componentClass, methodName, autoMethodName)); - } - - - - - - private static final double DEFAULT_INITIAL_SIZE = 0.1; // meters - private static final double SCALE_MIN = 0.01; - private static final double SCALE_MAX = 100.0; - - private static final String SCALE_ROCKET = trans.get("lbl.scaleRocket"); - private static final String SCALE_SUBSELECTION = trans.get("lbl.scaleSubselection"); - private static final String SCALE_SELECTION = trans.get("lbl.scaleSelection"); - - - - - private final DoubleModel multiplier = new DoubleModel(1.0, UnitGroup.UNITS_RELATIVE, SCALE_MIN, SCALE_MAX); - private final DoubleModel fromField = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - private final DoubleModel toField = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - - private final OpenRocketDocument document; - private final RocketComponent selection; - private final boolean onlySelection; - - private JComboBox selectionOption; - private JCheckBox scaleMassValues; - - private boolean changing = false; - - /** - * Sole constructor. - * - * @param document the document to modify. - * @param selection the currently selected component (or null if none selected). - * @param parent the parent window. - */ - public ScaleDialog(OpenRocketDocument document, RocketComponent selection, Window parent) { - this(document, selection, parent, false); - } - - /** - * Sole constructor. - * - * @param document the document to modify. - * @param selection the currently selected component (or null if none selected). - * @param parent the parent window. - * @param onlySelection true to only allow scaling on the selected component (not the whole rocket) - */ - public ScaleDialog(OpenRocketDocument document, RocketComponent selection, Window parent, Boolean onlySelection) { - super(parent, trans.get("title"), ModalityType.APPLICATION_MODAL); - - this.document = document; - this.selection = selection; - this.onlySelection = onlySelection; - - init(); - } - - private void init() { - // Generate options for scaling - List options = new ArrayList(); - if (!onlySelection) - options.add(SCALE_ROCKET); - if (selection != null && selection.getChildCount() > 0) { - options.add(SCALE_SUBSELECTION); - } - if (selection != null) { - options.add(SCALE_SELECTION); - } - - - /* - * Select initial size for "from" field. - * - * If a component is selected, either its diameter (for SymmetricComponents) or length is selected. - * Otherwise the maximum body diameter is selected. As a fallback DEFAULT_INITIAL_SIZE is used. - */ - // - double initialSize = 0; - if (selection != null) { - if (selection instanceof SymmetricComponent) { - SymmetricComponent s = (SymmetricComponent) selection; - initialSize = s.getForeRadius() * 2; - initialSize = MathUtil.max(initialSize, s.getAftRadius() * 2); - } else { - initialSize = selection.getLength(); - } - } else { - for (RocketComponent c : document.getRocket()) { - if (c instanceof SymmetricComponent) { - SymmetricComponent s = (SymmetricComponent) c; - initialSize = s.getForeRadius() * 2; - initialSize = MathUtil.max(initialSize, s.getAftRadius() * 2); - } - } - } - if (initialSize < 0.001) { - Unit unit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - initialSize = unit.fromUnit(unit.round(unit.toUnit(DEFAULT_INITIAL_SIZE))); - } - - fromField.setValue(initialSize); - toField.setValue(initialSize); - - - // Add actions to the values - multiplier.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (!changing) { - changing = true; - updateToField(); - changing = false; - } - } - }); - fromField.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (!changing) { - changing = true; - updateToField(); - changing = false; - } - } - }); - toField.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (!changing) { - changing = true; - updateMultiplier(); - changing = false; - } - } - }); - - - - String tip; - JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - this.add(panel); - - - // Scaling selection - tip = trans.get("lbl.scale.ttip"); - JLabel label = new JLabel(trans.get("lbl.scale")); - label.setToolTipText(tip); - panel.add(label, "span, split, gapright unrel"); - - selectionOption = new JComboBox(options.toArray()); - selectionOption.setEditable(false); - selectionOption.setToolTipText(tip); - panel.add(selectionOption, "growx, wrap para*2"); - - - // Scale multiplier - tip = trans.get("lbl.scaling.ttip"); - label = new JLabel(trans.get("lbl.scaling")); - label.setToolTipText(tip); - panel.add(label, "gapright unrel"); - - - JSpinner spin = new JSpinner(multiplier.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - panel.add(spin, "w :30lp:65lp"); - - UnitSelector unit = new UnitSelector(multiplier); - unit.setToolTipText(tip); - panel.add(unit, "w 30lp"); - BasicSlider slider = new BasicSlider(multiplier.getSliderModel(0.25, 1.0, 4.0)); - slider.setToolTipText(tip); - panel.add(slider, "w 100lp, growx, wrap para"); - - - // Scale from ... to ... - tip = trans.get("lbl.scaleFromTo.ttip"); - label = new JLabel(trans.get("lbl.scaleFrom")); - label.setToolTipText(tip); - panel.add(label, "gapright unrel, right"); - - spin = new JSpinner(fromField.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - panel.add(spin, "span, split, w :30lp:65lp"); - - unit = new UnitSelector(fromField); - unit.setToolTipText(tip); - panel.add(unit, "w 30lp"); - - label = new JLabel(trans.get("lbl.scaleTo")); - label.setToolTipText(tip); - panel.add(label, "gap unrel"); - - spin = new JSpinner(toField.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - panel.add(spin, "w :30lp:65lp"); - - unit = new UnitSelector(toField); - unit.setToolTipText(tip); - panel.add(unit, "w 30lp, wrap para*2"); - - - // Scale override - scaleMassValues = new JCheckBox(trans.get("checkbox.scaleMass")); - scaleMassValues.setToolTipText(trans.get("checkbox.scaleMass.ttip")); - scaleMassValues.setSelected(true); - boolean overridden = false; - for (RocketComponent c : document.getRocket()) { - if (c instanceof MassComponent || c.isMassOverridden()) { - overridden = true; - break; - } - } - scaleMassValues.setEnabled(overridden); - panel.add(scaleMassValues, "span, wrap para*3"); - - - // Buttons - - JButton scale = new JButton(trans.get("button.scale")); - scale.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - doScale(); - ScaleDialog.this.setVisible(false); - } - }); - panel.add(scale, "span, split, right, gap para"); - - JButton cancel = new JButton(trans.get("button.cancel")); - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ScaleDialog.this.setVisible(false); - } - }); - panel.add(cancel, "right, gap para"); - - - - GUIUtil.setDisposableDialogOptions(this, scale); - } - - - - private void doScale() { - double mul = multiplier.getValue(); - if (!(SCALE_MIN <= mul && mul <= SCALE_MAX)) { - Application.getExceptionHandler().handleErrorCondition("Illegal multiplier value, mul=" + mul); - return; - } - - if (MathUtil.equals(mul, 1.0)) { - // Nothing to do - log.user("Scaling by value 1.0 - nothing to do"); - return; - } - - boolean scaleMass = scaleMassValues.isSelected(); - - Object item = selectionOption.getSelectedItem(); - log.user("Scaling design by factor " + mul + ", option=" + item); - if (SCALE_ROCKET.equals(item)) { - - // Scale the entire rocket design - try { - document.startUndo(trans.get("undo.scaleRocket")); - for (RocketComponent c : document.getRocket()) { - scale(c, mul, scaleMass); - } - } finally { - document.stopUndo(); - } - - } else if (SCALE_SUBSELECTION.equals(item)) { - - // Scale component and subcomponents - try { - document.startUndo(trans.get("undo.scaleComponents")); - for (RocketComponent c : selection) { - scale(c, mul, scaleMass); - } - } finally { - document.stopUndo(); - } - - } else if (SCALE_SELECTION.equals(item)) { - - // Scale only the selected component - try { - document.startUndo(trans.get("undo.scaleComponent")); - scale(selection, mul, scaleMass); - } finally { - document.stopUndo(); - } - - } else { - throw new BugException("Unknown item selected, item=" + item); - } - } - - - /** - * Perform scaling on a single component. - */ - private void scale(RocketComponent component, double mul, boolean scaleMass) { - - Class clazz = component.getClass(); - while (clazz != null) { - List list = SCALERS.get(clazz); - if (list != null) { - for (Scaler s : list) { - s.scale(component, mul, scaleMass); - } - } - - clazz = clazz.getSuperclass(); - } - } - - - private void updateToField() { - double mul = multiplier.getValue(); - double from = fromField.getValue(); - double to = from * mul; - toField.setValue(to); - } - - private void updateMultiplier() { - double from = fromField.getValue(); - double to = toField.getValue(); - double mul = to / from; - - if (!MathUtil.equals(from, 0)) { - mul = MathUtil.clamp(mul, SCALE_MIN, SCALE_MAX); - multiplier.setValue(mul); - } - updateToField(); - } - - - - /** - * Interface for scaling a specific component/value. - */ - private interface Scaler { - public void scale(RocketComponent c, double multiplier, boolean scaleMass); - } - - /** - * General scaler implementation that uses reflection to get/set a specific value. - */ - private static class GeneralScaler implements Scaler { - - private final Method getter; - private final Method setter; - private final Method autoMethod; - - public GeneralScaler(Class componentClass, String methodName, String autoMethodName) { - - getter = Reflection.findMethod(componentClass, "get" + methodName); - setter = Reflection.findMethod(componentClass, "set" + methodName, double.class); - if (autoMethodName != null) { - autoMethod = Reflection.findMethod(componentClass, autoMethodName); - } else { - autoMethod = null; - } - - } - - @Override - public void scale(RocketComponent c, double multiplier, boolean scaleMass) { - - // Do not scale if set to automatic - if (autoMethod != null) { - boolean auto = (Boolean) autoMethod.invoke(c); - if (auto) { - return; - } - } - - // Scale value - double value = (Double) getter.invoke(c); - value = value * multiplier; - setter.invoke(c, value); - } - - } - - - private static class OverrideScaler implements Scaler { - - @Override - public void scale(RocketComponent component, double multiplier, boolean scaleMass) { - - if (component.isCGOverridden()) { - double cgx = component.getOverrideCGX(); - cgx = cgx * multiplier; - component.setOverrideCGX(cgx); - } - - if (scaleMass && component.isMassOverridden()) { - double mass = component.getOverrideMass(); - mass = mass * MathUtil.pow3(multiplier); - component.setOverrideMass(mass); - } - } - - } - - private static class MassComponentScaler implements Scaler { - - @Override - public void scale(RocketComponent component, double multiplier, boolean scaleMass) { - if (scaleMass) { - MassComponent c = (MassComponent) component; - double mass = c.getComponentMass(); - mass = mass * MathUtil.pow3(multiplier); - c.setComponentMass(mass); - } - } - - } - - private static class FreeformFinSetScaler implements Scaler { - - @Override - public void scale(RocketComponent component, double multiplier, boolean scaleMass) { - FreeformFinSet finset = (FreeformFinSet) component; - Coordinate[] points = finset.getFinPoints(); - for (int i = 0; i < points.length; i++) { - points[i] = points[i].multiply(multiplier); - } - try { - finset.setPoints(points); - } catch (IllegalFinPointException e) { - throw new BugException("Failed to set points after scaling, original=" + Arrays.toString(finset.getFinPoints()) + " scaled=" + Arrays.toString(points), e); - } - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/SwingWorkerDialog.java b/core/src/net/sf/openrocket/gui/dialogs/SwingWorkerDialog.java deleted file mode 100644 index 13fb93b0..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/SwingWorkerDialog.java +++ /dev/null @@ -1,181 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Dimension; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.SwingWorker; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - - -/** - * A modal dialog that runs specific SwingWorkers and waits until they complete. - * A message and progress bar is provided and a cancel button. If the cancel button - * is pressed, the currently running worker is interrupted and the later workers are not - * executed. - * - * @author Sampo Niskanen - */ -public class SwingWorkerDialog extends JDialog implements PropertyChangeListener { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - /** Number of milliseconds to wait at a time between checking worker status */ - private static final int DELAY = 100; - - /** Minimum number of milliseconds to wait before estimating work length */ - private static final int ESTIMATION_DELAY = 190; - - /** Open the dialog if estimated remaining time is longer than this */ - private static final int REMAINING_TIME_FOR_DIALOG = 1000; - - /** Open the dialog if estimated total time is longed than this */ - private static final int TOTAL_TIME_FOR_DIALOG = 2000; - - - private final SwingWorker worker; - private final JProgressBar progressBar; - - private boolean cancelled = false; - - - private SwingWorkerDialog(Window parent, String title, String label, SwingWorker w) { - super(parent, title, ModalityType.APPLICATION_MODAL); - - this.worker = w; - w.addPropertyChangeListener(this); - - JPanel panel = new JPanel(new MigLayout("fill")); - - if (label != null) { - panel.add(new JLabel(label), "wrap para"); - } - - progressBar = new JProgressBar(); - panel.add(progressBar, "growx, wrap para"); - - //// Cancel button - JButton cancel = new JButton(trans.get("dlg.but.cancel")); - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("User cancelled SwingWorker operation"); - cancel(); - } - }); - panel.add(cancel, "right"); - - this.add(panel); - this.setMinimumSize(new Dimension(250, 100)); - this.pack(); - this.setLocationRelativeTo(parent); - this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - } - - @Override - public void propertyChange(PropertyChangeEvent evt) { - if (worker.getState() == SwingWorker.StateValue.DONE) { - close(); - } - progressBar.setValue(worker.getProgress()); - } - - private void cancel() { - cancelled = true; - worker.cancel(true); - close(); - } - - private void close() { - worker.removePropertyChangeListener(this); - this.setVisible(false); - // For some reason setVisible(false) is not always enough... - this.dispose(); - } - - - /** - * Run a SwingWorker and if necessary show a dialog displaying the progress of - * the worker. The progress information is obtained from the SwingWorker's - * progress property. The dialog is shown only if the worker is estimated to - * take a notable amount of time. - *

- * The dialog contains a cancel button. Clicking it will call - * worker.cancel(true) and close the dialog immediately. - * - * @param parent the parent window for the dialog, or null. - * @param title the title for the dialog. - * @param label an additional label for the dialog, or null. - * @param worker the SwingWorker to execute. - * @return true if the worker has completed normally, - * false if the user cancelled the operation - */ - public static boolean runWorker(Window parent, String title, String label, - SwingWorker worker) { - - log.info("Running SwingWorker " + worker); - - // Start timing the worker - final long startTime = System.currentTimeMillis(); - worker.execute(); - - // Monitor worker thread before opening the dialog - while (true) { - - try { - Thread.sleep(DELAY); - } catch (InterruptedException e) { - // Should never occur - log.error("EDT was interrupted", e); - } - - if (worker.isDone()) { - // Worker has completed within time limits - log.info("Worker completed before opening dialog"); - return true; - } - - // Check whether enough time has gone to get realistic estimate - long elapsed = System.currentTimeMillis() - startTime; - if (elapsed < ESTIMATION_DELAY) - continue; - - - // Calculate and check estimated remaining time - int progress = MathUtil.clamp(worker.getProgress(), 1, 100); // Avoid div-by-zero - long estimate = elapsed * 100 / progress; - long remaining = estimate - elapsed; - - log.debug("Estimated run time, estimate=" + estimate + " remaining=" + remaining); - - if (estimate >= TOTAL_TIME_FOR_DIALOG) - break; - - if (remaining >= REMAINING_TIME_FOR_DIALOG) - break; - } - - - // Dialog is required - - log.info("Opening dialog for SwingWorker " + worker); - SwingWorkerDialog dialog = new SwingWorkerDialog(parent, title, label, worker); - dialog.setVisible(true); - log.info("Worker done, cancelled=" + dialog.cancelled); - - return !dialog.cancelled; - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/UpdateInfoDialog.java b/core/src/net/sf/openrocket/gui/dialogs/UpdateInfoDialog.java deleted file mode 100644 index 3ec6d6a1..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/UpdateInfoDialog.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Collections; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.communication.UpdateInfo; -import net.sf.openrocket.gui.components.URLLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.ComparablePair; - -public class UpdateInfoDialog extends JDialog { - - private final JCheckBox remind; - private static final Translator trans = Application.getTranslator(); - - public UpdateInfoDialog(UpdateInfo info) { - //// OpenRocket update available - super((Window)null, "OpenRocket update available", ModalityType.APPLICATION_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill")); - - - panel.add(new JLabel(Icons.loadImageIcon("pix/icon/icon-about.png", "OpenRocket")), - "spany 100, top"); - - //// OpenRocket version - panel.add(new JLabel("OpenRocket version " + info.getLatestVersion() + - " is available!"), "wrap para"); - - List> updates = info.getUpdates(); - if (updates.size() > 0) { - //// Updates include: - panel.add(new JLabel("Updates include:"), "wrap rel"); - - Collections.sort(updates); - int count = 0; - int n = -1; - for (int i=updates.size()-1; i>=0; i--) { - // Add only specific number of top features - if (count >= 4 && n != updates.get(i).getU()) - break; - n = updates.get(i).getU(); - panel.add(new JLabel(" " + Chars.BULLET + " " + updates.get(i).getV()), - "wrap 0px"); - count++; - } - } - - //// Download the new version from: - panel.add(new JLabel("Download the new version from:"), - "gaptop para, alignx 50%, wrap unrel"); - panel.add(new URLLabel(AboutDialog.OPENROCKET_URL), "alignx 50%, wrap para"); - - //// Remind me later - remind = new JCheckBox("Remind me later"); - //// Show this update also the next time you start OpenRocket - remind.setToolTipText("Show this update also the next time you start OpenRocket"); - remind.setSelected(true); - panel.add(remind); - - //Close button - JButton button = new JButton(trans.get("dlg.but.close")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - UpdateInfoDialog.this.dispose(); - } - }); - panel.add(button, "right, gapright para"); - - this.add(panel); - - this.pack(); - this.setLocationRelativeTo(null); - GUIUtil.setDisposableDialogOptions(this, button); - } - - - public boolean isReminderSelected() { - return remind.isSelected(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/WarningDialog.java b/core/src/net/sf/openrocket/gui/dialogs/WarningDialog.java deleted file mode 100644 index 30ab240f..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/WarningDialog.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.gui.dialogs; - -import java.awt.Component; - -import javax.swing.JDialog; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; - -public class WarningDialog extends JDialog { - - public static void showWarnings(Component parent, Object message, String title, - WarningSet warnings) { - - Warning[] w = warnings.toArray(new Warning[0]); - JList list = new JList(w); - JScrollPane pane = new JScrollPane(list); - - JOptionPane.showMessageDialog(parent, new Object[] { message, pane }, - title, JOptionPane.WARNING_MESSAGE); - - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/CloseableDialog.java b/core/src/net/sf/openrocket/gui/dialogs/motor/CloseableDialog.java deleted file mode 100644 index 48e58a0f..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/CloseableDialog.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor; - -public interface CloseableDialog { - - /** - * Close this dialog. - * - * @param ok whether "OK" should be considered to have been clicked. - */ - public void close(boolean ok); - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java b/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java deleted file mode 100644 index ca4205d2..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java +++ /dev/null @@ -1,115 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor; - - -import java.awt.Dialog; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog; -import net.sf.openrocket.gui.dialogs.motor.thrustcurve.ThrustCurveMotorSelectionPanel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; - -public class MotorChooserDialog extends JDialog implements CloseableDialog { - - private final ThrustCurveMotorSelectionPanel selectionPanel; - - private boolean okClicked = false; - private static final Translator trans = Application.getTranslator(); - - - public MotorChooserDialog(Motor current, double delay, double diameter, Window owner) { - super(owner, trans.get ("MotorChooserDialog.title"), Dialog.ModalityType.APPLICATION_MODAL); - - // Check that the motor database has been loaded properly - MotorDatabaseLoadingDialog.check(null); - - - JPanel panel = new JPanel(new MigLayout("fill")); - - selectionPanel = new ThrustCurveMotorSelectionPanel((ThrustCurveMotor) current, delay, diameter); - - panel.add(selectionPanel, "grow, wrap para"); - - - // OK / Cancel buttons - JButton okButton = new JButton(trans.get("dlg.but.ok")); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - close(true); - } - }); - panel.add(okButton, "tag ok, spanx, split"); - - //// Cancel button - JButton cancelButton = new JButton(trans.get("dlg.but.cancel")); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - close(false); - } - }); - panel.add(cancelButton, "tag cancel"); - - this.add(panel); - - this.setModal(true); - this.pack(); - this.setLocationByPlatform(true); - GUIUtil.setDisposableDialogOptions(this, okButton); - - JComponent focus = selectionPanel.getDefaultFocus(); - if (focus != null) { - focus.grabFocus(); - } - - // Set the closeable dialog after all initialization - selectionPanel.setCloseableDialog(this); - } - - - /** - * Return the motor selected by this chooser dialog, or null if the selection has been aborted. - * - * @return the selected motor, or null if no motor has been selected or the selection was canceled. - */ - public Motor getSelectedMotor() { - if (!okClicked) - return null; - return selectionPanel.getSelectedMotor(); - } - - /** - * Return the selected ejection charge delay. - * - * @return the selected ejection charge delay. - */ - public double getSelectedDelay() { - return selectionPanel.getSelectedDelay(); - } - - - - @Override - public void close(boolean ok) { - okClicked = ok; - this.setVisible(false); - - Motor selected = getSelectedMotor(); - if (okClicked && selected != null) { - selectionPanel.selectedMotor(selected); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/MotorSelector.java b/core/src/net/sf/openrocket/gui/dialogs/motor/MotorSelector.java deleted file mode 100644 index 23bd9984..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/MotorSelector.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor; - -import javax.swing.JComponent; - -import net.sf.openrocket.motor.Motor; - -public interface MotorSelector { - - /** - * Return the currently selected motor. - * - * @return the currently selected motor, or null if no motor is selected. - */ - public Motor getSelectedMotor(); - - /** - * Return the currently selected ejection charge delay. - * - * @return the currently selected ejection charge delay. - */ - public double getSelectedDelay(); - - /** - * Return the component that should have the default focus in this motor selector panel. - * - * @return the component that should have default focus, or null for none. - */ - public JComponent getDefaultFocus(); - - /** - * Notify that the provided motor has been selected. This can be used to store preference - * data for later usage. - * - * @param m the motor that was selected. - */ - public void selectedMotor(Motor m); - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/MotorClass.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/MotorClass.java deleted file mode 100644 index b6b35561..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/MotorClass.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; - -/** - * NAR approved motor classes (http://www.nar.org/NARmotors.html). - * - * @author Sampo Niskanen - */ -public enum MotorClass { - - A18("1/8A", 0, 0.3125), - A14("1/4A", 0.3125, 0.625), - A12("1/2A", 0.625, 1.25), - A("A", 1.25, 2.5), - B("B", 2.5, 5), - C("C", 5, 10), - D("D", 10, 20), - E("E", 20, 40), - F("F", 40, 80), - G("G", 80, 160), - H("H", 160, 320), - I("I", 320, 640), - J("J", 640, 1280), - K("K", 1280, 2560), - L("L", 2560, 5120), - M("M", 5120, 10240), - N("N", 10240, 20480), - O("O", 20480, 40960), - OVER("> O", 40960, Double.MAX_VALUE) { - @Override - public String getDescription(double impulse) { - return "Over O"; - } - - @Override - public String getClassDescription() { - return "Over O-class (over " + UnitGroup.UNITS_IMPULSE.toStringUnit(40960) + ")"; - } - }; - - - private final String className; - private final double min; - private final double max; - - - private MotorClass(String className, double min, double max) { - this.className = className; - this.min = min; - this.max = max; - } - - - public String getDescription(double impulse) { - double percent = (impulse - min) / (max - min) * 100; - if (percent < 1) { - // 0% looks stupid - percent = 1; - } - return String.format("%d%% %s", Math.round(percent), className); - } - - public String getClassDescription() { - return "Class " + className + " (" + UnitGroup.UNITS_IMPULSE.toStringUnit(min) + " - " + UnitGroup.UNITS_IMPULSE.toStringUnit(max) + ")"; - } - - - /** - * Find the appropriate motor class for the provided impulse. - */ - public static MotorClass getMotorClass(double impulse) { - double epsilon = 0.0000001; - - // Round large values so 640.1 Ns (which is displayed as 640 Ns) is counted as I-class - if (impulse >= 100) { - impulse = Math.rint(impulse); - } - - for (MotorClass m : MotorClass.values()) { - if (impulse <= m.max + epsilon) { - return m; - } - } - throw new BugException("Could not find motor class for impulse " + impulse); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/MotorHolder.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/MotorHolder.java deleted file mode 100644 index bb811333..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/MotorHolder.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import net.sf.openrocket.motor.ThrustCurveMotor; - -class MotorHolder { - - private final ThrustCurveMotor motor; - private final int index; - - public MotorHolder(ThrustCurveMotor motor, int index) { - this.motor = motor; - this.index = index; - } - - public ThrustCurveMotor getMotor() { - return motor; - } - - public int getIndex() { - return index; - } - - @Override - public String toString() { - return motor.getDesignation(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof MotorHolder)) - return false; - MotorHolder other = (MotorHolder) obj; - return this.motor.equals(other.motor); - } - - @Override - public int hashCode() { - return motor.hashCode(); - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorColumns.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorColumns.java deleted file mode 100644 index 7520a01b..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorColumns.java +++ /dev/null @@ -1,146 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import java.text.Collator; -import java.util.Comparator; - -import net.sf.openrocket.database.ThrustCurveMotorSet; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.DesignationComparator; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.unit.ValueComparator; - - -/** - * Enum defining the table columns. - */ - -enum ThrustCurveMotorColumns { - //// Manufacturer - MANUFACTURER("TCurveMotorCol.MANUFACTURER", 100) { - @Override - public String getValue(ThrustCurveMotorSet m) { - return m.getManufacturer().getDisplayName(); - } - - @Override - public Comparator getComparator() { - return Collator.getInstance(); - } - }, - //// Designation - DESIGNATION("TCurveMotorCol.DESIGNATION") { - @Override - public String getValue(ThrustCurveMotorSet m) { - return m.getDesignation(); - } - - @Override - public Comparator getComparator() { - return new DesignationComparator(); - } - }, - //// Type - TYPE("TCurveMotorCol.TYPE") { - @Override - public String getValue(ThrustCurveMotorSet m) { - return m.getType().getName(); - } - - @Override - public Comparator getComparator() { - return Collator.getInstance(); - } - }, - //// Diameter - DIAMETER("TCurveMotorCol.DIAMETER") { - @Override - public Object getValue(ThrustCurveMotorSet m) { - return new Value(m.getDiameter(), UnitGroup.UNITS_MOTOR_DIMENSIONS); - } - - @Override - public Comparator getComparator() { - return ValueComparator.INSTANCE; - } - }, - //// Length - LENGTH("TCurveMotorCol.LENGTH") { - @Override - public Object getValue(ThrustCurveMotorSet m) { - return new Value(m.getLength(), UnitGroup.UNITS_MOTOR_DIMENSIONS); - } - - @Override - public Comparator getComparator() { - return ValueComparator.INSTANCE; - } - }; - - - private final String title; - private final int width; - private static final Translator trans = Application.getTranslator(); - - ThrustCurveMotorColumns(String title) { - this(title, 50); - } - - ThrustCurveMotorColumns(String title, int width) { - this.title = title; - this.width = width; - } - - - public abstract Object getValue(ThrustCurveMotorSet m); - - public abstract Comparator getComparator(); - - public String getTitle() { - return trans.get(title); - } - - public int getWidth() { - return width; - } - - public String getToolTipText(ThrustCurveMotor m) { - String tip = ""; - tip += "" + m.toString() + ""; - tip += " (" + m.getMotorType().getDescription() + ")


"; - - String desc = m.getDescription().trim(); - if (desc.length() > 0) { - tip += "" + desc.replace("\n", "
") + "


"; - } - - tip += (trans.get("TCurveMotor.ttip.diameter") + " " + - UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit().toStringUnit(m.getDiameter()) + - "
"); - tip += (trans.get("TCurveMotor.ttip.length") + " " + - UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit().toStringUnit(m.getLength()) + - "
"); - tip += (trans.get("TCurveMotor.ttip.maxThrust") + " " + - UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(m.getMaxThrustEstimate()) + - "
"); - tip += (trans.get("TCurveMotor.ttip.avgThrust") + " " + - UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(m.getAverageThrustEstimate()) + - "
"); - tip += (trans.get("TCurveMotor.ttip.burnTime") + " " + - UnitGroup.UNITS_SHORT_TIME.getDefaultUnit() - .toStringUnit(m.getBurnTimeEstimate()) + "
"); - tip += (trans.get("TCurveMotor.ttip.totalImpulse") + " " + - UnitGroup.UNITS_IMPULSE.getDefaultUnit() - .toStringUnit(m.getTotalImpulseEstimate()) + "
"); - tip += (trans.get("TCurveMotor.ttip.launchMass") + " " + - UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(m.getLaunchCG().weight) + - "
"); - tip += (trans.get("TCurveMotor.ttip.emptyMass") + " " + - UnitGroup.UNITS_MASS.getDefaultUnit() - .toStringUnit(m.getEmptyCG().weight)); - return tip; - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorComparator.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorComparator.java deleted file mode 100644 index 0096bf17..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorComparator.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import java.util.Comparator; - -import net.sf.openrocket.motor.ThrustCurveMotor; - -/** - * Compares two ThrustCurveMotor objects for quality. - * - * @author Sampo Niskanen - */ -public class ThrustCurveMotorComparator implements Comparator { - - - @Override - public int compare(ThrustCurveMotor o1, ThrustCurveMotor o2) { - return calculateGoodness(o2) - calculateGoodness(o1); - } - - - private int calculateGoodness(ThrustCurveMotor motor) { - /* - * 10 chars of comments correspond to one thrust point, max ten points. - */ - int commentLength = Math.min(motor.getDescription().length(), 100); - return motor.getTimePoints().length * 10 + commentLength; - } - - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorDatabaseModel.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorDatabaseModel.java deleted file mode 100644 index 2dc92bd3..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorDatabaseModel.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import java.util.List; - -import javax.swing.table.AbstractTableModel; - -import net.sf.openrocket.database.ThrustCurveMotorSet; - -class ThrustCurveMotorDatabaseModel extends AbstractTableModel { - private final List database; - - public ThrustCurveMotorDatabaseModel(List database) { - this.database = database; - } - - @Override - public int getColumnCount() { - return ThrustCurveMotorColumns.values().length; - } - - @Override - public int getRowCount() { - return database.size(); - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - ThrustCurveMotorColumns column = getColumn(columnIndex); - return column.getValue(database.get(rowIndex)); - } - - @Override - public String getColumnName(int columnIndex) { - return getColumn(columnIndex).getTitle(); - } - - - public ThrustCurveMotorSet getMotorSet(int rowIndex) { - return database.get(rowIndex); - } - - - public int getIndex(ThrustCurveMotorSet m) { - return database.indexOf(m); - } - - private ThrustCurveMotorColumns getColumn(int index) { - return ThrustCurveMotorColumns.values()[index]; - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorPlotDialog.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorPlotDialog.java deleted file mode 100644 index c1ecb7cf..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorPlotDialog.java +++ /dev/null @@ -1,134 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Rectangle; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.renderer.xy.StandardXYItemRenderer; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; - -public class ThrustCurveMotorPlotDialog extends JDialog { - private static final Translator trans = Application.getTranslator(); - - public ThrustCurveMotorPlotDialog(List motors, int selected, Window parent) { - super(parent, "Motor thrust curves", ModalityType.APPLICATION_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill")); - - // Thrust curve plot - JFreeChart chart = ChartFactory.createXYLineChart( - "Motor thrust curves", // title - "Time / " + UnitGroup.UNITS_SHORT_TIME.getDefaultUnit().getUnit(), // xAxisLabel - "Thrust / " + UnitGroup.UNITS_FORCE.getDefaultUnit().getUnit(), // yAxisLabel - null, // dataset - PlotOrientation.VERTICAL, - true, // legend - true, // tooltips - false // urls - ); - - - // Add the data and formatting to the plot - XYPlot plot = chart.getXYPlot(); - - chart.setBackgroundPaint(panel.getBackground()); - plot.setBackgroundPaint(Color.WHITE); - plot.setDomainGridlinePaint(Color.LIGHT_GRAY); - plot.setRangeGridlinePaint(Color.LIGHT_GRAY); - - ChartPanel chartPanel = new ChartPanel(chart, - false, // properties - true, // save - false, // print - true, // zoom - true); // tooltips - chartPanel.setMouseWheelEnabled(true); - chartPanel.setEnforceFileExtensions(true); - chartPanel.setInitialDelay(500); - - StandardXYItemRenderer renderer = new StandardXYItemRenderer(); - renderer.setBaseShapesVisible(true); - renderer.setBaseShapesFilled(true); - plot.setRenderer(renderer); - - - // Create the plot data set - XYSeriesCollection dataset = new XYSeriesCollection(); - - // Selected thrust curve - int n = 0; - if (selected >= 0) { - dataset.addSeries(generateSeries(motors.get(selected))); - renderer.setSeriesStroke(n, new BasicStroke(1.5f)); - renderer.setSeriesPaint(n, ThrustCurveMotorSelectionPanel.getColor(selected)); - } - n++; - - // Other thrust curves - for (int i = 0; i < motors.size(); i++) { - if (i == selected) - continue; - - ThrustCurveMotor m = motors.get(i); - dataset.addSeries(generateSeries(m)); - renderer.setSeriesStroke(n, new BasicStroke(1.5f)); - renderer.setSeriesPaint(n, ThrustCurveMotorSelectionPanel.getColor(i)); - renderer.setSeriesShape(n, new Rectangle()); - n++; - } - - plot.setDataset(dataset); - - panel.add(chartPanel, "width 600:600:, height 400:400:, grow, wrap para"); - - - // Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ThrustCurveMotorPlotDialog.this.setVisible(false); - } - }); - panel.add(close, "right, tag close"); - - - this.add(panel); - - this.pack(); - GUIUtil.setDisposableDialogOptions(this, null); - } - - - private XYSeries generateSeries(ThrustCurveMotor motor) { - XYSeries series = new XYSeries(motor.getManufacturer() + " " + motor.getDesignation()); - double[] time = motor.getTimePoints(); - double[] thrust = motor.getThrustPoints(); - - for (int j = 0; j < time.length; j++) { - series.add(time[j], thrust[j]); - } - return series; - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorSelectionPanel.java b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorSelectionPanel.java deleted file mode 100644 index 7deaaa8f..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorSelectionPanel.java +++ /dev/null @@ -1,1002 +0,0 @@ -package net.sf.openrocket.gui.dialogs.motor.thrustcurve; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Font; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.prefs.Preferences; - -import javax.swing.BorderFactory; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JTable; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListCellRenderer; -import javax.swing.ListSelectionModel; -import javax.swing.RowFilter; -import javax.swing.SwingUtilities; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableModel; -import javax.swing.table.TableRowSorter; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.ThrustCurveMotorSet; -import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.dialogs.motor.CloseableDialog; -import net.sf.openrocket.gui.dialogs.motor.MotorSelector; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.utils.MotorCorrelation; - -import org.jfree.chart.ChartColor; -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.axis.ValueAxis; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.title.TextTitle; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; - -public class ThrustCurveMotorSelectionPanel extends JPanel implements MotorSelector { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private static final double MOTOR_SIMILARITY_THRESHOLD = 0.95; - - private static final int SHOW_ALL = 0; - private static final int SHOW_SMALLER = 1; - private static final int SHOW_EXACT = 2; - private static final String[] SHOW_DESCRIPTIONS = { - //// Show all motors - trans.get("TCMotorSelPan.SHOW_DESCRIPTIONS.desc1"), - //// Show motors with diameter less than that of the motor mount - trans.get("TCMotorSelPan.SHOW_DESCRIPTIONS.desc2"), - //// Show motors with diameter equal to that of the motor mount - trans.get("TCMotorSelPan.SHOW_DESCRIPTIONS.desc3") - }; - private static final int SHOW_MAX = 2; - - private static final int ZOOM_ICON_POSITION_NEGATIVE_X = 50; - private static final int ZOOM_ICON_POSITION_POSITIVE_Y = 12; - - private static final Paint[] CURVE_COLORS = ChartColor.createDefaultPaintArray(); - - private static final Color NO_COMMENT_COLOR = Color.GRAY; - private static final Color WITH_COMMENT_COLOR = Color.BLACK; - - private static final ThrustCurveMotorComparator MOTOR_COMPARATOR = new ThrustCurveMotorComparator(); - - - - private final List database; - - private final double diameter; - private CloseableDialog dialog = null; - - - private final ThrustCurveMotorDatabaseModel model; - private final JTable table; - private final TableRowSorter sorter; - - private final JCheckBox hideSimilarBox; - - private final JTextField searchField; - private String[] searchTerms = new String[0]; - - - private final JLabel curveSelectionLabel; - private final JComboBox curveSelectionBox; - private final DefaultComboBoxModel curveSelectionModel; - - private final JLabel totalImpulseLabel; - private final JLabel classificationLabel; - private final JLabel avgThrustLabel; - private final JLabel maxThrustLabel; - private final JLabel burnTimeLabel; - private final JLabel launchMassLabel; - private final JLabel emptyMassLabel; - private final JLabel dataPointsLabel; - private final JLabel digestLabel; - - private final JTextArea comment; - private final Font noCommentFont; - private final Font withCommentFont; - - private final JFreeChart chart; - private final ChartPanel chartPanel; - private final JLabel zoomIcon; - - private final JComboBox delayBox; - - private ThrustCurveMotor selectedMotor; - private ThrustCurveMotorSet selectedMotorSet; - private double selectedDelay; - - - /** - * Sole constructor. - * - * @param current the currently selected ThrustCurveMotor, or null for none. - * @param delay the currently selected ejection charge delay. - * @param diameter the diameter of the motor mount. - */ - public ThrustCurveMotorSelectionPanel(ThrustCurveMotor current, double delay, double diameter) { - super(new MigLayout("fill", "[grow][]")); - - this.diameter = diameter; - - - // Construct the database (adding the current motor if not in the db already) - List db; - // TODO - ugly blind cast. - db = ((ThrustCurveMotorSetDatabase) Application.getMotorSetDatabase()).getMotorSets(); - - // If current motor is not found in db, add a new ThrustCurveMotorSet containing it - if (current != null) { - selectedMotor = current; - for (ThrustCurveMotorSet motorSet : db) { - if (motorSet.getMotors().contains(current)) { - selectedMotorSet = motorSet; - break; - } - } - if (selectedMotorSet == null) { - db = new ArrayList(db); - ThrustCurveMotorSet extra = new ThrustCurveMotorSet(); - extra.addMotor(current); - selectedMotorSet = extra; - db.add(extra); - Collections.sort(db); - } - } - database = db; - - - - //// GUI - - JPanel panel; - JLabel label; - - panel = new JPanel(new MigLayout("fill")); - this.add(panel, "grow"); - - - - // Selection label - //// Select rocket motor: - label = new StyledLabel(trans.get("TCMotorSelPan.lbl.Selrocketmotor"), Style.BOLD); - panel.add(label, "spanx, wrap para"); - - // Diameter selection - JComboBox filterComboBox = new JComboBox(SHOW_DESCRIPTIONS); - filterComboBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JComboBox cb = (JComboBox) e.getSource(); - int sel = cb.getSelectedIndex(); - if ((sel < 0) || (sel > SHOW_MAX)) - sel = SHOW_ALL; - switch (sel) { - case SHOW_ALL: - sorter.setRowFilter(new MotorRowFilterAll()); - break; - - case SHOW_SMALLER: - sorter.setRowFilter(new MotorRowFilterSmaller()); - break; - - case SHOW_EXACT: - sorter.setRowFilter(new MotorRowFilterExact()); - break; - - default: - throw new BugException("Invalid selection mode sel=" + sel); - } - Application.getPreferences().putChoice("MotorDiameterMatch", sel); - scrollSelectionVisible(); - } - }); - panel.add(filterComboBox, "spanx, growx, wrap rel"); - - //// Hide very similar thrust curves - hideSimilarBox = new JCheckBox(trans.get("TCMotorSelPan.checkbox.hideSimilar")); - GUIUtil.changeFontSize(hideSimilarBox, -1); - hideSimilarBox.setSelected(Application.getPreferences().getBoolean(net.sf.openrocket.startup.Preferences.MOTOR_HIDE_SIMILAR, true)); - hideSimilarBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Application.getPreferences().putBoolean(net.sf.openrocket.startup.Preferences.MOTOR_HIDE_SIMILAR, hideSimilarBox.isSelected()); - updateData(); - } - }); - panel.add(hideSimilarBox, "gapleft para, spanx, growx, wrap para"); - - - // Motor selection table - model = new ThrustCurveMotorDatabaseModel(database); - table = new JTable(model); - - - // Set comparators and widths - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - sorter = new TableRowSorter(model); - for (int i = 0; i < ThrustCurveMotorColumns.values().length; i++) { - ThrustCurveMotorColumns column = ThrustCurveMotorColumns.values()[i]; - sorter.setComparator(i, column.getComparator()); - table.getColumnModel().getColumn(i).setPreferredWidth(column.getWidth()); - } - table.setRowSorter(sorter); - - // Set selection and double-click listeners - table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - int row = table.getSelectedRow(); - if (row >= 0) { - row = table.convertRowIndexToModel(row); - ThrustCurveMotorSet motorSet = model.getMotorSet(row); - log.user("Selected table row " + row + ": " + motorSet); - if (motorSet != selectedMotorSet) { - select(selectMotor(motorSet)); - } - } else { - log.user("Selected table row " + row + ", nothing selected"); - } - } - }); - table.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { - if (dialog != null) { - dialog.close(true); - } - } - } - }); - - - JScrollPane scrollpane = new JScrollPane(); - scrollpane.setViewportView(table); - panel.add(scrollpane, "grow, width :500:, height :300:, spanx, wrap para"); - - - - - // Motor mount diameter label - //// Motor mount diameter: - label = new StyledLabel(trans.get("TCMotorSelPan.lbl.Motormountdia") + " " + - UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit().toStringUnit(diameter)); - panel.add(label, "gapright 30lp, spanx, split"); - - - - // Search field - //// Search: - label = new StyledLabel(trans.get("TCMotorSelPan.lbl.Search")); - panel.add(label, ""); - - searchField = new JTextField(); - searchField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void changedUpdate(DocumentEvent e) { - update(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - update(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - update(); - } - - private void update() { - String text = searchField.getText().trim(); - String[] split = text.split("\\s+"); - ArrayList list = new ArrayList(); - for (String s : split) { - s = s.trim().toLowerCase(Locale.getDefault()); - if (s.length() > 0) { - list.add(s); - } - } - searchTerms = list.toArray(new String[0]); - sorter.sort(); - scrollSelectionVisible(); - } - }); - panel.add(searchField, "growx, wrap"); - - - - // Vertical split - this.add(panel, "grow"); - this.add(new JSeparator(JSeparator.VERTICAL), "growy, gap para para"); - panel = new JPanel(new MigLayout("fill")); - - - - // Thrust curve selection - //// Select thrust curve: - curveSelectionLabel = new JLabel(trans.get("TCMotorSelPan.lbl.Selectthrustcurve")); - panel.add(curveSelectionLabel); - - curveSelectionModel = new DefaultComboBoxModel(); - curveSelectionBox = new JComboBox(curveSelectionModel); - curveSelectionBox.setRenderer(new CurveSelectionRenderer(curveSelectionBox.getRenderer())); - curveSelectionBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object value = curveSelectionBox.getSelectedItem(); - if (value != null) { - select(((MotorHolder) value).getMotor()); - } - } - }); - panel.add(curveSelectionBox, "growx, wrap para"); - - - - - - // Ejection charge delay: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Ejectionchargedelay"))); - - delayBox = new JComboBox(); - delayBox.setEditable(true); - delayBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JComboBox cb = (JComboBox) e.getSource(); - String sel = (String) cb.getSelectedItem(); - //// None - if (sel.equalsIgnoreCase(trans.get("TCMotorSelPan.equalsIgnoreCase.None"))) { - selectedDelay = Motor.PLUGGED; - } else { - try { - selectedDelay = Double.parseDouble(sel); - } catch (NumberFormatException ignore) { - } - } - setDelays(false); - } - }); - panel.add(delayBox, "growx, wrap rel"); - //// (Number of seconds or \"None\") - panel.add(new StyledLabel(trans.get("TCMotorSelPan.lbl.NumberofsecondsorNone"), -3), "skip, wrap para"); - setDelays(false); - - - panel.add(new JSeparator(), "spanx, growx, wrap para"); - - - - // Thrust curve info - //// Total impulse: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Totalimpulse"))); - totalImpulseLabel = new JLabel(); - panel.add(totalImpulseLabel, "split"); - classificationLabel = new JLabel(); - classificationLabel.setEnabled(false); // Gray out - panel.add(classificationLabel, "gapleft unrel, wrap"); - - //// Avg. thrust: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Avgthrust"))); - avgThrustLabel = new JLabel(); - panel.add(avgThrustLabel, "wrap"); - - //// Max. thrust: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Maxthrust"))); - maxThrustLabel = new JLabel(); - panel.add(maxThrustLabel, "wrap"); - - //// Burn time: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Burntime"))); - burnTimeLabel = new JLabel(); - panel.add(burnTimeLabel, "wrap"); - - //// Launch mass: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Launchmass"))); - launchMassLabel = new JLabel(); - panel.add(launchMassLabel, "wrap"); - - //// Empty mass: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Emptymass"))); - emptyMassLabel = new JLabel(); - panel.add(emptyMassLabel, "wrap"); - - //// Data points: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Datapoints"))); - dataPointsLabel = new JLabel(); - panel.add(dataPointsLabel, "wrap para"); - - if (System.getProperty("openrocket.debug.motordigest") != null) { - //// Digest: - panel.add(new JLabel(trans.get("TCMotorSelPan.lbl.Digest"))); - digestLabel = new JLabel(); - panel.add(digestLabel, "w :300:, wrap para"); - } else { - digestLabel = null; - } - - - comment = new JTextArea(5, 5); - GUIUtil.changeFontSize(comment, -2); - withCommentFont = comment.getFont(); - noCommentFont = withCommentFont.deriveFont(Font.ITALIC); - comment.setLineWrap(true); - comment.setWrapStyleWord(true); - comment.setEditable(false); - scrollpane = new JScrollPane(comment); - panel.add(scrollpane, "spanx, growx, wrap para"); - - - - - // Thrust curve plot - chart = ChartFactory.createXYLineChart( - null, // title - null, // xAxisLabel - null, // yAxisLabel - null, // dataset - PlotOrientation.VERTICAL, - false, // legend - false, // tooltips - false // urls - ); - - - // Add the data and formatting to the plot - XYPlot plot = chart.getXYPlot(); - - changeLabelFont(plot.getRangeAxis(), -2); - changeLabelFont(plot.getDomainAxis(), -2); - - //// Thrust curve: - chart.setTitle(new TextTitle(trans.get("TCMotorSelPan.title.Thrustcurve"), this.getFont())); - chart.setBackgroundPaint(this.getBackground()); - plot.setBackgroundPaint(Color.WHITE); - plot.setDomainGridlinePaint(Color.LIGHT_GRAY); - plot.setRangeGridlinePaint(Color.LIGHT_GRAY); - - chartPanel = new ChartPanel(chart, - false, // properties - false, // save - false, // print - false, // zoom - false); // tooltips - chartPanel.setMouseZoomable(false); - chartPanel.setPopupMenu(null); - chartPanel.setMouseWheelEnabled(false); - chartPanel.setRangeZoomable(false); - chartPanel.setDomainZoomable(false); - - chartPanel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - chartPanel.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (selectedMotor == null || selectedMotorSet == null) - return; - if (e.getButton() == MouseEvent.BUTTON1) { - // Open plot dialog - List motors = getFilteredCurves(); - ThrustCurveMotorPlotDialog plotDialog = new ThrustCurveMotorPlotDialog(motors, - motors.indexOf(selectedMotor), - SwingUtilities.getWindowAncestor(ThrustCurveMotorSelectionPanel.this)); - plotDialog.setVisible(true); - } - } - }); - - JLayeredPane layer = new CustomLayeredPane(); - - layer.setBorder(BorderFactory.createLineBorder(Color.BLUE)); - - layer.add(chartPanel, (Integer) 0); - - zoomIcon = new JLabel(Icons.ZOOM_IN); - zoomIcon.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - layer.add(zoomIcon, (Integer) 1); - - - panel.add(layer, "width 300:300:, height 180:180:, grow, spanx"); - - - - this.add(panel, "grow"); - - - - // Sets the filter: - int showMode = Application.getPreferences().getChoice(net.sf.openrocket.startup.Preferences.MOTOR_DIAMETER_FILTER, SHOW_MAX, SHOW_EXACT); - filterComboBox.setSelectedIndex(showMode); - - - // Update the panel data - updateData(); - selectedDelay = delay; - setDelays(false); - - } - - - @Override - public Motor getSelectedMotor() { - return selectedMotor; - } - - - @Override - public double getSelectedDelay() { - return selectedDelay; - } - - - @Override - public JComponent getDefaultFocus() { - return searchField; - } - - @Override - public void selectedMotor(Motor motorSelection) { - if (!(motorSelection instanceof ThrustCurveMotor)) { - log.error("Received argument that was not ThrustCurveMotor: " + motorSelection); - return; - } - - ThrustCurveMotor motor = (ThrustCurveMotor) motorSelection; - ThrustCurveMotorSet set = findMotorSet(motor); - if (set == null) { - log.error("Could not find set for motor:" + motorSelection); - return; - } - - // Store selected motor in preferences node, set all others to false - Preferences prefs = ((SwingPreferences) Application.getPreferences()).getNode(net.sf.openrocket.startup.Preferences.PREFERRED_THRUST_CURVE_MOTOR_NODE); - for (ThrustCurveMotor m : set.getMotors()) { - String digest = m.getDigest(); - prefs.putBoolean(digest, m == motor); - } - } - - public void setCloseableDialog(CloseableDialog dialog) { - this.dialog = dialog; - } - - - - private void changeLabelFont(ValueAxis axis, float size) { - Font font = axis.getTickLabelFont(); - font = font.deriveFont(font.getSize2D() + size); - axis.setTickLabelFont(font); - } - - - /** - * Called when a different motor is selected from within the panel. - */ - private void select(ThrustCurveMotor motor) { - if (selectedMotor == motor) - return; - - ThrustCurveMotorSet set = findMotorSet(motor); - if (set == null) { - throw new BugException("Could not find motor from database, motor=" + motor); - } - - boolean updateDelays = (selectedMotorSet != set); - - selectedMotor = motor; - selectedMotorSet = set; - updateData(); - if (updateDelays) { - setDelays(true); - } - } - - - private void updateData() { - - if (selectedMotorSet == null) { - // No motor selected - curveSelectionModel.removeAllElements(); - curveSelectionBox.setEnabled(false); - curveSelectionLabel.setEnabled(false); - totalImpulseLabel.setText(""); - totalImpulseLabel.setToolTipText(null); - classificationLabel.setText(""); - classificationLabel.setToolTipText(null); - avgThrustLabel.setText(""); - maxThrustLabel.setText(""); - burnTimeLabel.setText(""); - launchMassLabel.setText(""); - emptyMassLabel.setText(""); - dataPointsLabel.setText(""); - if (digestLabel != null) { - digestLabel.setText(""); - } - setComment(""); - chart.getXYPlot().setDataset(new XYSeriesCollection()); - return; - } - - - // Check which thrust curves to display - List motors = getFilteredCurves(); - final int index = motors.indexOf(selectedMotor); - - - // Update the thrust curve selection box - curveSelectionModel.removeAllElements(); - for (int i = 0; i < motors.size(); i++) { - curveSelectionModel.addElement(new MotorHolder(motors.get(i), i)); - } - curveSelectionBox.setSelectedIndex(index); - - if (motors.size() > 1) { - curveSelectionBox.setEnabled(true); - curveSelectionLabel.setEnabled(true); - } else { - curveSelectionBox.setEnabled(false); - curveSelectionLabel.setEnabled(false); - } - - - // Update thrust curve data - double impulse = selectedMotor.getTotalImpulseEstimate(); - MotorClass mc = MotorClass.getMotorClass(impulse); - totalImpulseLabel.setText(UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(impulse)); - classificationLabel.setText("(" + mc.getDescription(impulse) + ")"); - totalImpulseLabel.setToolTipText(mc.getClassDescription()); - classificationLabel.setToolTipText(mc.getClassDescription()); - - avgThrustLabel.setText(UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit( - selectedMotor.getAverageThrustEstimate())); - maxThrustLabel.setText(UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit( - selectedMotor.getMaxThrustEstimate())); - burnTimeLabel.setText(UnitGroup.UNITS_SHORT_TIME.getDefaultUnit().toStringUnit( - selectedMotor.getBurnTimeEstimate())); - launchMassLabel.setText(UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit( - selectedMotor.getLaunchCG().weight)); - emptyMassLabel.setText(UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit( - selectedMotor.getEmptyCG().weight)); - dataPointsLabel.setText("" + (selectedMotor.getTimePoints().length - 1)); - if (digestLabel != null) { - digestLabel.setText(selectedMotor.getDigest()); - } - - setComment(selectedMotor.getDescription()); - - - // Update the plot - XYPlot plot = chart.getXYPlot(); - - XYSeriesCollection dataset = new XYSeriesCollection(); - for (int i = 0; i < motors.size(); i++) { - ThrustCurveMotor m = motors.get(i); - - //// Thrust - XYSeries series = new XYSeries(trans.get("TCMotorSelPan.title.Thrust")); - double[] time = m.getTimePoints(); - double[] thrust = m.getThrustPoints(); - - for (int j = 0; j < time.length; j++) { - series.add(time[j], thrust[j]); - } - - dataset.addSeries(series); - - boolean selected = (i == index); - plot.getRenderer().setSeriesStroke(i, new BasicStroke(selected ? 3 : 1)); - plot.getRenderer().setSeriesPaint(i, getColor(i)); - } - - plot.setDataset(dataset); - } - - private List getFilteredCurves() { - List motors = selectedMotorSet.getMotors(); - if (hideSimilarBox.isSelected()) { - List filtered = new ArrayList(motors.size()); - for (int i = 0; i < motors.size(); i++) { - ThrustCurveMotor m = motors.get(i); - if (m.equals(selectedMotor)) { - filtered.add(m); - continue; - } - - double similarity = MotorCorrelation.similarity(selectedMotor, m); - log.debug("Motor similarity: " + similarity); - if (similarity < MOTOR_SIMILARITY_THRESHOLD) { - filtered.add(m); - } - } - motors = filtered; - } - - Collections.sort(motors, MOTOR_COMPARATOR); - - return motors; - } - - - private void setComment(String s) { - s = s.trim(); - if (s.length() == 0) { - //// No description available. - comment.setText(trans.get("TCMotorSelPan.noDescription")); - comment.setFont(noCommentFont); - comment.setForeground(NO_COMMENT_COLOR); - } else { - comment.setText(s); - comment.setFont(withCommentFont); - comment.setForeground(WITH_COMMENT_COLOR); - } - comment.setCaretPosition(0); - } - - private void scrollSelectionVisible() { - if (selectedMotorSet != null) { - int index = table.convertRowIndexToView(model.getIndex(selectedMotorSet)); - //System.out.println("index=" + index); - table.getSelectionModel().setSelectionInterval(index, index); - Rectangle rect = table.getCellRect(index, 0, true); - rect = new Rectangle(rect.x, rect.y - 100, rect.width, rect.height + 200); - table.scrollRectToVisible(rect); - } - } - - - public static Color getColor(int index) { - return (Color) CURVE_COLORS[index % CURVE_COLORS.length]; - } - - - /** - * Find the ThrustCurveMotorSet that contains a motor. - * - * @param motor the motor to look for. - * @return the ThrustCurveMotorSet, or null if not found. - */ - private ThrustCurveMotorSet findMotorSet(ThrustCurveMotor motor) { - for (ThrustCurveMotorSet set : database) { - if (set.getMotors().contains(motor)) { - return set; - } - } - - return null; - } - - - - /** - * Select the default motor from this ThrustCurveMotorSet. This uses primarily motors - * that the user has previously used, and secondarily a heuristic method of selecting which - * thrust curve seems to be better or more reliable. - * - * @param set the motor set - * @return the default motor in this set - */ - private ThrustCurveMotor selectMotor(ThrustCurveMotorSet set) { - if (set.getMotorCount() == 0) { - throw new BugException("Attempting to select motor from empty ThrustCurveMotorSet: " + set); - } - if (set.getMotorCount() == 1) { - return set.getMotors().get(0); - } - - - // Find which motor has been used the most recently - List list = set.getMotors(); - Preferences prefs = ((SwingPreferences) Application.getPreferences()).getNode(net.sf.openrocket.startup.Preferences.PREFERRED_THRUST_CURVE_MOTOR_NODE); - for (ThrustCurveMotor m : list) { - String digest = m.getDigest(); - if (prefs.getBoolean(digest, false)) { - return m; - } - } - - // No motor has been used - Collections.sort(list, MOTOR_COMPARATOR); - return list.get(0); - } - - - /** - * Set the values in the delay combo box. If reset is true - * then sets the selected value as the value closest to selectedDelay, otherwise - * leaves selection alone. - */ - private void setDelays(boolean reset) { - if (selectedMotor == null) { - - //// None - delayBox.setModel(new DefaultComboBoxModel(new String[] { trans.get("TCMotorSelPan.delayBox.None") })); - delayBox.setSelectedIndex(0); - - } else { - - List delays = selectedMotorSet.getDelays(); - String[] delayStrings = new String[delays.size()]; - double currentDelay = selectedDelay; // Store current setting locally - - for (int i = 0; i < delays.size(); i++) { - //// None - delayStrings[i] = ThrustCurveMotor.getDelayString(delays.get(i), trans.get("TCMotorSelPan.delayBox.None")); - } - delayBox.setModel(new DefaultComboBoxModel(delayStrings)); - - if (reset) { - - // Find and set the closest value - double closest = Double.NaN; - for (int i = 0; i < delays.size(); i++) { - // if-condition to always become true for NaN - if (!(Math.abs(delays.get(i) - currentDelay) > Math.abs(closest - currentDelay))) { - closest = delays.get(i); - } - } - if (!Double.isNaN(closest)) { - selectedDelay = closest; - //// None - delayBox.setSelectedItem(ThrustCurveMotor.getDelayString(closest, trans.get("TCMotorSelPan.delayBox.None"))); - } else { - delayBox.setSelectedItem("None"); - } - - } else { - - selectedDelay = currentDelay; - //// None - delayBox.setSelectedItem(ThrustCurveMotor.getDelayString(currentDelay, trans.get("TCMotorSelPan.delayBox.None"))); - - } - - } - } - - - - - ////////////////////// - - - private class CurveSelectionRenderer implements ListCellRenderer { - - private final ListCellRenderer renderer; - - public CurveSelectionRenderer(ListCellRenderer renderer) { - this.renderer = renderer; - } - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean isSelected, boolean cellHasFocus) { - - Component c = renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value instanceof MotorHolder) { - MotorHolder m = (MotorHolder) value; - c.setForeground(getColor(m.getIndex())); - } - - return c; - } - - } - - - //////// Row filters - - /** - * Abstract adapter class. - */ - private abstract class MotorRowFilter extends RowFilter { - @Override - public boolean include(RowFilter.Entry entry) { - int index = entry.getIdentifier(); - ThrustCurveMotorSet m = model.getMotorSet(index); - return filterByDiameter(m) && filterByString(m); - } - - public abstract boolean filterByDiameter(ThrustCurveMotorSet m); - - - public boolean filterByString(ThrustCurveMotorSet m) { - main: for (String s : searchTerms) { - for (ThrustCurveMotorColumns col : ThrustCurveMotorColumns.values()) { - String str = col.getValue(m).toString().toLowerCase(Locale.getDefault()); - if (str.indexOf(s) >= 0) - continue main; - } - return false; - } - return true; - } - } - - /** - * Show all motors. - */ - private class MotorRowFilterAll extends MotorRowFilter { - @Override - public boolean filterByDiameter(ThrustCurveMotorSet m) { - return true; - } - } - - /** - * Show motors smaller than the mount. - */ - private class MotorRowFilterSmaller extends MotorRowFilter { - @Override - public boolean filterByDiameter(ThrustCurveMotorSet m) { - return (m.getDiameter() <= diameter + 0.0004); - } - } - - /** - * Show motors that fit the mount. - */ - private class MotorRowFilterExact extends MotorRowFilter { - @Override - public boolean filterByDiameter(ThrustCurveMotorSet m) { - return ((m.getDiameter() <= diameter + 0.0004) && (m.getDiameter() >= diameter - 0.0015)); - } - } - - - /** - * Custom layered pane that sets the bounds of the components on every layout. - */ - public class CustomLayeredPane extends JLayeredPane { - @Override - public void doLayout() { - synchronized (getTreeLock()) { - int w = getWidth(); - int h = getHeight(); - chartPanel.setBounds(0, 0, w, h); - zoomIcon.setBounds(w - ZOOM_ICON_POSITION_NEGATIVE_X, ZOOM_ICON_POSITION_POSITIVE_Y, 50, 50); - } - } - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/FunctionEvaluationData.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/FunctionEvaluationData.java deleted file mode 100644 index 6162e965..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/FunctionEvaluationData.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.sf.openrocket.gui.dialogs.optimization; - -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.unit.Value; - -/** - * Value object for function evaluation information. - * - * @author Sampo Niskanen - */ -public class FunctionEvaluationData { - - private final Point point; - private final Value[] state; - private final Value domainReference; - private final Value parameterValue; - private final double goalValue; - - - public FunctionEvaluationData(Point point, Value[] state, Value domainReference, Value parameterValue, double goalValue) { - this.point = point; - this.state = state.clone(); - this.domainReference = domainReference; - this.parameterValue = parameterValue; - this.goalValue = goalValue; - } - - - /** - * Return the function evaluation point (in 0...1 range). - */ - public Point getPoint() { - return point; - } - - - /** - * Return the function evaluation state in SI units + units. - */ - public Value[] getState() { - return state; - } - - - /** - * Return the domain description. - */ - public Value getDomainReference() { - return domainReference; - } - - - /** - * Return the optimization parameter value (or NaN is outside of domain). - */ - public Value getParameterValue() { - return parameterValue; - } - - - /** - * Return the function goal value. - */ - public double getGoalValue() { - return goalValue; - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java deleted file mode 100644 index 7a0ecc5f..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java +++ /dev/null @@ -1,1595 +0,0 @@ -package net.sf.openrocket.gui.dialogs.optimization; - -import java.awt.Component; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; -import java.text.Collator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.JToggleButton; -import javax.swing.ListSelectionModel; -import javax.swing.Timer; -import javax.swing.border.TitledBorder; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableColumnModel; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.CsvOptionPanel; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.DoubleCellEditor; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.components.UnitCellEditor; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.scalefigure.RocketFigure; -import net.sf.openrocket.gui.scalefigure.ScaleScrollPane; -import net.sf.openrocket.gui.util.FileHelper; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.optimization.rocketoptimization.OptimizationGoal; -import net.sf.openrocket.optimization.rocketoptimization.SimulationDomain; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.optimization.rocketoptimization.domains.IdentitySimulationDomain; -import net.sf.openrocket.optimization.rocketoptimization.domains.StabilityDomain; -import net.sf.openrocket.optimization.rocketoptimization.goals.MaximizationGoal; -import net.sf.openrocket.optimization.rocketoptimization.goals.MinimizationGoal; -import net.sf.openrocket.optimization.rocketoptimization.goals.ValueSeekGoal; -import net.sf.openrocket.optimization.services.OptimizationServiceHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.CaliberUnit; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.Named; -import net.sf.openrocket.util.TextUtil; - -import com.itextpdf.text.Font; - - -/** - * General rocket optimization dialog. - * - * @author Sampo Niskanen - */ -public class GeneralOptimizationDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private static final Collator collator = Collator.getInstance(); - - - private static final String GOAL_MAXIMIZE = trans.get("goal.maximize"); - private static final String GOAL_MINIMIZE = trans.get("goal.minimize"); - private static final String GOAL_SEEK = trans.get("goal.seek"); - - private static final String START_TEXT = trans.get("btn.start"); - private static final String STOP_TEXT = trans.get("btn.stop"); - - - - private final List optimizationParameters = new ArrayList(); - private final Map> simulationModifiers = - new HashMap>(); - - - private final OpenRocketDocument baseDocument; - private OpenRocketDocument documentCopy; - - - private final JButton addButton; - private final JButton removeButton; - private final JButton removeAllButton; - - private final ParameterSelectionTableModel selectedModifierTableModel; - private final JTable selectedModifierTable; - private final DescriptionArea selectedModifierDescription; - private final SimulationModifierTree availableModifierTree; - - private final JComboBox simulationSelectionCombo; - private final JComboBox optimizationParameterCombo; - - private final JComboBox optimizationGoalCombo; - private final JSpinner optimizationGoalSpinner; - private final UnitSelector optimizationGoalUnitSelector; - private final DoubleModel optimizationSeekValue; - - private DoubleModel minimumStability; - private DoubleModel maximumStability; - private final JCheckBox minimumStabilitySelected; - private final JSpinner minimumStabilitySpinner; - private final UnitSelector minimumStabilityUnitSelector; - private final JCheckBox maximumStabilitySelected; - private final JSpinner maximumStabilitySpinner; - private final UnitSelector maximumStabilityUnitSelector; - - private final JLabel bestValueLabel; - private final JLabel stepCountLabel; - private final JLabel evaluationCountLabel; - private final JLabel stepSizeLabel; - - private final RocketFigure figure; - private final JToggleButton startButton; - private final JButton plotButton; - private final JButton saveButton; - - private final JButton applyButton; - private final JButton resetButton; - private final JButton closeButton; - - private final List selectedModifiers = new ArrayList(); - - /** List of components to disable while optimization is running */ - private final List disableComponents = new ArrayList(); - - /** Whether optimization is currently running or not */ - private boolean running = false; - /** The optimization worker that is running */ - private OptimizationWorker worker = null; - - - private double bestValue = Double.NaN; - private Unit bestValueUnit = Unit.NOUNIT2; - private int stepCount = 0; - private int evaluationCount = 0; - private double stepSize = 0; - - private final Map evaluationHistory = new LinkedHashMap(); - private final List optimizationPath = new LinkedList(); - - - private boolean updating = false; - - - /** - * Sole constructor. - * - * @param document the document - * @param parent the parent window - */ - public GeneralOptimizationDialog(OpenRocketDocument document, Window parent) { - super(parent, trans.get("title")); - - this.baseDocument = document; - this.documentCopy = document.copy(); - - loadOptimizationParameters(); - loadSimulationModifiers(); - - JPanel sub; - JLabel label; - JScrollPane scroll; - String tip; - - JPanel panel = new JPanel(new MigLayout("fill")); - - - ChangeListener clearHistoryChangeListener = new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - clearHistory(); - } - }; - ActionListener clearHistoryActionListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - clearHistory(); - } - }; - - - - //// Selected modifiers table - - selectedModifierTableModel = new ParameterSelectionTableModel(); - selectedModifierTable = new JTable(selectedModifierTableModel); - selectedModifierTable.setDefaultRenderer(Double.class, new DoubleCellRenderer()); - selectedModifierTable.setRowSelectionAllowed(true); - selectedModifierTable.setColumnSelectionAllowed(false); - selectedModifierTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - - // Make sure spinner editor fits into the cell height - selectedModifierTable.setRowHeight(new JSpinner().getPreferredSize().height - 4); - - selectedModifierTable.setDefaultEditor(Double.class, new DoubleCellEditor()); - selectedModifierTable.setDefaultEditor(Unit.class, new UnitCellEditor() { - @Override - protected UnitGroup getUnitGroup(Unit value, int row, int column) { - return selectedModifiers.get(row).getUnitGroup(); - } - }); - - disableComponents.add(selectedModifierTable); - - selectedModifierTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - updateComponents(); - } - }); - - // Set column widths - TableColumnModel columnModel = selectedModifierTable.getColumnModel(); - columnModel.getColumn(0).setPreferredWidth(150); - columnModel.getColumn(1).setPreferredWidth(40); - columnModel.getColumn(2).setPreferredWidth(40); - columnModel.getColumn(3).setPreferredWidth(40); - - scroll = new JScrollPane(selectedModifierTable); - - label = new StyledLabel(trans.get("lbl.paramsToOptimize"), Style.BOLD); - disableComponents.add(label); - panel.add(label, "split 3, flowy"); - panel.add(scroll, "wmin 300lp, height 200lp, grow"); - selectedModifierDescription = new DescriptionArea(2, -3); - disableComponents.add(selectedModifierDescription); - panel.add(selectedModifierDescription, "growx"); - - - - //// Add/remove buttons - sub = new JPanel(new MigLayout("fill")); - - addButton = new JButton(Chars.LEFT_ARROW + " " + trans.get("btn.add") + " "); - addButton.setToolTipText(trans.get("btn.add.ttip")); - addButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SimulationModifier mod = getSelectedAvailableModifier(); - if (mod != null) { - addModifier(mod); - clearHistory(); - } else { - log.error("Attempting to add simulation modifier when none is selected"); - } - } - }); - disableComponents.add(addButton); - sub.add(addButton, "wrap para, sg button"); - - removeButton = new JButton(" " + trans.get("btn.remove") + " " + Chars.RIGHT_ARROW); - removeButton.setToolTipText(trans.get("btn.remove.ttip")); - removeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SimulationModifier mod = getSelectedModifier(); - if (mod == null) { - log.error("Attempting to remove simulation modifier when none is selected"); - return; - } - removeModifier(mod); - clearHistory(); - } - }); - disableComponents.add(removeButton); - sub.add(removeButton, "wrap para*2, sg button"); - - removeAllButton = new JButton(trans.get("btn.removeAll")); - removeAllButton.setToolTipText(trans.get("btn.removeAll.ttip")); - removeAllButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Removing all selected modifiers"); - selectedModifiers.clear(); - selectedModifierTableModel.fireTableDataChanged(); - availableModifierTree.repaint(); - clearHistory(); - } - }); - disableComponents.add(removeAllButton); - sub.add(removeAllButton, "wrap para, sg button"); - - panel.add(sub); - - - - //// Available modifier tree - availableModifierTree = new SimulationModifierTree(documentCopy.getRocket(), simulationModifiers, selectedModifiers); - availableModifierTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(TreeSelectionEvent e) { - updateComponents(); - } - }); - - // Handle double-click - availableModifierTree.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.getClickCount() == 2) { - SimulationModifier mod = getSelectedAvailableModifier(); - if (mod != null) { - addModifier(mod); - clearHistory(); - } else { - log.user("Double-clicked non-available option"); - } - } - } - }); - - disableComponents.add(availableModifierTree); - scroll = new JScrollPane(availableModifierTree); - label = new StyledLabel(trans.get("lbl.availableParams"), Style.BOLD); - disableComponents.add(label); - panel.add(label, "split 2, flowy"); - panel.add(scroll, "width 300lp, height 200lp, grow, wrap para*2"); - - - - - //// Optimization options sub-panel - - sub = new JPanel(new MigLayout("fill")); - TitledBorder border = BorderFactory.createTitledBorder(trans.get("lbl.optimizationOpts")); - GUIUtil.changeFontStyle(border, Font.BOLD); - sub.setBorder(border); - disableComponents.add(sub); - - - //// Simulation to optimize - - label = new JLabel(trans.get("lbl.optimizeSim")); - tip = trans.get("lbl.optimizeSim.ttip"); - label.setToolTipText(tip); - disableComponents.add(label); - sub.add(label, ""); - - simulationSelectionCombo = new JComboBox(); - simulationSelectionCombo.setToolTipText(tip); - populateSimulations(); - simulationSelectionCombo.addActionListener(clearHistoryActionListener); - disableComponents.add(simulationSelectionCombo); - sub.add(simulationSelectionCombo, "growx, wrap unrel"); - - - - //// Value to optimize - label = new JLabel(trans.get("lbl.optimizeValue")); - tip = trans.get("lbl.optimizeValue.ttip"); - label.setToolTipText(tip); - disableComponents.add(label); - sub.add(label, ""); - - optimizationParameterCombo = new JComboBox(); - optimizationParameterCombo.setToolTipText(tip); - populateParameters(); - optimizationParameterCombo.addActionListener(clearHistoryActionListener); - disableComponents.add(optimizationParameterCombo); - sub.add(optimizationParameterCombo, "growx, wrap unrel"); - - - - //// Optimization goal - label = new JLabel(trans.get("lbl.optimizeGoal")); - tip = trans.get("lbl.optimizeGoal"); - label.setToolTipText(tip); - disableComponents.add(label); - sub.add(label, ""); - - optimizationGoalCombo = new JComboBox(new String[] { GOAL_MAXIMIZE, GOAL_MINIMIZE, GOAL_SEEK }); - optimizationGoalCombo.setToolTipText(tip); - optimizationGoalCombo.setEditable(false); - optimizationGoalCombo.addActionListener(clearHistoryActionListener); - disableComponents.add(optimizationGoalCombo); - sub.add(optimizationGoalCombo, "growx"); - - - //// Optimization custom value - optimizationSeekValue = new DoubleModel(0, UnitGroup.UNITS_NONE); - optimizationSeekValue.addChangeListener(clearHistoryChangeListener); - - optimizationGoalSpinner = new JSpinner(optimizationSeekValue.getSpinnerModel()); - tip = trans.get("lbl.optimizeGoalValue.ttip"); - optimizationGoalSpinner.setToolTipText(tip); - optimizationGoalSpinner.setEditor(new SpinnerEditor(optimizationGoalSpinner)); - disableComponents.add(optimizationGoalSpinner); - sub.add(optimizationGoalSpinner, "width 30lp"); - - optimizationGoalUnitSelector = new UnitSelector(optimizationSeekValue); - optimizationGoalUnitSelector.setToolTipText(tip); - disableComponents.add(optimizationGoalUnitSelector); - sub.add(optimizationGoalUnitSelector, "width 20lp, wrap unrel"); - - - panel.add(sub, "grow"); - - - - //// Required stability sub-panel - - sub = new JPanel(new MigLayout("fill")); - border = BorderFactory.createTitledBorder(trans.get("lbl.requireStability")); - GUIUtil.changeFontStyle(border, Font.BOLD); - sub.setBorder(border); - disableComponents.add(sub); - - - - double ref = CaliberUnit.calculateCaliber(baseDocument.getRocket()); - minimumStability = new DoubleModel(ref, UnitGroup.stabilityUnits(ref)); - maximumStability = new DoubleModel(5 * ref, UnitGroup.stabilityUnits(ref)); - minimumStability.addChangeListener(clearHistoryChangeListener); - maximumStability.addChangeListener(clearHistoryChangeListener); - - - //// Minimum stability - tip = trans.get("lbl.requireMinStability.ttip"); - minimumStabilitySelected = new JCheckBox(trans.get("lbl.requireMinStability")); - minimumStabilitySelected.setSelected(true); - minimumStabilitySelected.setToolTipText(tip); - minimumStabilitySelected.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateComponents(); - } - }); - disableComponents.add(minimumStabilitySelected); - sub.add(minimumStabilitySelected); - - minimumStabilitySpinner = new JSpinner(minimumStability.getSpinnerModel()); - minimumStabilitySpinner.setToolTipText(tip); - minimumStabilitySpinner.setEditor(new SpinnerEditor(minimumStabilitySpinner)); - disableComponents.add(minimumStabilitySpinner); - sub.add(minimumStabilitySpinner, "growx"); - - minimumStabilityUnitSelector = new UnitSelector(minimumStability); - minimumStabilityUnitSelector.setToolTipText(tip); - disableComponents.add(minimumStabilityUnitSelector); - sub.add(minimumStabilityUnitSelector, "growx, wrap unrel"); - - - //// Maximum stability - tip = trans.get("lbl.requireMaxStability.ttip"); - maximumStabilitySelected = new JCheckBox(trans.get("lbl.requireMaxStability")); - maximumStabilitySelected.setToolTipText(tip); - maximumStabilitySelected.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateComponents(); - } - }); - disableComponents.add(maximumStabilitySelected); - sub.add(maximumStabilitySelected); - - maximumStabilitySpinner = new JSpinner(maximumStability.getSpinnerModel()); - maximumStabilitySpinner.setToolTipText(tip); - maximumStabilitySpinner.setEditor(new SpinnerEditor(maximumStabilitySpinner)); - disableComponents.add(maximumStabilitySpinner); - sub.add(maximumStabilitySpinner, "growx"); - - maximumStabilityUnitSelector = new UnitSelector(maximumStability); - maximumStabilityUnitSelector.setToolTipText(tip); - disableComponents.add(maximumStabilityUnitSelector); - sub.add(maximumStabilityUnitSelector, "growx, wrap para"); - - - - // DescriptionArea desc = new DescriptionArea("Stability requirements are verified during each time step of the simulation.", - // 2, -2, false); - // desc.setViewportBorder(null); - // disableComponents.add(desc); - // sub.add(desc, "span, growx"); - - - panel.add(sub, "span 2, grow, wrap para*2"); - - - - - //// Rocket figure - figure = new RocketFigure(getSelectedSimulation().getConfiguration()); - figure.setBorderPixels(1, 1); - ScaleScrollPane figureScrollPane = new ScaleScrollPane(figure); - figureScrollPane.setFitting(true); - panel.add(figureScrollPane, "span, split, height 200lp, grow"); - - - sub = new JPanel(new MigLayout("fill")); - - - label = new JLabel(trans.get("status.bestValue")); - tip = trans.get("status.bestValue.ttip"); - label.setToolTipText(tip); - sub.add(label, "gapright unrel"); - - bestValueLabel = new JLabel(); - bestValueLabel.setToolTipText(tip); - sub.add(bestValueLabel, "wmin 60lp, wrap rel"); - - - label = new JLabel(trans.get("status.stepCount")); - tip = trans.get("status.stepCount.ttip"); - label.setToolTipText(tip); - sub.add(label, "gapright unrel"); - - stepCountLabel = new JLabel(); - stepCountLabel.setToolTipText(tip); - sub.add(stepCountLabel, "wrap rel"); - - - label = new JLabel(trans.get("status.evalCount")); - tip = trans.get("status.evalCount.ttip"); - label.setToolTipText(tip); - sub.add(label, "gapright unrel"); - - evaluationCountLabel = new JLabel(); - evaluationCountLabel.setToolTipText(tip); - sub.add(evaluationCountLabel, "wrap rel"); - - - label = new JLabel(trans.get("status.stepSize")); - tip = trans.get("status.stepSize.ttip"); - label.setToolTipText(tip); - sub.add(label, "gapright unrel"); - - stepSizeLabel = new JLabel(); - stepSizeLabel.setToolTipText(tip); - sub.add(stepSizeLabel, "wrap para"); - - - //// Start/Stop button - - startButton = new JToggleButton(START_TEXT); - startButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (updating) { - log.debug("Updating, ignoring event"); - return; - } - if (running) { - log.user("Stopping optimization"); - stopOptimization(); - } else { - log.user("Starting optimization"); - startOptimization(); - } - } - }); - sub.add(startButton, "span, growx, wrap para*2"); - - - plotButton = new JButton(trans.get("btn.plotPath")); - plotButton.setToolTipText(trans.get("btn.plotPath.ttip")); - plotButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Plotting optimization path, dimensionality=" + selectedModifiers.size()); - OptimizationPlotDialog dialog = new OptimizationPlotDialog( - Collections.unmodifiableList(optimizationPath), - Collections.unmodifiableMap(evaluationHistory), - Collections.unmodifiableList(selectedModifiers), - getSelectedParameter(), - UnitGroup.stabilityUnits(getSelectedSimulation().getRocket()), - GeneralOptimizationDialog.this); - dialog.setVisible(true); - } - }); - disableComponents.add(plotButton); - sub.add(plotButton, "span, growx, wrap"); - - - saveButton = new JButton(trans.get("btn.save")); - saveButton.setToolTipText(trans.get("btn.save.ttip")); - saveButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("User selected save path"); - savePath(); - } - }); - disableComponents.add(saveButton); - sub.add(saveButton, "span, growx"); - - - - panel.add(sub, "wrap para*2"); - - - - - //// Bottom buttons - - applyButton = new JButton(trans.get("btn.apply")); - applyButton.setToolTipText(trans.get("btn.apply.ttip")); - applyButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Applying optimization changes"); - applyDesign(); - } - }); - disableComponents.add(applyButton); - panel.add(applyButton, "span, split, gapright para, right"); - - resetButton = new JButton(trans.get("btn.reset")); - resetButton.setToolTipText(trans.get("btn.reset.ttip")); - resetButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Resetting optimization design"); - resetDesign(); - } - }); - disableComponents.add(resetButton); - panel.add(resetButton, "gapright para, right"); - - closeButton = new JButton(trans.get("btn.close")); - closeButton.setToolTipText(trans.get("btn.close.ttip")); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Closing optimization dialog"); - stopOptimization(); - GeneralOptimizationDialog.this.dispose(); - } - }); - panel.add(closeButton, "right"); - - - this.add(panel); - clearHistory(); - updateComponents(); - GUIUtil.setDisposableDialogOptions(this, null); - } - - - private void startOptimization() { - if (running) { - log.info("Optimization already running"); - return; - } - - - if (selectedModifiers.isEmpty()) { - JOptionPane.showMessageDialog(this, trans.get("error.selectParams.text"), - trans.get("error.selectParams.title"), JOptionPane.ERROR_MESSAGE); - updating = true; - startButton.setSelected(false); - startButton.setText(START_TEXT); - updating = false; - return; - } - - - running = true; - - // Update the button status - updating = true; - startButton.setSelected(true); - startButton.setText(STOP_TEXT); - updating = false; - - - // Create a copy of the simulation (we're going to modify the original in the current thread) - Simulation simulation = getSelectedSimulation(); - Rocket rocketCopy = simulation.getRocket().copyWithOriginalID(); - simulation = simulation.duplicateSimulation(rocketCopy); - - OptimizableParameter parameter = getSelectedParameter(); - - OptimizationGoal goal; - String value = (String) optimizationGoalCombo.getSelectedItem(); - if (GOAL_MAXIMIZE.equals(value)) { - goal = new MaximizationGoal(); - } else if (GOAL_MINIMIZE.equals(value)) { - goal = new MinimizationGoal(); - } else if (GOAL_SEEK.equals(value)) { - goal = new ValueSeekGoal(optimizationSeekValue.getValue()); - } else { - throw new BugException("optimizationGoalCombo had invalid value: " + value); - } - - SimulationDomain domain; - if (minimumStabilitySelected.isSelected() || maximumStabilitySelected.isSelected()) { - double min, max; - boolean minAbsolute, maxAbsolute; - - /* - * Make minAbsolute/maxAbsolute consistent with each other to produce reasonable - * result in plot tool tips. Yes, this is a bit ugly. - */ - - // Min stability - Unit unit = minimumStability.getCurrentUnit(); - if (unit instanceof CaliberUnit) { - min = unit.toUnit(minimumStability.getValue()); - minAbsolute = false; - } else { - min = minimumStability.getValue(); - minAbsolute = true; - } - - // Max stability - unit = maximumStability.getCurrentUnit(); - if (unit instanceof CaliberUnit) { - max = unit.toUnit(maximumStability.getValue()); - maxAbsolute = false; - } else { - max = maximumStability.getValue(); - maxAbsolute = true; - } - - - if (!minimumStabilitySelected.isSelected()) { - min = Double.NaN; - minAbsolute = maxAbsolute; - } - if (!maximumStabilitySelected.isSelected()) { - max = Double.NaN; - maxAbsolute = minAbsolute; - } - - domain = new StabilityDomain(min, minAbsolute, max, maxAbsolute); - } else { - domain = new IdentitySimulationDomain(); - } - - SimulationModifier[] modifiers = selectedModifiers.toArray(new SimulationModifier[0]); - - // Create and start the background worker - worker = new OptimizationWorker(simulation, parameter, goal, domain, modifiers) { - @Override - protected void done(OptimizationException exception) { - log.info("Optimization finished, exception=" + exception, exception); - - if (exception != null) { - JOptionPane.showMessageDialog(GeneralOptimizationDialog.this, - new Object[] { - trans.get("error.optimizationFailure.text"), - exception.getLocalizedMessage() - }, trans.get("error.optimizationFailure.title"), JOptionPane.ERROR_MESSAGE); - } - - worker = null; - stopOptimization(); - - // Disable the start/stop button for a short while after ending the simulation - // to prevent accidentally starting a new optimization when trying to stop it - startButton.setEnabled(false); - Timer timer = new Timer(750, new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - startButton.setEnabled(true); - } - }); - timer.setRepeats(false); - timer.start(); - updateComponents(); - } - - @Override - protected void functionEvaluated(List data) { - for (FunctionEvaluationData d : data) { - evaluationHistory.put(d.getPoint(), d); - evaluationCount++; - } - updateCounters(); - } - - @Override - protected void optimizationStepTaken(List data) { - - // Add starting point to the path - if (optimizationPath.isEmpty()) { - optimizationPath.add(data.get(0).getOldPoint()); - } - - // Add other points to the path - for (OptimizationStepData d : data) { - optimizationPath.add(d.getNewPoint()); - } - - // Get function value from the latest point - OptimizationStepData latest = data.get(data.size() - 1); - Point newPoint = latest.getNewPoint(); - - FunctionEvaluationData pointValue = evaluationHistory.get(newPoint); - if (pointValue != null && pointValue.getParameterValue() != null) { - bestValue = pointValue.getParameterValue().getValue(); - } else { - bestValue = Double.NaN; - } - - // Update the simulation - Simulation sim = getSelectedSimulation(); - for (int i = 0; i < newPoint.dim(); i++) { - try { - selectedModifiers.get(i).modify(sim, newPoint.get(i)); - } catch (OptimizationException e) { - throw new BugException("Simulation modifier failed to modify the base simulation " + - "modifier=" + selectedModifiers.get(i), e); - } - } - figure.updateFigure(); - - // Update other counter data - stepCount += data.size(); - stepSize = latest.getStepSize(); - updateCounters(); - } - }; - worker.start(); - - - clearHistory(); - - updateComponents(); - } - - private void stopOptimization() { - if (!running) { - log.info("Optimization not running"); - return; - } - - if (worker != null && worker.isAlive()) { - log.info("Worker still running, interrupting it and setting to null"); - worker.interrupt(); - worker = null; - return; - } - - running = false; - - // Update the button status - updating = true; - startButton.setSelected(false); - startButton.setText(START_TEXT); - updating = false; - - - updateComponents(); - } - - - - - /** - * Reset the current optimization history and values. This does not reset the design. - */ - private void clearHistory() { - evaluationHistory.clear(); - optimizationPath.clear(); - bestValue = Double.NaN; - bestValueUnit = getSelectedParameter().getUnitGroup().getDefaultUnit(); - stepCount = 0; - evaluationCount = 0; - stepSize = 0.5; - updateCounters(); - updateComponents(); - } - - - private void applyDesign() { - // TODO: MEDIUM: Apply also potential changes to simulations - Rocket src = getSelectedSimulation().getRocket().copyWithOriginalID(); - Rocket dest = baseDocument.getRocket(); - try { - baseDocument.startUndo(trans.get("undoText")); - dest.freeze(); - - // Remove all children - while (dest.getChildCount() > 0) { - dest.removeChild(0); - } - - // Move all children to the destination rocket - while (src.getChildCount() > 0) { - RocketComponent c = src.getChild(0); - src.removeChild(0); - dest.addChild(c); - } - - } finally { - dest.thaw(); - baseDocument.stopUndo(); - } - } - - - private void resetDesign() { - clearHistory(); - - documentCopy = baseDocument.copy(); - - loadOptimizationParameters(); - loadSimulationModifiers(); - - // Replace selected modifiers with corresponding new modifiers - List newSelected = new ArrayList(); - for (SimulationModifier original : selectedModifiers) { - List newModifiers = simulationModifiers.get(original.getRelatedObject()); - if (newModifiers != null) { - int index = newModifiers.indexOf(original); - if (index >= 0) { - SimulationModifier updated = newModifiers.get(index); - updated.setMinValue(original.getMinValue()); - updated.setMaxValue(original.getMaxValue()); - newSelected.add(updated); - } - } - } - selectedModifiers.clear(); - selectedModifiers.addAll(newSelected); - selectedModifierTableModel.fireTableDataChanged(); - - // Update the available modifier tree - availableModifierTree.populateTree(documentCopy.getRocket(), simulationModifiers); - availableModifierTree.expandComponents(); - - - // Update selectable simulations - populateSimulations(); - - // Update selectable parameters - populateParameters(); - - } - - - private void populateSimulations() { - String current = null; - Object selection = simulationSelectionCombo.getSelectedItem(); - if (selection != null) { - current = selection.toString(); - } - - - List> simulations = new ArrayList>(); - Rocket rocket = documentCopy.getRocket(); - - for (Simulation s : documentCopy.getSimulations()) { - String id = s.getConfiguration().getMotorConfigurationID(); - String name = createSimulationName(s.getName(), rocket.getMotorConfigurationNameOrDescription(id)); - simulations.add(new Named(s, name)); - } - - for (String id : rocket.getMotorConfigurationIDs()) { - if (id == null) { - continue; - } - Simulation sim = new Simulation(rocket); - sim.getConfiguration().setMotorConfigurationID(id); - String name = createSimulationName(trans.get("basicSimulationName"), rocket.getMotorConfigurationNameOrDescription(id)); - simulations.add(new Named(sim, name)); - } - - - Simulation sim = new Simulation(rocket); - sim.getConfiguration().setMotorConfigurationID(null); - String name = createSimulationName(trans.get("noSimulationName"), rocket.getMotorConfigurationNameOrDescription(null)); - simulations.add(new Named(sim, name)); - - - simulationSelectionCombo.setModel(new DefaultComboBoxModel(simulations.toArray())); - simulationSelectionCombo.setSelectedIndex(0); - if (current != null) { - for (int i = 0; i < simulations.size(); i++) { - if (simulations.get(i).toString().equals(current)) { - simulationSelectionCombo.setSelectedIndex(i); - break; - } - } - } - } - - - private void populateParameters() { - String current = null; - Object selection = optimizationParameterCombo.getSelectedItem(); - if (selection != null) { - current = selection.toString(); - } else { - // Default to apogee altitude event if it is not the first one in the list - current = trans.get("MaximumAltitudeParameter.name"); - } - - List> parameters = new ArrayList>(); - for (OptimizableParameter p : optimizationParameters) { - parameters.add(new Named(p, p.getName())); - } - - optimizationParameterCombo.setModel(new DefaultComboBoxModel(parameters.toArray())); - - for (int i = 0; i < parameters.size(); i++) { - if (parameters.get(i).toString().equals(current)) { - optimizationParameterCombo.setSelectedIndex(i); - break; - } - } - } - - private void updateCounters() { - bestValueLabel.setText(bestValueUnit.toStringUnit(bestValue)); - stepCountLabel.setText("" + stepCount); - evaluationCountLabel.setText("" + evaluationCount); - stepSizeLabel.setText(UnitGroup.UNITS_RELATIVE.toStringUnit(stepSize)); - } - - - private void loadOptimizationParameters() { - optimizationParameters.clear(); - optimizationParameters.addAll(OptimizationServiceHelper.getOptimizableParameters(documentCopy)); - - if (optimizationParameters.isEmpty()) { - throw new BugException("No rocket optimization parameters found, distribution built wrong."); - } - - Collections.sort(optimizationParameters, new Comparator() { - @Override - public int compare(OptimizableParameter o1, OptimizableParameter o2) { - return o1.getName().compareTo(o2.getName()); - } - }); - } - - - private void loadSimulationModifiers() { - simulationModifiers.clear(); - - for (SimulationModifier m : OptimizationServiceHelper.getSimulationModifiers(documentCopy)) { - Object key = m.getRelatedObject(); - List list = simulationModifiers.get(key); - if (list == null) { - list = new ArrayList(); - simulationModifiers.put(key, list); - } - list.add(m); - } - - for (Object key : simulationModifiers.keySet()) { - List list = simulationModifiers.get(key); - Collections.sort(list, new Comparator() { - @Override - public int compare(SimulationModifier o1, SimulationModifier o2) { - return o1.getName().compareTo(o2.getName()); - } - }); - } - - } - - - - private void addModifier(SimulationModifier mod) { - if (!selectedModifiers.contains(mod)) { - log.user(1, "Adding simulation modifier " + mod); - selectedModifiers.add(mod); - Collections.sort(selectedModifiers, new SimulationModifierComparator()); - selectedModifierTableModel.fireTableDataChanged(); - availableModifierTree.repaint(); - } else { - log.user(1, "Attempting to add an already existing simulation modifier " + mod); - } - } - - - private void removeModifier(SimulationModifier mod) { - log.user(1, "Removing simulation modifier " + mod); - selectedModifiers.remove(mod); - selectedModifierTableModel.fireTableDataChanged(); - availableModifierTree.repaint(); - } - - - - /** - * Update the enabled status of all components in the dialog. - */ - private void updateComponents() { - boolean state; - - if (updating) { - log.debug("Ignoring updateComponents"); - return; - } - - log.debug("Running updateComponents()"); - - updating = true; - - - // First enable all components if optimization not running - if (!running) { - log.debug("Initially enabling all components"); - for (JComponent c : disableComponents) { - c.setEnabled(true); - } - } - - - // "Add" button - SimulationModifier mod = getSelectedAvailableModifier(); - state = (mod != null && !selectedModifiers.contains(mod)); - log.debug("addButton enabled: " + state); - addButton.setEnabled(state); - - // "Remove" button - state = (selectedModifierTable.getSelectedRow() >= 0); - log.debug("removeButton enabled: " + state); - removeButton.setEnabled(state); - - // "Remove all" button - state = (!selectedModifiers.isEmpty()); - log.debug("removeAllButton enabled: " + state); - removeAllButton.setEnabled(state); - - - // Optimization goal - String selected = (String) optimizationGoalCombo.getSelectedItem(); - state = GOAL_SEEK.equals(selected); - log.debug("optimizationGoalSpinner & UnitSelector enabled: " + state); - optimizationGoalSpinner.setVisible(state); - optimizationGoalUnitSelector.setVisible(state); - - - // Minimum/maximum stability options - state = minimumStabilitySelected.isSelected(); - log.debug("minimumStabilitySpinner & UnitSelector enabled: " + state); - minimumStabilitySpinner.setEnabled(state); - minimumStabilityUnitSelector.setEnabled(state); - - state = maximumStabilitySelected.isSelected(); - log.debug("maximumStabilitySpimmer & UnitSelector enabled: " + state); - maximumStabilitySpinner.setEnabled(state); - maximumStabilityUnitSelector.setEnabled(state); - - - // Plot button (enabled if path exists and dimensionality is 1 or 2) - state = (!optimizationPath.isEmpty() && (selectedModifiers.size() == 1 || selectedModifiers.size() == 2)); - log.debug("plotButton enabled: " + state + " optimizationPath.isEmpty=" + optimizationPath.isEmpty() + - " selectedModifiers.size=" + selectedModifiers.size()); - plotButton.setEnabled(state); - - // Save button (enabled if path exists) - state = (!evaluationHistory.isEmpty()); - log.debug("saveButton enabled: " + state); - saveButton.setEnabled(state); - - - // Last disable all components if optimization is running - if (running) { - log.debug("Disabling all components because optimization is running"); - for (JComponent c : disableComponents) { - c.setEnabled(false); - } - } - - - // Update description text - mod = getSelectedModifier(); - if (mod != null) { - selectedModifierDescription.setText(mod.getDescription()); - } else { - selectedModifierDescription.setText(""); - } - - - // Update the figure - figure.setConfiguration(getSelectedSimulation().getConfiguration()); - - updating = false; - } - - - private void savePath() { - - if (evaluationHistory.isEmpty()) { - throw new BugException("evaluation history is empty"); - } - - CsvOptionPanel csvOptions = new CsvOptionPanel(GeneralOptimizationDialog.class, - trans.get("export.header"), trans.get("export.header.ttip")); - - - JFileChooser chooser = new JFileChooser(); - chooser.setFileFilter(FileHelper.CSV_FILE_FILTER); - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - chooser.setAccessory(csvOptions); - - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) - return; - - File file = chooser.getSelectedFile(); - if (file == null) - return; - - file = FileHelper.ensureExtension(file, "csv"); - if (!FileHelper.confirmWrite(file, this)) { - return; - } - - String fieldSeparator = csvOptions.getFieldSeparator(); - String commentCharacter = csvOptions.getCommentCharacter(); - boolean includeHeader = csvOptions.getSelectionOption(0); - csvOptions.storePreferences(); - - log.info("Saving optimization path to " + file + ", fieldSeparator=" + fieldSeparator + - ", commentCharacter=" + commentCharacter + ", includeHeader=" + includeHeader); - - try { - Writer writer = new BufferedWriter(new FileWriter(file)); - - // Write header - if (includeHeader) { - FunctionEvaluationData data = evaluationHistory.values().iterator().next(); - - writer.write(commentCharacter); - for (SimulationModifier mod : selectedModifiers) { - writer.write(mod.getRelatedObject().toString() + ": " + mod.getName() + " / " + - mod.getUnitGroup().getDefaultUnit().getUnit()); - writer.write(fieldSeparator); - } - if (minimumStabilitySelected.isSelected() || maximumStabilitySelected.isSelected()) { - writer.write(trans.get("export.stability") + " / " + data.getDomainReference().getUnit().getUnit()); - writer.write(fieldSeparator); - } - writer.write(getSelectedParameter().getName() + " / " + - getSelectedParameter().getUnitGroup().getDefaultUnit().getUnit()); - - writer.write("\n"); - } - - - for (FunctionEvaluationData data : evaluationHistory.values()) { - Value[] state = data.getState(); - - for (int i = 0; i < state.length; i++) { - writer.write(TextUtil.doubleToString(state[i].getUnitValue())); - writer.write(fieldSeparator); - } - - if (minimumStabilitySelected.isSelected() || maximumStabilitySelected.isSelected()) { - writer.write(TextUtil.doubleToString(data.getDomainReference().getUnitValue())); - writer.write(fieldSeparator); - } - - if (data.getParameterValue() != null) { - writer.write(TextUtil.doubleToString(data.getParameterValue().getUnitValue())); - } else { - writer.write("N/A"); - } - writer.write("\n"); - } - - writer.close(); - log.info("File successfully saved"); - - } catch (IOException e) { - FileHelper.errorWriting(e, this); - } - - } - - /** - * Return the currently selected available simulation modifier from the modifier tree, - * or null if none selected. - */ - private SimulationModifier getSelectedAvailableModifier() { - TreePath treepath = availableModifierTree.getSelectionPath(); - if (treepath != null) { - Object o = ((DefaultMutableTreeNode) treepath.getLastPathComponent()).getUserObject(); - if (o instanceof SimulationModifier) { - return (SimulationModifier) o; - } - } - return null; - } - - /** - * Return the currently selected simulation. - * @return the selected simulation. - */ - @SuppressWarnings("unchecked") - private Simulation getSelectedSimulation() { - /* This is to debug a NPE where the returned selected item is null. */ - Object item = simulationSelectionCombo.getSelectedItem(); - if (item == null) { - String s = "Selected simulation is null:"; - s = s + " item count=" + simulationSelectionCombo.getItemCount(); - for (int i = 0; i < simulationSelectionCombo.getItemCount(); i++) { - s = s + " [" + i + "]=" + simulationSelectionCombo.getItemAt(i); - } - throw new BugException(s); - } - return ((Named) item).get(); - } - - - /** - * Return the currently selected simulation modifier from the table, - * or null if none selected. - * @return the selected modifier or null. - */ - private SimulationModifier getSelectedModifier() { - int row = selectedModifierTable.getSelectedRow(); - if (row < 0) { - return null; - } - row = selectedModifierTable.convertRowIndexToModel(row); - return selectedModifiers.get(row); - } - - - /** - * Return the currently selected optimization parameter. - * @return the selected optimization parameter. - */ - @SuppressWarnings("unchecked") - private OptimizableParameter getSelectedParameter() { - return ((Named) optimizationParameterCombo.getSelectedItem()).get(); - } - - - private Unit getModifierUnit(int index) { - return selectedModifiers.get(index).getUnitGroup().getDefaultUnit(); - } - - private String createSimulationName(String simulationName, String motorConfiguration) { - String name; - boolean hasParenthesis = motorConfiguration.matches("^[\\[\\(].*[\\]\\)]$"); - name = simulationName + " "; - if (!hasParenthesis) { - name += "("; - } - name += motorConfiguration; - if (!hasParenthesis) { - name += ")"; - } - return name; - } - - /** - * The table model for the parameter selection. - * - * [Body tube: Length] [min] [max] [unit] - */ - private class ParameterSelectionTableModel extends AbstractTableModel { - - private static final int PARAMETER = 0; - private static final int CURRENT = 1; - private static final int MIN = 2; - private static final int MAX = 3; - private static final int COUNT = 4; - - @Override - public int getColumnCount() { - return COUNT; - } - - @Override - public int getRowCount() { - return selectedModifiers.size(); - } - - @Override - public String getColumnName(int column) { - switch (column) { - case PARAMETER: - return trans.get("table.col.parameter"); - case CURRENT: - return trans.get("table.col.current"); - case MIN: - return trans.get("table.col.min"); - case MAX: - return trans.get("table.col.max"); - default: - throw new IndexOutOfBoundsException("column=" + column); - } - - } - - @Override - public Class getColumnClass(int column) { - switch (column) { - case PARAMETER: - return String.class; - case CURRENT: - return Double.class; - case MIN: - return Double.class; - case MAX: - return Double.class; - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - @Override - public Object getValueAt(int row, int column) { - - SimulationModifier modifier = selectedModifiers.get(row); - - switch (column) { - case PARAMETER: - return modifier.getRelatedObject().toString() + ": " + modifier.getName(); - case CURRENT: - try { - return getModifierUnit(row).toUnit(modifier.getCurrentSIValue(getSelectedSimulation())); - } catch (OptimizationException e) { - throw new BugException("Could not read current SI value from modifier " + modifier, e); - } - case MIN: - return getModifierUnit(row).toUnit(modifier.getMinValue()); - case MAX: - return getModifierUnit(row).toUnit(modifier.getMaxValue()); - default: - throw new IndexOutOfBoundsException("column=" + column); - } - - } - - @Override - public void setValueAt(Object value, int row, int column) { - - if (row >= selectedModifiers.size()) { - throw new BugException("setValueAt with invalid row: value=" + value + " row=" + row + " column=" + column + - " selectedModifiers.size=" + selectedModifiers.size() + " selectedModifiers=" + selectedModifiers + - " selectedModifierTable.getRowCount=" + selectedModifierTable.getRowCount()); - } - - switch (column) { - case PARAMETER: - break; - - case MIN: - double min = (Double) value; - min = getModifierUnit(row).fromUnit(min); - selectedModifiers.get(row).setMinValue(min); - break; - - case CURRENT: - break; - - case MAX: - double max = (Double) value; - max = getModifierUnit(row).fromUnit(max); - selectedModifiers.get(row).setMaxValue(max); - break; - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - this.fireTableRowsUpdated(row, row); - - } - - @Override - public boolean isCellEditable(int row, int column) { - switch (column) { - case PARAMETER: - return false; - case CURRENT: - return false; - case MIN: - return true; - case MAX: - return true; - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - } - - - private class DoubleCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, - boolean hasFocus, int row, int column) { - - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - - double val = (Double) value; - Unit unit = getModifierUnit(row); - - val = unit.fromUnit(val); - this.setText(unit.toStringUnit(val)); - - return this; - } - } - - - private static class SimulationModifierComparator implements Comparator { - - @Override - public int compare(SimulationModifier mod1, SimulationModifier mod2) { - Object rel1 = mod1.getRelatedObject(); - Object rel2 = mod2.getRelatedObject(); - - /* - * Primarily order by related object: - * - * - RocketComponents first - * - Two RocketComponents are ordered based on their position in the rocket - */ - if (!rel1.equals(rel2)) { - - if (rel1 instanceof RocketComponent) { - if (rel2 instanceof RocketComponent) { - - RocketComponent root = ((RocketComponent) rel1).getRoot(); - for (RocketComponent c : root) { - if (c.equals(rel1)) { - return -1; - } - if (c.equals(rel2)) { - return 1; - } - } - - throw new BugException("Error sorting modifiers, mod1=" + mod1 + " rel1=" + rel1 + - " mod2=" + mod2 + " rel2=" + rel2); - - } else { - return -1; - } - } else { - if (rel2 instanceof RocketComponent) { - return 1; - } - } - - } - - // Secondarily sort by name - return collator.compare(mod1.getName(), mod2.getName()); - } - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationPlotDialog.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationPlotDialog.java deleted file mode 100644 index 1df3214e..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationPlotDialog.java +++ /dev/null @@ -1,435 +0,0 @@ -package net.sf.openrocket.gui.dialogs.optimization; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.LinearInterpolator; -import net.sf.openrocket.util.MathUtil; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.annotations.XYBoxAnnotation; -import org.jfree.chart.annotations.XYLineAnnotation; -import org.jfree.chart.annotations.XYPointerAnnotation; -import org.jfree.chart.axis.AxisLocation; -import org.jfree.chart.axis.NumberAxis; -import org.jfree.chart.labels.CustomXYToolTipGenerator; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.renderer.PaintScale; -import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; -import org.jfree.chart.renderer.xy.XYShapeRenderer; -import org.jfree.chart.title.PaintScaleLegend; -import org.jfree.data.xy.DefaultXYZDataset; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; -import org.jfree.ui.RectangleEdge; -import org.jfree.ui.TextAnchor; - -/** - * A class that plots the path of an optimization. - * - * @author Sampo Niskanen - */ -public class OptimizationPlotDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - private static final LinearInterpolator RED = new LinearInterpolator( - new double[] { 0.0, 1.0 }, new double[] { 0.0, 1.0 } - ); - private static final LinearInterpolator GREEN = new LinearInterpolator( - new double[] { 0.0, 1.0 }, new double[] { 0.0, 0.0 } - ); - private static final LinearInterpolator BLUE = new LinearInterpolator( - new double[] { 0.0, 1.0 }, new double[] { 1.0, 0.0 } - ); - - private static final Color OUT_OF_DOMAIN_COLOR = Color.BLACK; - - private static final Color PATH_COLOR = new Color(220, 0, 0); - - - public OptimizationPlotDialog(List path, Map evaluations, - List modifiers, OptimizableParameter parameter, UnitGroup stabilityUnit, Window parent) { - super(parent, trans.get("title"), ModalityType.APPLICATION_MODAL); - - - JPanel panel = new JPanel(new MigLayout("fill")); - - ChartPanel chart; - if (modifiers.size() == 1) { - chart = create1DPlot(path, evaluations, modifiers, parameter, stabilityUnit); - } else if (modifiers.size() == 2) { - chart = create2DPlot(path, evaluations, modifiers, parameter, stabilityUnit); - } else { - throw new IllegalArgumentException("Invalid dimensionality, dim=" + modifiers.size()); - } - chart.setBorder(BorderFactory.createLineBorder(Color.BLACK)); - panel.add(chart, "span, grow, wrap para"); - - - JLabel label = new StyledLabel(trans.get("lbl.zoomInstructions"), -2); - panel.add(label, ""); - - - JButton close = new JButton(trans.get("button.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - OptimizationPlotDialog.this.setVisible(false); - } - }); - panel.add(close, "right"); - - - this.add(panel); - - GUIUtil.setDisposableDialogOptions(this, close); - GUIUtil.rememberWindowSize(this); - } - - - - /** - * Create a 1D plot of the optimization path. - */ - private ChartPanel create1DPlot(List path, Map evaluations, - List modifiers, OptimizableParameter parameter, UnitGroup stabilityUnit) { - - SimulationModifier modX = modifiers.get(0); - Unit xUnit = modX.getUnitGroup().getDefaultUnit(); - Unit yUnit = parameter.getUnitGroup().getDefaultUnit(); - - // Create the optimization path (with autosort) - XYSeries series = new XYSeries(trans.get("plot1d.series"), true, true); - List tooltips = new ArrayList(); - for (Point p : evaluations.keySet()) { - FunctionEvaluationData data = evaluations.get(p); - if (data != null) { - if (data.getParameterValue() != null) { - Value[] state = data.getState(); - series.add(xUnit.toUnit(state[0].getValue()), yUnit.toUnit(data.getParameterValue().getValue())); - tooltips.add(getTooltip(data, parameter)); - } - } else { - log.error("Could not find evaluation data for point " + p); - } - } - - - String xLabel = modX.getRelatedObject().toString() + ": " + modX.getName() + " / " + xUnit.getUnit(); - String yLabel = parameter.getName() + " / " + yUnit.getUnit(); - - JFreeChart chart = ChartFactory.createXYLineChart( - trans.get("plot1d.title"), - xLabel, - yLabel, - null, - PlotOrientation.VERTICAL, - false, // Legend - true, // Tooltips - false); // Urls - - - // Set the scale of the plot to the limits - double x1 = xUnit.toUnit(modX.getMinValue()); - double x2 = xUnit.toUnit(modX.getMaxValue()); - - if (x1 < x2 - 0.0001) { - log.debug("Setting 1D plot domain axis x1=" + x1 + " x2=" + x2); - chart.getXYPlot().getDomainAxis().setRange(x1, x2); - } else { - log.warn("1D plot domain singular x1=" + x1 + " x2=" + x2 + ", not setting"); - } - - // Add lines to show optimization limits - XYLineAnnotation line = new XYLineAnnotation(x1, -1e19, x1, 1e19); - chart.getXYPlot().addAnnotation(line); - line = new XYLineAnnotation(x2, -1e19, x2, 1e19); - chart.getXYPlot().addAnnotation(line); - - // Mark the optimum point - Point optimum = path.get(path.size() - 1); - FunctionEvaluationData data = evaluations.get(optimum); - if (data != null) { - if (data.getParameterValue() != null) { - Value[] state = data.getState(); - double x = xUnit.toUnit(state[0].getValue()); - double y = yUnit.toUnit(data.getParameterValue().getValue()); - - XYPointerAnnotation text = new XYPointerAnnotation(trans.get("plot.label.optimum"), - x, y, Math.PI / 2); - text.setTextAnchor(TextAnchor.TOP_LEFT); - chart.getXYPlot().addAnnotation(text); - } - } else { - log.error("Could not find evaluation data for point " + optimum); - } - - - XYLineAndShapeRenderer lineRenderer = new XYLineAndShapeRenderer(true, true); - lineRenderer.setBaseShapesVisible(true); - lineRenderer.setSeriesShapesFilled(0, false); - //lineRenderer.setSeriesShape(0, shapeRenderer.getBaseShape()); - lineRenderer.setSeriesOutlinePaint(0, PATH_COLOR); - lineRenderer.setSeriesPaint(0, PATH_COLOR); - lineRenderer.setUseOutlinePaint(true); - CustomXYToolTipGenerator tooltipGenerator = new CustomXYToolTipGenerator(); - tooltipGenerator.addToolTipSeries(tooltips); - lineRenderer.setBaseToolTipGenerator(tooltipGenerator); - - XYPlot plot = chart.getXYPlot(); - - plot.setDataset(0, new XYSeriesCollection(series)); - plot.setRenderer(lineRenderer); - - - - return new ChartPanel(chart); - } - - /** - * Create a 2D plot of the optimization path. - */ - private ChartPanel create2DPlot(List path, Map evaluations, - List modifiers, OptimizableParameter parameter, UnitGroup stabilityUnit) { - - Unit parameterUnit = parameter.getUnitGroup().getDefaultUnit(); - - SimulationModifier modX = modifiers.get(0); - SimulationModifier modY = modifiers.get(1); - - Unit xUnit = modX.getUnitGroup().getDefaultUnit(); - Unit yUnit = modY.getUnitGroup().getDefaultUnit(); - - // Create the optimization path dataset - XYSeries pathSeries = new XYSeries(trans.get("plot2d.path"), false, true); - List pathTooltips = new ArrayList(); - for (Point p : path) { - FunctionEvaluationData data = evaluations.get(p); - if (data != null) { - Value[] state = data.getState(); - pathSeries.add(xUnit.toUnit(state[0].getValue()), yUnit.toUnit(state[1].getValue())); - pathTooltips.add(getTooltip(data, parameter)); - } else { - log.error("Could not find evaluation data for point " + p); - } - } - - - // Create evaluations dataset - double min = Double.POSITIVE_INFINITY; - double max = Double.NEGATIVE_INFINITY; - double[][] evals = new double[3][evaluations.size()]; - List evalTooltips = new ArrayList(); - - Iterator iterator = evaluations.values().iterator(); - for (int i = 0; i < evaluations.size(); i++) { - FunctionEvaluationData data = iterator.next(); - Value param = data.getParameterValue(); - double value; - if (param != null) { - value = parameterUnit.toUnit(data.getParameterValue().getValue()); - } else { - value = Double.NaN; - } - - Value[] state = data.getState(); - evals[0][i] = xUnit.toUnit(state[0].getValue()); - evals[1][i] = yUnit.toUnit(state[1].getValue()); - evals[2][i] = value; - - if (value < min) { - min = value; - } - if (value > max) { - max = value; - } - - evalTooltips.add(getTooltip(data, parameter)); - } - DefaultXYZDataset evalDataset = new DefaultXYZDataset(); - evalDataset.addSeries(trans.get("plot2d.evals"), evals); - - - - String xLabel = modX.getRelatedObject().toString() + ": " + modX.getName() + " / " + xUnit.getUnit(); - String yLabel = modY.getRelatedObject().toString() + ": " + modY.getName() + " / " + yUnit.getUnit(); - - JFreeChart chart = ChartFactory.createXYLineChart( - trans.get("plot2d.title"), - xLabel, - yLabel, - null, - //evalDataset, - PlotOrientation.VERTICAL, - true, // Legend - true, // Tooltips - false); // Urls - - - // Set the scale of the plot to the limits - double x1 = xUnit.toUnit(modX.getMinValue()); - double x2 = xUnit.toUnit(modX.getMaxValue()); - double y1 = yUnit.toUnit(modY.getMinValue()); - double y2 = yUnit.toUnit(modY.getMaxValue()); - - if (x1 < x2 - 0.0001) { - log.debug("Setting 2D plot domain axis to x1=" + x1 + " x2=" + x2); - chart.getXYPlot().getDomainAxis().setRange(x1, x2); - } else { - log.warn("2D plot has singular domain axis: x1=" + x1 + " x2=" + x2); - } - - if (y1 < y2 - 0.0001) { - log.debug("Setting 2D plot range axis to y1=" + y1 + " y2=" + y2); - chart.getXYPlot().getRangeAxis().setRange(y1, y2); - } else { - log.warn("2D plot has singular range axis: y1=" + y1 + " y2=" + y2); - } - - XYBoxAnnotation box = new XYBoxAnnotation(x1, y1, x2, y2); - chart.getXYPlot().addAnnotation(box); - - int n = pathSeries.getItemCount(); - XYPointerAnnotation text = new XYPointerAnnotation(trans.get("plot.label.optimum"), - (Double) pathSeries.getX(n - 1), (Double) pathSeries.getY(n - 1), -Math.PI / 5); - text.setTextAnchor(TextAnchor.BASELINE_LEFT); - chart.getXYPlot().addAnnotation(text); - - - if (min < max - 0.0001) { - log.debug("Setting gradient scale range to min=" + min + " max=" + max); - } else { - log.warn("2D plot has singular gradient scale, resetting to (0,1): min=" + min + " max=" + max); - min = 0; - max = 1; - } - - PaintScale paintScale = new GradientScale(min, max); - - XYShapeRenderer shapeRenderer = new XYShapeRenderer(); - shapeRenderer.setPaintScale(paintScale); - shapeRenderer.setUseFillPaint(true); - CustomXYToolTipGenerator tooltipGenerator = new CustomXYToolTipGenerator(); - tooltipGenerator.addToolTipSeries(evalTooltips); - shapeRenderer.setBaseToolTipGenerator(tooltipGenerator); - - - shapeRenderer.getLegendItem(0, 0); - - - XYLineAndShapeRenderer lineRenderer = new XYLineAndShapeRenderer(true, true); - lineRenderer.setBaseShapesVisible(true); - lineRenderer.setSeriesShapesFilled(0, false); - lineRenderer.setSeriesShape(0, shapeRenderer.getBaseShape()); - lineRenderer.setSeriesOutlinePaint(0, PATH_COLOR); - lineRenderer.setSeriesPaint(0, PATH_COLOR); - lineRenderer.setUseOutlinePaint(true); - tooltipGenerator = new CustomXYToolTipGenerator(); - tooltipGenerator.addToolTipSeries(pathTooltips); - lineRenderer.setBaseToolTipGenerator(tooltipGenerator); - - - XYPlot plot = chart.getXYPlot(); - - plot.setDataset(0, new XYSeriesCollection(pathSeries)); - plot.setRenderer(lineRenderer); - - plot.setDataset(1, evalDataset); - plot.setRenderer(1, shapeRenderer); - - - // Add value scale - NumberAxis numberAxis = new NumberAxis(parameter.getName() + " / " + parameterUnit.getUnit()); - PaintScaleLegend scale = new PaintScaleLegend(paintScale, numberAxis); - scale.setPosition(RectangleEdge.RIGHT); - scale.setMargin(4.0D, 4.0D, 40.0D, 4.0D); - scale.setAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); - chart.addSubtitle(scale); - - - return new ChartPanel(chart); - } - - - - private String getTooltip(FunctionEvaluationData data, OptimizableParameter parameter) { - String ttip = ""; - if (data.getParameterValue() != null) { - ttip += parameter.getName() + ": " + - parameter.getUnitGroup().getDefaultUnit().toStringUnit(data.getParameterValue().getValue()); - ttip += "
"; - } - if (data.getDomainReference() != null) { - ttip += trans.get("plot.ttip.stability") + " " + data.getDomainReference(); - } - return ttip; - } - - private class GradientScale implements PaintScale { - - private final double min; - private final double max; - - public GradientScale(double min, double max) { - this.min = min; - this.max = max; - } - - @Override - public Paint getPaint(double value) { - if (Double.isNaN(value)) { - return OUT_OF_DOMAIN_COLOR; - } - - value = MathUtil.map(value, min, max, 0.0, 1.0); - value = MathUtil.clamp(value, 0.0, 1.0); - - float r = (float) RED.getValue(value); - float g = (float) GREEN.getValue(value); - float b = (float) BLUE.getValue(value); - - return new Color(r, g, b); - } - - @Override - public double getLowerBound() { - return min; - } - - @Override - public double getUpperBound() { - return max; - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationStepData.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationStepData.java deleted file mode 100644 index ec1ece5a..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationStepData.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.sf.openrocket.gui.dialogs.optimization; - -import net.sf.openrocket.optimization.general.Point; - -/** - * Value object for optimization step data. - * - * @author Sampo Niskanen - */ -public class OptimizationStepData { - - private final Point oldPoint; - private final double oldValue; - private final Point newPoint; - private final double newValue; - private final double stepSize; - - - public OptimizationStepData(Point oldPoint, double oldValue, Point newPoint, double newValue, double stepSize) { - this.oldPoint = oldPoint; - this.oldValue = oldValue; - this.newPoint = newPoint; - this.newValue = newValue; - this.stepSize = stepSize; - } - - - public Point getOldPoint() { - return oldPoint; - } - - - public double getOldValue() { - return oldValue; - } - - - public Point getNewPoint() { - return newPoint; - } - - - public double getNewValue() { - return newValue; - } - - - public double getStepSize() { - return stepSize; - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationWorker.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationWorker.java deleted file mode 100644 index eda1f9ae..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/OptimizationWorker.java +++ /dev/null @@ -1,234 +0,0 @@ -package net.sf.openrocket.gui.dialogs.optimization; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.LinkedBlockingQueue; - -import javax.swing.SwingUtilities; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.FunctionOptimizer; -import net.sf.openrocket.optimization.general.OptimizationController; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.ParallelExecutorCache; -import net.sf.openrocket.optimization.general.ParallelFunctionCache; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.optimization.general.multidim.MultidirectionalSearchOptimizer; -import net.sf.openrocket.optimization.general.onedim.GoldenSectionSearchOptimizer; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.optimization.rocketoptimization.OptimizationGoal; -import net.sf.openrocket.optimization.rocketoptimization.RocketOptimizationFunction; -import net.sf.openrocket.optimization.rocketoptimization.RocketOptimizationListener; -import net.sf.openrocket.optimization.rocketoptimization.SimulationDomain; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.BugException; - -/** - * A background worker that runs the optimization in the background. It supports providing - * evaluation and step counter information via listeners that are executed on the EDT. - * - * @author Sampo Niskanen - */ -public abstract class OptimizationWorker extends Thread implements OptimizationController, RocketOptimizationListener { - - /* - * Note: This is implemented as a separate Thread object instead of a SwingWorker because - * the SwingWorker cannot be interrupted in any way except by canceling the task, which - * makes it impossible to wait for its exiting (SwingWorker.get() throws a CancellationException - * if cancel() has been called). - * - * SwingWorker also seems to miss some chunks that have been provided to process() when the - * thread ends. - * - * Nothing of this is documented, of course... - */ - - private static final LogHelper log = Application.getLogger(); - - /** Notify listeners every this many milliseconds */ - private static final long PURGE_TIMEOUT = 500; - /** End optimization when step size is below this threshold */ - private static final double STEP_SIZE_LIMIT = 0.005; - - private final FunctionOptimizer optimizer; - private final RocketOptimizationFunction function; - - private final Simulation simulation; - private final SimulationModifier[] modifiers; - - private final ParallelFunctionCache cache; - - - private final LinkedBlockingQueue evaluationQueue = - new LinkedBlockingQueue(); - private final LinkedBlockingQueue stepQueue = - new LinkedBlockingQueue(); - private volatile long lastPurge = 0; - - private OptimizationException optimizationException = null; - - - /** - * Sole constructor - * @param simulation the simulation - * @param parameter the optimization parameter - * @param goal the optimization goal - * @param domain the optimization domain - * @param modifiers the simulation modifiers - */ - public OptimizationWorker(Simulation simulation, OptimizableParameter parameter, - OptimizationGoal goal, SimulationDomain domain, SimulationModifier... modifiers) { - - this.simulation = simulation; - this.modifiers = modifiers.clone(); - - function = new RocketOptimizationFunction(simulation, parameter, goal, domain, modifiers); - function.addRocketOptimizationListener(this); - - cache = new ParallelExecutorCache(1); - cache.setFunction(function); - - if (modifiers.length == 1) { - optimizer = new GoldenSectionSearchOptimizer(cache); - } else { - optimizer = new MultidirectionalSearchOptimizer(cache); - } - } - - - @Override - public void run() { - try { - - double[] current = new double[modifiers.length]; - for (int i = 0; i < modifiers.length; i++) { - current[i] = modifiers[i].getCurrentScaledValue(simulation); - } - Point initial = new Point(current); - - optimizer.optimize(initial, this); - - } catch (OptimizationException e) { - this.optimizationException = e; - } finally { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - lastPurge = System.currentTimeMillis() + 24L * 3600L * 1000L; - processQueue(); - done(optimizationException); - } - }); - } - } - - /** - * This method is called after the optimization has ended, either normally, when interrupted - * or by throwing an exception. This method is called on the EDT, like the done() method of SwingWorker. - *

- * All data chunks to the listeners will be guaranteed to have been processed before calling done(). - * - * @param exception a possible optimization exception that occurred, or null for normal exit. - */ - protected abstract void done(OptimizationException exception); - - - /** - * This method is called for each function evaluation that has taken place. - * This method is called on the EDT. - * - * @param data the data accumulated since the last call - */ - protected abstract void functionEvaluated(List data); - - /** - * This method is called after each step taken by the optimization algorithm. - * This method is called on the EDT. - * - * @param data the data accumulated since the last call - */ - protected abstract void optimizationStepTaken(List data); - - - /** - * Publishes data to the listeners. The queue is purged every PURGE_TIMEOUT milliseconds. - * - * @param data the data to publish to the listeners - */ - private synchronized void publish(FunctionEvaluationData evaluation, OptimizationStepData step) { - - if (evaluation != null) { - evaluationQueue.add(evaluation); - } - if (step != null) { - stepQueue.add(step); - } - - // Add a method to the EDT to process the queue data - long now = System.currentTimeMillis(); - if (lastPurge + PURGE_TIMEOUT <= now) { - lastPurge = now; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - processQueue(); - } - }); - } - - } - - - /** - * Process the queue and call the listeners. This method must always be called from the EDT. - */ - private void processQueue() { - - if (!SwingUtilities.isEventDispatchThread()) { - throw new BugException("processQueue called from non-EDT"); - } - - - List evaluations = new ArrayList(); - evaluationQueue.drainTo(evaluations); - if (!evaluations.isEmpty()) { - functionEvaluated(evaluations); - } - - - List steps = new ArrayList(); - stepQueue.drainTo(steps); - if (!steps.isEmpty()) { - optimizationStepTaken(steps); - } - } - - - - - /* - * NOTE: The stepTaken and evaluated methods may be called from other - * threads than the EDT or the SwingWorker thread! - */ - - @Override - public boolean stepTaken(Point oldPoint, double oldValue, Point newPoint, double newValue, double stepSize) { - publish(null, new OptimizationStepData(oldPoint, oldValue, newPoint, newValue, stepSize)); - - if (stepSize < STEP_SIZE_LIMIT) { - log.info("stepSize=" + stepSize + " is below limit, ending optimization"); - return false; - } else { - return true; - } - } - - @Override - public void evaluated(Point point, Value[] state, Value domainReference, Value parameterValue, double goalValue) { - publish(new FunctionEvaluationData(point, state, domainReference, parameterValue, goalValue), null); - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java deleted file mode 100644 index 663c79b8..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java +++ /dev/null @@ -1,196 +0,0 @@ -package net.sf.openrocket.gui.dialogs.optimization; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; - -import javax.swing.JTree; -import javax.swing.ToolTipManager; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; - -import net.sf.openrocket.gui.components.BasicTree; -import net.sf.openrocket.gui.main.ComponentIcons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.TextUtil; - -/** - * A tree that displays the simulation modifiers in a tree structure. - *

- * All nodes in the model are instances of DefaultMutableTreeNode. The user objects - * within are either of type RocketComponent, String or SimulationModifier. - * - * @author Sampo Niskanen - */ -public class SimulationModifierTree extends BasicTree { - - private final List selectedModifiers; - private static final Translator trans = Application.getTranslator(); - - /** - * Sole constructor. - * - * @param rocket the rocket. - * @param simulationModifiers the simulation modifiers, ordered and mapped by components - * @param selectedModifiers a list of the currently selected modifiers (may be modified). - */ - public SimulationModifierTree(Rocket rocket, Map> simulationModifiers, - List selectedModifiers) { - this.selectedModifiers = selectedModifiers; - - populateTree(rocket, simulationModifiers); - this.setCellRenderer(new ComponentModifierTreeRenderer()); - - // Enable tooltips for this component - ToolTipManager.sharedInstance().registerComponent(this); - - expandComponents(); - } - - - /** - * Populate the simulation modifier tree from the provided information. This can be used to update - * the tree. - */ - public void populateTree(Rocket rocket, Map> simulationModifiers) { - - DefaultMutableTreeNode baseNode = new DefaultMutableTreeNode(rocket); - populateTree(baseNode, rocket, simulationModifiers); - - this.setModel(new DefaultTreeModel(baseNode)); - } - - - private static void populateTree(DefaultMutableTreeNode node, RocketComponent component, - Map> simulationModifiers) { - - // Add modifiers (if any) - List modifiers = simulationModifiers.get(component); - if (modifiers != null) { - DefaultMutableTreeNode modifierNode; - - if (component.getChildCount() > 0) { - modifierNode = new DefaultMutableTreeNode(trans.get("SimulationModifierTree.OptimizationParameters")); - node.add(modifierNode); - } else { - modifierNode = node; - } - - for (SimulationModifier m : modifiers) { - modifierNode.add(new DefaultMutableTreeNode(m)); - } - } - - // Add child components - for (RocketComponent c : component.getChildren()) { - DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(c); - node.add(newNode); - populateTree(newNode, c, simulationModifiers); - } - - } - - - /** - * Expand the rocket components, but not the modifiers. - */ - @SuppressWarnings("rawtypes") - public void expandComponents() { - DefaultMutableTreeNode baseNode = (DefaultMutableTreeNode) this.getModel().getRoot(); - - Enumeration enumeration = baseNode.breadthFirstEnumeration(); - - while (enumeration.hasMoreElements()) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement(); - Object object = node.getUserObject(); - if (object instanceof RocketComponent) { - this.makeVisible(new TreePath(node.getPath())); - } - } - } - - - - - public class ComponentModifierTreeRenderer extends DefaultTreeCellRenderer { - private Font componentFont; - private Font stringFont; - private Font modifierFont; - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus2) { - - super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus2); - - if (componentFont == null) { - makeFonts(); - } - - - // Customize based on line type - - Object object = ((DefaultMutableTreeNode) value).getUserObject(); - - // Set icon (for rocket components, null for others) - setIcon(ComponentIcons.getSmallIcon(object.getClass())); - - - // Set text color/style - if (object instanceof RocketComponent) { - setForeground(Color.GRAY); - setFont(componentFont); - - // Set tooltip - RocketComponent c = (RocketComponent) object; - String comment = c.getComment().trim(); - if (comment.length() > 0) { - comment = TextUtil.htmlEncode(comment); - comment = "" + comment.replace("\n", "
"); - this.setToolTipText(comment); - } else { - this.setToolTipText(null); - } - } else if (object instanceof String) { - setForeground(Color.GRAY); - setFont(stringFont); - } else if (object instanceof SimulationModifier) { - - if (selectedModifiers.contains(object)) { - setForeground(Color.GRAY); - } else { - setForeground(Color.BLACK); - } - setFont(modifierFont); - setText(((SimulationModifier) object).getName()); - setToolTipText(((SimulationModifier) object).getDescription()); - } - - return this; - } - - private void makeFonts() { - Font font = getFont(); - componentFont = font.deriveFont(Font.ITALIC); - stringFont = font; - modifierFont = font.deriveFont(Font.BOLD); - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/preferences/MaterialEditPanel.java b/core/src/net/sf/openrocket/gui/dialogs/preferences/MaterialEditPanel.java deleted file mode 100644 index a106ba32..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preferences/MaterialEditPanel.java +++ /dev/null @@ -1,392 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preferences; - -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Iterator; - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.DefaultTableCellRenderer; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.database.Database; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.gui.adaptors.Column; -import net.sf.openrocket.gui.adaptors.ColumnTableModel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.dialogs.CustomMaterialDialog; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; - -public class MaterialEditPanel extends JPanel { - - private final JTable table; - - private final JButton addButton; - private final JButton editButton; - private final JButton deleteButton; - private final JButton revertButton; - private static final Translator trans = Application.getTranslator(); - - - public MaterialEditPanel() { - super(new MigLayout("fill")); - - - // TODO: LOW: Create sorter that keeps material types always in order - final ColumnTableModel model = new ColumnTableModel( - //// Material - new Column(trans.get("matedtpan.col.Material")) { - @Override - public Object getValueAt(int row) { - return getMaterial(row).getName(); - } - }, - //// Type - new Column(trans.get("matedtpan.col.Type")) { - @Override - public Object getValueAt(int row) { - return getMaterial(row).getType().toString(); - } - - @Override - public int getDefaultWidth() { - return 15; - } - }, - //// Density - new Column(trans.get("matedtpan.col.Density")) { - @Override - public Object getValueAt(int row) { - Material m = getMaterial(row); - double d = m.getDensity(); - switch (m.getType()) { - case LINE: - return UnitGroup.UNITS_DENSITY_LINE.toValue(d); - - case SURFACE: - return UnitGroup.UNITS_DENSITY_SURFACE.toValue(d); - - case BULK: - return UnitGroup.UNITS_DENSITY_BULK.toValue(d); - - default: - throw new IllegalStateException("Material type " + m.getType()); - } - } - - @Override - public int getDefaultWidth() { - return 15; - } - - @Override - public Class getColumnClass() { - return Value.class; - } - } - ) { - @Override - public int getRowCount() { - return Databases.BULK_MATERIAL.size() + Databases.SURFACE_MATERIAL.size() + - Databases.LINE_MATERIAL.size(); - } - }; - - table = new JTable(model); - model.setColumnWidths(table.getColumnModel()); - table.setAutoCreateRowSorter(true); - table.setDefaultRenderer(Object.class, new MaterialCellRenderer()); - this.add(new JScrollPane(table), "w 200px, h 100px, grow 100"); - - - //// New button - addButton = new JButton(trans.get("matedtpan.but.new")); - //// Add a new material - addButton.setToolTipText(trans.get("matedtpan.col.but.ttip.New")); - addButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - CustomMaterialDialog dialog = new CustomMaterialDialog( - SwingUtilities.getWindowAncestor(MaterialEditPanel.this), - //// Add a custom material - null, false, trans.get("matedtpan.title.Addcustmaterial")); - dialog.setVisible(true); - if (dialog.getOkClicked()) { - Material mat = dialog.getMaterial(); - getDatabase(mat).add(mat); - model.fireTableDataChanged(); - setButtonStates(); - } - } - }); - this.add(addButton, "gap rel rel para para, w 70lp, split 5, flowy, growx 1, top"); - - //// Edit button - editButton = new JButton(trans.get("matedtpan.but.edit")); - //// Edit an existing material - editButton.setToolTipText(trans.get("matedtpan.but.ttip.edit")); - editButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int sel = table.getSelectedRow(); - if (sel < 0) - return; - sel = table.convertRowIndexToModel(sel); - Material m = getMaterial(sel); - - CustomMaterialDialog dialog; - if (m.isUserDefined()) { - dialog = new CustomMaterialDialog( - SwingUtilities.getWindowAncestor(MaterialEditPanel.this), - //// Edit material - m, false, trans.get("matedtpan.title.Editmaterial")); - } else { - dialog = new CustomMaterialDialog( - SwingUtilities.getWindowAncestor(MaterialEditPanel.this), - //// Add a custom material - m, false, trans.get("matedtpan.title.Addcustmaterial"), - //// The built-in materials cannot be modified. - trans.get("matedtpan.title2.Editmaterial")); - } - - dialog.setVisible(true); - - if (dialog.getOkClicked()) { - if (m.isUserDefined()) { - getDatabase(m).remove(m); - } - Material mat = dialog.getMaterial(); - getDatabase(mat).add(mat); - model.fireTableDataChanged(); - setButtonStates(); - } - } - }); - this.add(editButton, "gap rel rel para para, growx 1, top"); - - //// Delete button - deleteButton = new JButton(trans.get("matedtpan.but.delete")); - //// Delete a user-defined material - deleteButton.setToolTipText(trans.get("matedtpan.but.ttip.delete")); - deleteButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int sel = table.getSelectedRow(); - if (sel < 0) - return; - sel = table.convertRowIndexToModel(sel); - Material m = getMaterial(sel); - if (!m.isUserDefined()) - return; - getDatabase(m).remove(m); - model.fireTableDataChanged(); - setButtonStates(); - } - }); - this.add(deleteButton, "gap rel rel para para, growx 1, top"); - - - this.add(new JPanel(), "grow 1"); - - //// Revert all button - revertButton = new JButton(trans.get("matedtpan.but.revertall")); - //// Delete all user-defined materials - revertButton.setToolTipText(trans.get("matedtpan.but.ttip.revertall")); - revertButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int sel = JOptionPane.showConfirmDialog(MaterialEditPanel.this, - //// Delete all user-defined materials? - trans.get("matedtpan.title.Deletealluser-defined"), - //// Revert all? - trans.get("matedtpan.title.Revertall"), - JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); - if (sel == JOptionPane.YES_OPTION) { - Iterator iterator; - - iterator = Databases.LINE_MATERIAL.iterator(); - while (iterator.hasNext()) { - if (iterator.next().isUserDefined()) - iterator.remove(); - } - - iterator = Databases.SURFACE_MATERIAL.iterator(); - while (iterator.hasNext()) { - if (iterator.next().isUserDefined()) - iterator.remove(); - } - - iterator = Databases.BULK_MATERIAL.iterator(); - while (iterator.hasNext()) { - if (iterator.next().isUserDefined()) - iterator.remove(); - } - model.fireTableDataChanged(); - setButtonStates(); - } - } - }); - this.add(revertButton, "gap rel rel para para, growx 1, bottom, wrap unrel"); - - setButtonStates(); - table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - setButtonStates(); - } - }); - table.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - editButton.doClick(); - } - } - }); - - //// Editing materials will not affect existing - //// rocket designs. - this.add(new StyledLabel(trans.get("matedtpan.lbl.edtmaterials"), -2, Style.ITALIC), "span"); - - - } - - - private Database getDatabase(Material m) { - switch (m.getType()) { - case BULK: - return Databases.BULK_MATERIAL; - - case SURFACE: - return Databases.SURFACE_MATERIAL; - - case LINE: - return Databases.LINE_MATERIAL; - - default: - throw new IllegalArgumentException("Material type invalid, m=" + m); - } - } - - - private void setButtonStates() { - int sel = table.getSelectedRow(); - - // Add button always enabled - addButton.setEnabled(true); - - // Edit button enabled if a material is selected - editButton.setEnabled(sel >= 0); - - // Delete button enabled if a user-defined material is selected - if (sel >= 0) { - int modelRow = table.convertRowIndexToModel(sel); - deleteButton.setEnabled(getMaterial(modelRow).isUserDefined()); - } else { - deleteButton.setEnabled(false); - } - - // Revert button enabled if any user-defined material exists - boolean found = false; - - for (Material m : Databases.BULK_MATERIAL) { - if (m.isUserDefined()) { - found = true; - break; - } - } - if (!found) { - for (Material m : Databases.SURFACE_MATERIAL) { - if (m.isUserDefined()) { - found = true; - break; - } - } - } - if (!found) { - for (Material m : Databases.LINE_MATERIAL) { - if (m.isUserDefined()) { - found = true; - break; - } - } - } - revertButton.setEnabled(found); - - } - - private Material getMaterial(int origRow) { - int row = origRow; - int n; - - n = Databases.BULK_MATERIAL.size(); - if (row < n) { - return Databases.BULK_MATERIAL.get(row); - } - row -= n; - - n = Databases.SURFACE_MATERIAL.size(); - if (row < n) { - return Databases.SURFACE_MATERIAL.get(row); - } - row -= n; - - n = Databases.LINE_MATERIAL.size(); - if (row < n) { - return Databases.LINE_MATERIAL.get(row); - } - throw new IndexOutOfBoundsException("row=" + origRow + " while material count" + - " bulk:" + Databases.BULK_MATERIAL.size() + - " surface:" + Databases.SURFACE_MATERIAL.size() + - " line:" + Databases.LINE_MATERIAL.size()); - } - - - private class MaterialCellRenderer extends DefaultTableCellRenderer { - - /* (non-Javadoc) - * @see javax.swing.table.DefaultTableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int) - */ - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - Component c = super.getTableCellRendererComponent(table, value, isSelected, - hasFocus, row, column); - if (c instanceof JLabel) { - JLabel label = (JLabel) c; - Material m = getMaterial(row); - - if (isSelected) { - if (m.isUserDefined()) - label.setForeground(table.getSelectionForeground()); - else - label.setForeground(Color.GRAY); - } else { - if (m.isUserDefined()) - label.setForeground(table.getForeground()); - else - label.setForeground(Color.GRAY); - } - } - return c; - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java b/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java deleted file mode 100644 index a3d963ee..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java +++ /dev/null @@ -1,698 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preferences; - -import java.awt.Dialog; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import javax.swing.AbstractListModel; -import javax.swing.ComboBoxModel; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.Timer; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.communication.UpdateInfo; -import net.sf.openrocket.communication.UpdateInfoRetriever; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.dialogs.UpdateInfoDialog; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.gui.util.SimpleFileFilter; -import net.sf.openrocket.l10n.L10N; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.Named; -import net.sf.openrocket.util.Utils; - - -public class PreferencesDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - - private final List unitSelectors = new ArrayList(); - - private File defaultDirectory = null; - private static final Translator trans = Application.getTranslator(); - - private PreferencesDialog(Window parent) { - //// Preferences - super(parent, trans.get("pref.dlg.title.Preferences"), Dialog.ModalityType.APPLICATION_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill, gap unrel", "[grow]", "[grow][]")); - - JTabbedPane tabbedPane = new JTabbedPane(); - panel.add(tabbedPane, "grow, wrap"); - - //// Units and Default units - tabbedPane.addTab(trans.get("pref.dlg.tab.Units"), null, unitsPane(), - trans.get("pref.dlg.tab.Defaultunits")); - //// Materials and Custom materials - tabbedPane.addTab(trans.get("pref.dlg.tab.Materials"), null, new MaterialEditPanel(), - trans.get("pref.dlg.tab.Custommaterials")); - //// Options and Miscellaneous options - tabbedPane.addTab(trans.get("pref.dlg.tab.Options"), null, optionsPane(), - trans.get("pref.dlg.tab.Miscellaneousoptions")); - - //// Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - PreferencesDialog.this.setVisible(false); - PreferencesDialog.this.dispose(); - } - }); - panel.add(close, "span, right, tag close"); - - this.setContentPane(panel); - pack(); - this.setLocationRelativeTo(null); - - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent e) { - ((SwingPreferences) Application.getPreferences()).storeDefaultUnits(); - } - }); - - GUIUtil.setDisposableDialogOptions(this, close); - } - - - private JPanel optionsPane() { - JPanel panel = new JPanel(new MigLayout("fillx, ins 30lp n n n")); - - - //// Language selector - Locale userLocale = null; - { - String locale = Application.getPreferences().getString("locale", null); - userLocale = L10N.toLocale(locale); - } - List> locales = new ArrayList>(); - for (Locale l : SwingPreferences.getSupportedLocales()) { - locales.add(new Named(l, l.getDisplayLanguage())); - } - Collections.sort(locales); - locales.add(0, new Named(null, trans.get("languages.default"))); - - final JComboBox languageCombo = new JComboBox(locales.toArray()); - for (int i = 0; i < locales.size(); i++) { - if (Utils.equals(userLocale, locales.get(i).get())) { - languageCombo.setSelectedIndex(i); - } - } - languageCombo.addActionListener(new ActionListener() { - @Override - @SuppressWarnings("unchecked") - public void actionPerformed(ActionEvent e) { - Named selection = (Named) languageCombo.getSelectedItem(); - Locale l = selection.get(); - Application.getPreferences().putString(Preferences.USER_LOCAL, l == null ? null : l.toString()); - } - }); - panel.add(new JLabel(trans.get("lbl.language")), "gapright para"); - panel.add(languageCombo, "wrap rel, growx, sg combos"); - - panel.add(new StyledLabel(trans.get("PreferencesDialog.lbl.languageEffect"), -3, Style.ITALIC), "span, wrap para*2"); - - - //// Position to insert new body components: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Positiontoinsert")), "gapright para"); - panel.add(new JComboBox(new PrefChoiseSelector(Preferences.BODY_COMPONENT_INSERT_POSITION_KEY, - //// Always ask - //// Insert in middle - //// Add to end - trans.get("pref.dlg.PrefChoiseSelector1"), - trans.get("pref.dlg.PrefChoiseSelector2"), - trans.get("pref.dlg.PrefChoiseSelector3"))), "wrap para, growx, sg combos"); - - //// Confirm deletion of simulations: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Confirmdeletion"))); - panel.add(new JComboBox(new PrefBooleanSelector(Preferences.CONFIRM_DELETE_SIMULATION, - //// Delete - //// Confirm - trans.get("pref.dlg.PrefBooleanSelector1"), - trans.get("pref.dlg.PrefBooleanSelector2"), true)), "wrap 40lp, growx, sg combos"); - - //// User-defined thrust curves: - panel.add(new JLabel(trans.get("pref.dlg.lbl.User-definedthrust")), "spanx, wrap"); - final JTextField field = new JTextField(); - List files = ((SwingPreferences) Application.getPreferences()).getUserThrustCurveFiles(); - String str = ""; - for (File file : files) { - if (str.length() > 0) { - str += ";"; - } - str += file.getAbsolutePath(); - } - field.setText(str); - field.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - changed(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - changed(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - changed(); - } - - private void changed() { - String text = field.getText(); - List list = new ArrayList(); - for (String s : text.split(";")) { - s = s.trim(); - if (s.length() > 0) { - list.add(new File(s)); - } - } - ((SwingPreferences) Application.getPreferences()).setUserThrustCurveFiles(list); - } - }); - panel.add(field, "w 100px, gapright unrel, spanx, growx, split"); - - //// Add button - JButton button = new JButton(trans.get("pref.dlg.but.add")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser chooser = new JFileChooser(); - SimpleFileFilter filter = - new SimpleFileFilter( - //// All thrust curve files (*.eng; *.rse; *.zip; directories) - trans.get("pref.dlg.Allthrustcurvefiles"), - true, "eng", "rse", "zip"); - chooser.addChoosableFileFilter(filter); - //// RASP motor files (*.eng) - chooser.addChoosableFileFilter(new SimpleFileFilter(trans.get("pref.dlg.RASPfiles"), - true, "eng")); - //// RockSim engine files (*.rse) - chooser.addChoosableFileFilter(new SimpleFileFilter(trans.get("pref.dlg.RockSimfiles"), - true, "rse")); - //// ZIP archives (*.zip) - chooser.addChoosableFileFilter(new SimpleFileFilter(trans.get("pref.dlg.ZIParchives"), - true, "zip")); - chooser.setFileFilter(filter); - chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); - if (defaultDirectory != null) { - chooser.setCurrentDirectory(defaultDirectory); - } - - //// Add - int returnVal = chooser.showDialog(PreferencesDialog.this, trans.get("pref.dlg.Add")); - if (returnVal == JFileChooser.APPROVE_OPTION) { - log.user("Adding user thrust curve: " + chooser.getSelectedFile()); - defaultDirectory = chooser.getCurrentDirectory(); - String text = field.getText().trim(); - if (text.length() > 0) { - text += ";"; - } - text += chooser.getSelectedFile().getAbsolutePath(); - field.setText(text); - } - } - }); - panel.add(button, "gapright unrel"); - - //// Reset button - button = new JButton(trans.get("pref.dlg.but.reset")); - - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // First one sets to the default, but does not un-set the pref - field.setText(((SwingPreferences)Application.getPreferences()).getDefaultUserThrustCurveFile().getAbsolutePath()); - ((SwingPreferences) Application.getPreferences()).setUserThrustCurveFiles(null); - } - }); - panel.add(button, "wrap"); - - //// Add directories, RASP motor files (*.eng), RockSim engine files (*.rse) or ZIP archives separated by a semicolon (;) to load external thrust curves. Changes will take effect the next time you start OpenRocket. - DescriptionArea desc = new DescriptionArea(trans.get("pref.dlg.DescriptionArea.Adddirectories"), 3, -3, false); - desc.setBackground(getBackground()); - panel.add(desc, "spanx, growx, wrap 40lp"); - - - - //// Check for software updates at startup - final JCheckBox softwareUpdateBox = - new JCheckBox(trans.get("pref.dlg.checkbox.Checkupdates")); - softwareUpdateBox.setSelected( Application.getPreferences().getCheckUpdates()); - softwareUpdateBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Application.getPreferences().setCheckUpdates(softwareUpdateBox.isSelected()); - } - }); - panel.add(softwareUpdateBox); - - //// Check now button - button = new JButton(trans.get("pref.dlg.but.checknow")); - //// Check for software updates now - button.setToolTipText(trans.get("pref.dlg.ttip.Checkupdatesnow")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - checkForUpdates(); - } - }); - panel.add(button, "right, wrap"); - - - return panel; - } - - private JPanel unitsPane() { - JPanel panel = new JPanel(new MigLayout("", "[][]40lp[][]")); - JComboBox combo; - - //// Select your preferred units: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Selectprefunits")), "span, wrap paragraph"); - - - //// Rocket dimensions: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Rocketdimensions"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_LENGTH)); - panel.add(combo, "sizegroup boxes"); - - //// Line density: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Linedensity"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_DENSITY_LINE)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Motor dimensions: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Motordimensions"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_MOTOR_DIMENSIONS)); - panel.add(combo, "sizegroup boxes"); - - //// Surface density: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Surfacedensity"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_DENSITY_SURFACE)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Distance: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Distance"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_DISTANCE)); - panel.add(combo, "sizegroup boxes"); - - //// Bulk density:: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Bulkdensity"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_DENSITY_BULK)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Velocity: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Velocity"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_VELOCITY)); - panel.add(combo, "sizegroup boxes"); - - //// Surface roughness: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Surfaceroughness"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_ROUGHNESS)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Acceleration: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Acceleration"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_ACCELERATION)); - panel.add(combo, "sizegroup boxes"); - - //// Area: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Area"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_AREA)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Mass: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Mass"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_MASS)); - panel.add(combo, "sizegroup boxes"); - - //// Angle: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Angle"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_ANGLE)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Force: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Force"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_FORCE)); - panel.add(combo, "sizegroup boxes"); - - //// Roll rate: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Rollrate"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_ROLL)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Total impulse: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Totalimpulse"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_IMPULSE)); - panel.add(combo, "sizegroup boxes"); - - //// Temperature: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Temperature"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_TEMPERATURE)); - panel.add(combo, "sizegroup boxes, wrap"); - - //// Moment of inertia: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Momentofinertia"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_INERTIA)); - panel.add(combo, "sizegroup boxes"); - - //// Pressure: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Pressure"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_PRESSURE)); - panel.add(combo, "sizegroup boxes, wrap"); - - - //// Stability: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Stability"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_STABILITY)); - panel.add(combo, "sizegroup boxes"); - - //// Windspeed: - panel.add(new JLabel(trans.get("pref.dlg.lbl.Windspeed"))); - combo = new JComboBox(new DefaultUnitSelector(UnitGroup.UNITS_WINDSPEED)); - panel.add(combo, "sizegroup boxes, wrap para"); - - - - - //// Default metric button - JButton button = new JButton(trans.get("pref.dlg.but.defaultmetric")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - UnitGroup.setDefaultMetricUnits(); - for (DefaultUnitSelector s : unitSelectors) - s.fireChange(); - } - }); - panel.add(button, "spanx, split 2, grow"); - - //// Default imperial button - button = new JButton(trans.get("pref.dlg.but.defaultimperial")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - UnitGroup.setDefaultImperialUnits(); - for (DefaultUnitSelector s : unitSelectors) - s.fireChange(); - } - }); - panel.add(button, "grow, wrap para"); - - //// The effects will take place the next time you open a window. - panel.add(new StyledLabel( - trans.get("pref.dlg.lbl.effect1"), -2, Style.ITALIC), - "spanx, wrap"); - - - return panel; - } - - - - - - private class DefaultUnitSelector extends AbstractListModel implements ComboBoxModel { - - private final UnitGroup group; - - public DefaultUnitSelector(UnitGroup group) { - this.group = group; - unitSelectors.add(this); - } - - @Override - public Object getSelectedItem() { - return group.getDefaultUnit(); - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - if (!(item instanceof Unit)) { - throw new IllegalArgumentException("Illegal argument " + item); - } - group.setDefaultUnit(group.getUnitIndex((Unit) item)); - } - - @Override - public Object getElementAt(int index) { - return group.getUnit(index); - } - - @Override - public int getSize() { - return group.getUnitCount(); - } - - - public void fireChange() { - this.fireContentsChanged(this, 0, this.getSize()); - } - } - - - - private class PrefChoiseSelector extends AbstractListModel implements ComboBoxModel { - private final String preference; - private final String[] descriptions; - - public PrefChoiseSelector(String preference, String... descriptions) { - this.preference = preference; - this.descriptions = descriptions; - } - - @Override - public Object getSelectedItem() { - return descriptions[Application.getPreferences().getChoice(preference, descriptions.length, 0)]; - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - if (!(item instanceof String)) { - throw new IllegalArgumentException("Illegal argument " + item); - } - int index; - for (index = 0; index < descriptions.length; index++) { - if (((String) item).equalsIgnoreCase(descriptions[index])) - break; - } - if (index >= descriptions.length) { - throw new IllegalArgumentException("Illegal argument " + item); - } - - Application.getPreferences().putChoice(preference, index); - } - - @Override - public Object getElementAt(int index) { - return descriptions[index]; - } - - @Override - public int getSize() { - return descriptions.length; - } - } - - - private class PrefBooleanSelector extends AbstractListModel implements ComboBoxModel { - private final String preference; - private final String trueDesc, falseDesc; - private final boolean def; - - public PrefBooleanSelector(String preference, String falseDescription, - String trueDescription, boolean defaultState) { - this.preference = preference; - this.trueDesc = trueDescription; - this.falseDesc = falseDescription; - this.def = defaultState; - } - - @Override - public Object getSelectedItem() { - if (Application.getPreferences().getBoolean(preference, def)) { - return trueDesc; - } else { - return falseDesc; - } - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - if (!(item instanceof String)) { - throw new IllegalArgumentException("Illegal argument " + item); - } - - if (trueDesc.equals(item)) { - Application.getPreferences().putBoolean(preference, true); - } else if (falseDesc.equals(item)) { - Application.getPreferences().putBoolean(preference, false); - } else { - throw new IllegalArgumentException("Illegal argument " + item); - } - } - - @Override - public Object getElementAt(int index) { - switch (index) { - case 0: - return def ? trueDesc : falseDesc; - - case 1: - return def ? falseDesc : trueDesc; - - default: - throw new IndexOutOfBoundsException("Boolean asked for index=" + index); - } - } - - @Override - public int getSize() { - return 2; - } - } - - - private void checkForUpdates() { - final UpdateInfoRetriever retriever = new UpdateInfoRetriever(); - retriever.start(); - - - // Progress dialog - final JDialog dialog = new JDialog(this, ModalityType.APPLICATION_MODAL); - JPanel panel = new JPanel(new MigLayout()); - - //// Checking for updates... - panel.add(new JLabel(trans.get("pref.dlg.lbl.Checkingupdates")), "wrap"); - - JProgressBar bar = new JProgressBar(); - bar.setIndeterminate(true); - panel.add(bar, "growx, wrap para"); - - //// Cancel button - JButton cancel = new JButton(trans.get("dlg.but.cancel")); - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dialog.dispose(); - } - }); - panel.add(cancel, "right"); - dialog.add(panel); - - GUIUtil.setDisposableDialogOptions(dialog, cancel); - - - // Timer to monitor progress - final Timer timer = new Timer(100, null); - final long startTime = System.currentTimeMillis(); - - ActionListener listener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (!retriever.isRunning() || startTime + 10000 < System.currentTimeMillis()) { - timer.stop(); - dialog.dispose(); - } - } - }; - timer.addActionListener(listener); - timer.start(); - - - // Wait for action - dialog.setVisible(true); - - - // Check result - UpdateInfo info = retriever.getUpdateInfo(); - if (info == null) { - JOptionPane.showMessageDialog(this, - //// An error occurred while communicating with the server. - trans.get("pref.dlg.lbl.msg1"), - //// Unable to retrieve update information - trans.get("pref.dlg.lbl.msg2"), JOptionPane.WARNING_MESSAGE, null); - } else if (info.getLatestVersion() == null || - info.getLatestVersion().equals("") || - BuildProperties.getVersion().equalsIgnoreCase(info.getLatestVersion())) { - JOptionPane.showMessageDialog(this, - //// You are running the latest version of OpenRocket. - trans.get("pref.dlg.lbl.msg3"), - //// No updates available - trans.get("pref.dlg.lbl.msg4"), JOptionPane.INFORMATION_MESSAGE, null); - } else { - UpdateInfoDialog infoDialog = new UpdateInfoDialog(info); - infoDialog.setVisible(true); - if (infoDialog.isReminderSelected()) { - Application.getPreferences().putString(SwingPreferences.LAST_UPDATE, ""); - } else { - Application.getPreferences().putString(SwingPreferences.LAST_UPDATE, info.getLatestVersion()); - } - } - - } - - - //////// Singleton implementation //////// - - private static PreferencesDialog dialog = null; - - public static void showPreferences(Window parent) { - if (dialog != null) { - dialog.dispose(); - } - dialog = new PreferencesDialog(parent); - dialog.setVisible(true); - } - - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetChooserDialog.java b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetChooserDialog.java deleted file mode 100644 index 9efa3675..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetChooserDialog.java +++ /dev/null @@ -1,298 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preset; - - -import java.awt.Dialog; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.RowFilter; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.table.TableColumn; -import javax.swing.table.TableModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.startup.Application; - -/** - * Dialog shown for selecting a preset component. - */ -public class ComponentPresetChooserDialog extends JDialog { - - private static final Translator trans = Application.getTranslator(); - - private final RocketComponent component; - - private ComponentPresetTable componentSelectionTable; - private JTextField filterText; - private JCheckBox foreDiameterFilterCheckBox; - private JCheckBox aftDiameterFilterCheckBox; - - private ComponentPresetRowFilter foreDiameterFilter; - private ComponentPresetRowFilter aftDiameterFilter; - - - /* - * outerDiamtereColumnIndex is the index of the column associated with the OUTER_DIAMETER - * field. This index is needed by the matchOuterDiameterCheckBox to implement filtering. - */ - int aftDiameterColumnIndex = -1; - int foreDiameterColumnIndex = -1; - - private List presets; - private ComponentPreset.Type presetType; - - private boolean okClicked = false; - - - public ComponentPresetChooserDialog(Window owner, RocketComponent component) { - super(owner, trans.get("title"), Dialog.ModalityType.APPLICATION_MODAL); - this.component = component; - this.presetType = component.getPresetType(); - this.presets = Application.getComponentPresetDao().listForType(component.getPresetType()); - - List> displayedColumnKeys = Arrays.asList(component.getPresetType().getDisplayedColumns()); - - { - final List> columnKeys = ComponentPreset.ORDERED_KEY_LIST; - int i = 0; // We start at 0 but use preincrement because the first column is favorite. - for (final TypedKey key : columnKeys) { - // Note the increment early in the loop. This really means that initial loop i=1 - // we do it here so the continue below doesn't mess up the counting. - i++; - // Don't allow the matching filters if the column is not part of the default set for - // this kind of preset. - if (!displayedColumnKeys.contains(key)) { - continue; - } - if (key == ComponentPreset.OUTER_DIAMETER || key == ComponentPreset.AFT_OUTER_DIAMETER) { - aftDiameterColumnIndex = i; - } - if (key == ComponentPreset.OUTER_DIAMETER || key == ComponentPreset.FORE_OUTER_DIAMETER) { - foreDiameterColumnIndex = i; - } - } - } - - - JPanel panel = new JPanel(new MigLayout("fill, ins para")); - - /* - * Add filter by text. - */ - JPanel sub = new JPanel(new MigLayout("fill, ins 0")); - JLabel filterLabel = new JLabel(trans.get("ComponentPresetChooserDialog.filter.label")); - sub.add(filterLabel, "gapright para"); - - filterText = new JTextField(); - sub.add(filterText, "growx"); - filterText.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void changedUpdate(DocumentEvent e) { - updateFilters(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - updateFilters(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - updateFilters(); - } - }); - - panel.add(sub, "growx, ay 0, gapright para"); - - - panel.add(getFilterCheckboxes(), "wrap para"); - - componentSelectionTable = new ComponentPresetTable(presetType, presets, displayedColumnKeys); - // GUIUtil.setAutomaticColumnTableWidths(componentSelectionTable, 20); - int w = componentSelectionTable.getRowHeight() + 4; - TableColumn tc = componentSelectionTable.getColumnModel().getColumn(0); - tc.setPreferredWidth(w); - tc.setMaxWidth(w); - tc.setMinWidth(w); - - JScrollPane scrollpane = new JScrollPane(); - scrollpane.setViewportView(componentSelectionTable); - panel.add(scrollpane, "grow, width 700lp, height 300lp, spanx, wrap para"); - - - // OK / Cancel buttons - JButton okButton = new JButton(trans.get("dlg.but.ok")); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - close(true); - } - }); - panel.add(okButton, "tag ok, spanx, split"); - - //// Cancel button - JButton cancelButton = new JButton(trans.get("dlg.but.cancel")); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - close(false); - } - }); - panel.add(cancelButton, "tag cancel"); - - this.add(panel); - - GUIUtil.rememberWindowSize(this); - GUIUtil.setDisposableDialogOptions(this, okButton); - } - - - private JPanel getFilterCheckboxes() { - SymmetricComponent sc; - - JPanel panel = new JPanel(new MigLayout("fill, ins 0")); - - /* - * Add show all compatible check box. - */ - final List compatibleTypes = component.getPresetType().getCompatibleTypes(); - final ComponentPreset.Type nativeType = component.getPresetType(); - if (compatibleTypes != null && compatibleTypes.size() > 0) { - JCheckBox showAll = new JCheckBox(); - showAll.setText(trans.get("ComponentPresetChooserDialog.checkbox.showAllCompatible")); - panel.add(showAll, "wrap"); - showAll.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (((JCheckBox) e.getItem()).isSelected()) { - presets = Application.getComponentPresetDao().listForTypes(compatibleTypes); - } else { - presets = Application.getComponentPresetDao().listForType(nativeType); - } - componentSelectionTable.updateData(presets); - } - }); - } - - /* - * Add filter by fore diameter - */ - foreDiameterFilterCheckBox = new JCheckBox(trans.get("ComponentPresetChooserDialog.checkbox.filterForeDiameter")); - sc = getPreviousSymmetricComponent(); - if (sc != null && foreDiameterColumnIndex >= 0) { - foreDiameterFilter = new ComponentPresetRowFilter(sc.getAftRadius() * 2.0, foreDiameterColumnIndex); - panel.add(foreDiameterFilterCheckBox, "wrap"); - foreDiameterFilterCheckBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - updateFilters(); - } - }); - } - - /* - * Add filter by aft diameter - */ - aftDiameterFilterCheckBox = new JCheckBox(trans.get("ComponentPresetChooserDialog.checkbox.filterAftDiameter")); - sc = getNextSymmetricComponent(); - if (sc != null && aftDiameterColumnIndex >= 0) { - aftDiameterFilter = new ComponentPresetRowFilter(sc.getForeRadius() * 2.0, aftDiameterColumnIndex); - panel.add(aftDiameterFilterCheckBox, "wrap"); - aftDiameterFilterCheckBox.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - updateFilters(); - } - }); - } - - return panel; - } - - /** - * Return the motor selected by this chooser dialog, or null if the selection has been aborted. - * - * @return the selected motor, or null if no motor has been selected or the selection was canceled. - */ - public ComponentPreset getSelectedComponentPreset() { - if (!okClicked) - return null; - int row = componentSelectionTable.getSelectedRow(); - if ( row < 0 ) { - // Nothing selected. - return null; - } - row = componentSelectionTable.convertRowIndexToModel(row); - return presets.get(row); - } - - public void close(boolean ok) { - okClicked = ok; - this.setVisible(false); - } - - private void updateFilters() { - List> filters = new ArrayList>(2); - String filterTextRegex = filterText.getText(); - if (filterTextRegex != null) { - try { - // The "(?iu)" magic turns on case insensitivity with unicode chars - RowFilter regexFilter = RowFilter.regexFilter("(?iu)" + filterTextRegex); - filters.add(regexFilter); - } catch (java.util.regex.PatternSyntaxException e) { - } - } - if (aftDiameterFilterCheckBox.isSelected()) { - filters.add(aftDiameterFilter); - } - if (foreDiameterFilterCheckBox.isSelected()) { - filters.add(foreDiameterFilter); - } - - componentSelectionTable.setRowFilter(RowFilter.andFilter(filters)); - } - - - private SymmetricComponent getPreviousSymmetricComponent() { - RocketComponent c = component; - while (c != null) { - c = c.getPreviousComponent(); - if (c instanceof SymmetricComponent) { - return (SymmetricComponent) c; - } - } - return null; - } - - - private SymmetricComponent getNextSymmetricComponent() { - RocketComponent c = component; - while (c != null) { - c = c.getNextComponent(); - if (c instanceof SymmetricComponent) { - return (SymmetricComponent) c; - } - } - return null; - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetRowFilter.java b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetRowFilter.java deleted file mode 100644 index 7c66aa13..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetRowFilter.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preset; - -import javax.swing.RowFilter; -import javax.swing.table.TableModel; - -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.MathUtil; - -public class ComponentPresetRowFilter extends RowFilter { - - private final double value; - private final int column; - private final double epsilon; - - ComponentPresetRowFilter(double value, int column) { - this.value = value; - this.column = column; - /* - * Accept 5% difference, but at least 1mm. - */ - this.epsilon = MathUtil.max(value * 0.05, 0.001); - } - - @Override - public boolean include(RowFilter.Entry entry) { - Object o = entry.getValue(column); - if (o instanceof Value) { - Value v = (Value) o; - return Math.abs(value - v.getValue()) < epsilon; - } - if (o instanceof Double) { - Double d = (Double) o; - return Math.abs(value - d) < epsilon; - } - return true; - } - -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTable.java b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTable.java deleted file mode 100644 index cad447f1..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTable.java +++ /dev/null @@ -1,283 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preset; - -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Set; - -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JMenu; -import javax.swing.JPopupMenu; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.RowFilter; -import javax.swing.RowSorter.SortKey; -import javax.swing.SortOrder; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.JTableHeader; -import javax.swing.table.TableColumn; -import javax.swing.table.TableModel; -import javax.swing.table.TableRowSorter; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.AlphanumComparator; - -public class ComponentPresetTable extends JTable { - - private static final Translator trans = Application.getTranslator(); - - private final TableRowSorter sorter; - private List presets; - private final ComponentPreset.Type presetType; - private Set favorites; - private final AbstractTableModel tableModel; - private final XTableColumnModel tableColumnModel; - private final ComponentPresetTableColumn[] columns; - - public ComponentPresetTable(final ComponentPreset.Type presetType, List presets, List> visibleColumnKeys) { - super(); - this.presets = presets; - this.presetType = presetType; - this.favorites = Application.getPreferences().getComponentFavorites(presetType); - this.columns = new ComponentPresetTableColumn[ComponentPreset.ORDERED_KEY_LIST.size()+1]; - - - tableModel = new AbstractTableModel() { - final ComponentPresetTableColumn[] myColumns = columns; - @Override - public int getRowCount() { - return ComponentPresetTable.this.presets.size(); - } - - @Override - public int getColumnCount() { - return myColumns.length; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - return myColumns[columnIndex].getValueFromPreset(favorites,ComponentPresetTable.this.presets.get(rowIndex)); - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - // Only support favorite - if ( columnIndex != 0 ) { - return; - } - ComponentPreset preset = ComponentPresetTable.this.presets.get(rowIndex); - Application.getComponentPresetDao().setFavorite(preset, presetType, (Boolean) aValue); - ComponentPresetTable.this.updateFavorites(); - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - return columnIndex == 0; - } - - @Override - public Class getColumnClass(int columnIndex) { - return columnIndex == 0 ? Boolean.class : Object.class; - } - - }; - - - sorter = new TableRowSorter(tableModel); - - tableColumnModel = new XTableColumnModel(); - - /* - * Set up the Column Table model, and customize the sorting. - */ - columns[0] = new ComponentPresetTableColumn.Favorite(0); - tableColumnModel.addColumn(columns[0]); - - List hiddenColumns = new ArrayList(); - { - int index = 1; - for (final TypedKey key: ComponentPreset.ORDERED_KEY_LIST ) { - if ( key.getType() == Double.class && key.getUnitGroup() != null ) { - columns[index] = new ComponentPresetTableColumn.DoubleWithUnit((TypedKey)key,index); - } else { - columns[index] = new ComponentPresetTableColumn.Parameter(key,index); - } - tableColumnModel.addColumn(columns[index]); - if ( key == ComponentPreset.MANUFACTURER || key == ComponentPreset.PARTNO ) { - sorter.setComparator(index, new AlphanumComparator()); - } else if ( key.getType() == Double.class ) { - sorter.setComparator(index, new Comparator() { - - @Override - public int compare(Value o1, Value o2) { - return Double.compare(o1.getValue(), o2.getValue()); - } - - }); - } - if ( visibleColumnKeys.indexOf(key) < 0 ) { - hiddenColumns.add(columns[index]); - } - index ++; - } - } - - this.setAutoCreateColumnsFromModel(false); - this.setColumnModel( tableColumnModel ); - this.setModel(tableModel); - this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - this.setRowSorter(sorter); - - for ( TableColumn hiddenColumn : hiddenColumns ) { - tableColumnModel.setColumnVisible(hiddenColumn, false); - } - - JTableHeader header = this.getTableHeader(); - - header.setReorderingAllowed(true); - - header.addMouseListener( new MouseAdapter() { - - @Override - public void mousePressed(MouseEvent e) { - if ( e.isPopupTrigger() ) { - doPopup(e); - } - } - @Override - public void mouseReleased(MouseEvent e) { - if ( e.isPopupTrigger() ) { - doPopup(e); - } - } - }); - } - - public void setRowFilter( RowFilter filter ) { - sorter.setRowFilter( filter ); - } - - public void updateData( List presets ) { - this.presets = presets; - this.favorites = Application.getPreferences().getComponentFavorites(presetType); - this.tableModel.fireTableDataChanged(); - } - - public void updateFavorites() { - this.favorites = Application.getPreferences().getComponentFavorites(presetType); - this.tableModel.fireTableDataChanged(); - } - - private void doPopup(MouseEvent evt ) { - - // Figure out what column header was clicked on. - int colIndex = tableColumnModel.getColumnIndexAtX( evt.getX() ); - ComponentPresetTableColumn colClicked = null; - if ( colIndex >=0 ) { - colClicked = (ComponentPresetTableColumn) tableColumnModel.getColumn(colIndex); - } - - JPopupMenu columnMenu = new ColumnPopupMenu(colClicked, colIndex); - columnMenu.show(evt.getComponent(),evt.getX(),evt.getY()); - } - - private class ColumnPopupMenu extends JPopupMenu { - - ColumnPopupMenu(ComponentPresetTableColumn colClicked, int colClickedIndex) { - if ( colClickedIndex >= 0 ) { - JCheckBoxMenuItem item = new SortAscColumnMenuItem(colClickedIndex); - this.add(item); - item = new SortDescColumnMenuItem(colClickedIndex); - this.add(item); - this.addSeparator(); - if ( colClicked instanceof ComponentPresetTableColumn.DoubleWithUnit ) { - this.add( new UnitSelectorMenuItem( (ComponentPresetTableColumn.DoubleWithUnit) colClicked )); - this.addSeparator(); - } - } - for( TableColumn c: columns ) { - JCheckBoxMenuItem item = new ToggleColumnMenuItem(c); - this.add(item); - } - } - - - private class SortAscColumnMenuItem extends JCheckBoxMenuItem implements ItemListener { - private int columnClicked; - SortAscColumnMenuItem(int columnClicked) { - super( trans.get("ComponentPresetChooserDialog.menu.sortAsc") ); - this.addItemListener(this); - this.columnClicked = columnClicked; - } - @Override - public void itemStateChanged(ItemEvent e) { - sorter.setSortKeys( Collections.singletonList( new SortKey(columnClicked, SortOrder.ASCENDING))); - } - } - - private class SortDescColumnMenuItem extends JCheckBoxMenuItem implements ItemListener { - private int columnClicked; - SortDescColumnMenuItem(int columnClicked) { - super( trans.get("ComponentPresetChooserDialog.menu.sortDesc") ); - this.addItemListener(this); - this.columnClicked = columnClicked; - } - @Override - public void itemStateChanged(ItemEvent e) { - sorter.setSortKeys( Collections.singletonList( new SortKey(columnClicked, SortOrder.DESCENDING))); - } - } - - private class ToggleColumnMenuItem extends JCheckBoxMenuItem implements ItemListener { - TableColumn col; - ToggleColumnMenuItem( TableColumn col ) { - super( String.valueOf(col.getHeaderValue()), tableColumnModel.isColumnVisible(col)); - this.addItemListener(this); - this.col = col; - } - @Override - public void itemStateChanged(ItemEvent e) { - tableColumnModel.setColumnVisible(col, !tableColumnModel.isColumnVisible(col)); - } - } - - private class UnitSelectorMenuItem extends JMenu implements ItemListener { - ComponentPresetTableColumn.DoubleWithUnit col; - UnitSelectorMenuItem( ComponentPresetTableColumn.DoubleWithUnit col ) { - super(trans.get("ComponentPresetChooserDialog.menu.units")); - this.col = col; - UnitGroup group = col.unitGroup; - Unit selectedUnit = col.selectedUnit; - for( Unit u : group.getUnits() ) { - JCheckBoxMenuItem item = new JCheckBoxMenuItem( u.toString() ); - if ( u == selectedUnit ) { - item.setSelected(true); - } - item.addItemListener(this); - this.add(item); - } - - } - @Override - public void itemStateChanged(ItemEvent e) { - JCheckBoxMenuItem item = (JCheckBoxMenuItem) e.getItem(); - String val = item.getText(); - col.selectedUnit = col.unitGroup.findApproximate(val); - ComponentPresetTable.this.tableModel.fireTableDataChanged(); - return; - } - - } - } -} diff --git a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTableColumn.java b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTableColumn.java deleted file mode 100644 index 5d5d12d6..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTableColumn.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preset; - -import java.util.Set; - -import javax.swing.table.TableColumn; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; - -public abstract class ComponentPresetTableColumn extends TableColumn { - - private static final Translator trans = Application.getTranslator(); - - protected ComponentPresetTableColumn( String header, int modelIndex ) { - this.setHeaderValue(header); - this.setModelIndex(modelIndex); - - } - - public abstract Object getValueFromPreset( Set favorites, ComponentPreset preset ); - - public static class Favorite extends ComponentPresetTableColumn { - - public Favorite(int modelIndex) { - super(trans.get("table.column.Favorite"), modelIndex); - } - - @Override - public Object getValueFromPreset( Set favorites, ComponentPreset preset ) { - return Boolean.valueOf(favorites.contains(preset.preferenceKey())); - } - - } - - public static class Parameter extends ComponentPresetTableColumn { - - protected final TypedKey key; - - public Parameter( TypedKey key, int modelIndex ) { - super( trans.get("table.column." + key.getName()), modelIndex ); - this.key = key; - } - - @Override - public Object getValueFromPreset(Set favorites, ComponentPreset preset) { - return preset.has(key) ? preset.get(key) : null; - } - - } - - - public static class DoubleWithUnit extends Parameter { - - UnitGroup unitGroup; - Unit selectedUnit; - - public DoubleWithUnit( TypedKey key, int modelIndex ) { - super(key,modelIndex); - this.unitGroup = key.getUnitGroup(); - this.selectedUnit = unitGroup.getDefaultUnit(); - } - - @Override - public Object getValueFromPreset(Set favorites, ComponentPreset preset) { - Double value = (Double) super.getValueFromPreset(favorites, preset); - if ( value != null ) { - return new Value((Double)super.getValueFromPreset(favorites, preset),selectedUnit); - } else { - return null; - } - } - - - } - -} - - - diff --git a/core/src/net/sf/openrocket/gui/dialogs/preset/XTableColumnModel.java b/core/src/net/sf/openrocket/gui/dialogs/preset/XTableColumnModel.java deleted file mode 100644 index ac05c789..00000000 --- a/core/src/net/sf/openrocket/gui/dialogs/preset/XTableColumnModel.java +++ /dev/null @@ -1,242 +0,0 @@ -package net.sf.openrocket.gui.dialogs.preset; - -import java.util.Enumeration; -import java.util.Vector; - -import javax.swing.table.DefaultTableColumnModel; -import javax.swing.table.TableColumn; - -public class XTableColumnModel extends DefaultTableColumnModel { - - /** Array of TableColumn objects in this model. - * Holds all column objects, regardless of their visibility - */ - protected Vector allTableColumns = new Vector(); - - /** - * Creates an extended table column model. - */ - XTableColumnModel() { - super(); - } - - /** - * Sets the visibility of the specified TableColumn. - * The call is ignored if the TableColumn is not found in this column model - * or its visibility status did not change. - *

- * - * @param aColumn the column to show/hide - * @param visible its new visibility status - */ - // listeners will receive columnAdded()/columnRemoved() event - public void setColumnVisible(TableColumn column, boolean visible) { - if (!visible) { - super.removeColumn(column); - } - else { - // find the visible index of the column: - // iterate through both collections of visible and all columns, counting - // visible columns up to the one that's about to be shown again - int noVisibleColumns = tableColumns.size(); - int noInvisibleColumns = allTableColumns.size(); - int visibleIndex = 0; - - for (int invisibleIndex = 0; invisibleIndex < noInvisibleColumns; ++invisibleIndex) { - TableColumn visibleColumn = (visibleIndex < noVisibleColumns ? (TableColumn) tableColumns.get(visibleIndex) : null); - TableColumn testColumn = allTableColumns.get(invisibleIndex); - - if (testColumn == column) { - if (visibleColumn != column) { - super.addColumn(column); - super.moveColumn(tableColumns.size() - 1, visibleIndex); - } - return; // #################### - } - if (testColumn == visibleColumn) { - ++visibleIndex; - } - } - } - } - - /** - * Makes all columns in this model visible - */ - public void setAllColumnsVisible(boolean visible) { - int noColumns = allTableColumns.size(); - - for (int columnIndex = 0; columnIndex < noColumns; ++columnIndex) { - TableColumn visibleColumn = (columnIndex < tableColumns.size() ? (TableColumn) tableColumns.get(columnIndex) : null); - TableColumn invisibleColumn = allTableColumns.get(columnIndex); - if (visible) { - - if (visibleColumn != invisibleColumn) { - super.addColumn(invisibleColumn); - super.moveColumn(tableColumns.size() - 1, columnIndex); - } - } else { - super.removeColumn(invisibleColumn); - } - } - } - - /** - * Maps the index of the column in the table model at - * modelColumnIndex to the TableColumn object. - * There may me multiple TableColumn objects showing the same model column, though this is uncommon. - * This method will always return the first visible or else the first invisible column with the specified index. - * @param modelColumnIndex index of column in table model - * @return table column object or null if no such column in this column model - */ - public TableColumn getColumnByModelIndex(int modelColumnIndex) { - for (int columnIndex = 0; columnIndex < allTableColumns.size(); ++columnIndex) { - TableColumn column = allTableColumns.get(columnIndex); - if (column.getModelIndex() == modelColumnIndex) { - return column; - } - } - return null; - } - - /** Checks wether the specified column is currently visible. - * @param aColumn column to check - * @return visibility of specified column (false if there is no such column at all. [It's not visible, right?]) - */ - public boolean isColumnVisible(TableColumn aColumn) { - return (tableColumns.indexOf(aColumn) >= 0); - } - - /** Append column to the right of exisiting columns. - * Posts columnAdded event. - * @param column The column to be added - * @see #removeColumn - * @exception IllegalArgumentException if column is null - */ - @Override - public void addColumn(TableColumn column) { - allTableColumns.add(column); - super.addColumn(column); - } - - /** Removes column from this column model. - * Posts columnRemoved event. - * Will do nothing if the column is not in this model. - * @param column the column to be added - * @see #addColumn - */ - @Override - public void removeColumn(TableColumn column) { - int allColumnsIndex = allTableColumns.indexOf(column); - if (allColumnsIndex != -1) { - allTableColumns.remove(allColumnsIndex); - } - super.removeColumn(column); - } - - /** - * Moves the column from oldIndex to newIndex. - * Posts columnMoved event. - * Will not move any columns if oldIndex equals newIndex. - * - * @param oldIndex index of column to be moved - * @param newIndex new index of the column - * @exception IllegalArgumentException if either oldIndex or - * newIndex - * are not in [0, getColumnCount() - 1] - */ - @Override - public void moveColumn(int oldIndex, int newIndex) { - if ((oldIndex < 0) || (oldIndex >= getColumnCount()) || - (newIndex < 0) || (newIndex >= getColumnCount())) - throw new IllegalArgumentException("moveColumn() - Index out of range"); - - TableColumn fromColumn = tableColumns.get(oldIndex); - TableColumn toColumn = tableColumns.get(newIndex); - - int allColumnsOldIndex = allTableColumns.indexOf(fromColumn); - int allColumnsNewIndex = allTableColumns.indexOf(toColumn); - - if (oldIndex != newIndex) { - allTableColumns.remove(allColumnsOldIndex); - allTableColumns.add(allColumnsNewIndex, fromColumn); - } - - super.moveColumn(oldIndex, newIndex); - } - - /** - * Returns the total number of columns in this model. - * - * @param onlyVisible if set only visible columns will be counted - * @return the number of columns in the tableColumns array - * @see #getColumns - */ - public int getColumnCount(boolean onlyVisible) { - Vector columns = (onlyVisible ? tableColumns : allTableColumns); - return columns.size(); - } - - /** - * Returns an Enumeration of all the columns in the model. - * - * @param onlyVisible if set all invisible columns will be missing from the enumeration. - * @return an Enumeration of the columns in the model - */ - public Enumeration getColumns(boolean onlyVisible) { - Vector columns = (onlyVisible ? tableColumns : allTableColumns); - - return columns.elements(); - } - - /** - * Returns the position of the first column whose identifier equals identifier. - * Position is the the index in all visible columns if onlyVisible is true or - * else the index in all columns. - * - * @param identifier the identifier object to search for - * @param onlyVisible if set searches only visible columns - * - * @return the index of the first column whose identifier - * equals identifier - * - * @exception IllegalArgumentException if identifier - * is null, or if no - * TableColumn has this - * identifier - * @see #getColumn - */ - public int getColumnIndex(Object identifier, boolean onlyVisible) { - if (identifier == null) { - throw new IllegalArgumentException("Identifier is null"); - } - - Vector columns = (onlyVisible ? tableColumns : allTableColumns); - int noColumns = columns.size(); - TableColumn column; - - for (int columnIndex = 0; columnIndex < noColumns; ++columnIndex) { - column = columns.get(columnIndex); - - if (identifier.equals(column.getIdentifier())) - return columnIndex; - } - - throw new IllegalArgumentException("Identifier not found"); - } - - /** - * Returns the TableColumn object for the column - * at columnIndex. - * - * @param columnIndex the index of the column desired - * @param onlyVisible if set columnIndex is meant to be relative to all visible columns only - * else it is the index in all columns - * - * @return the TableColumn object for the column - * at columnIndex - */ - public TableColumn getColumn(int columnIndex, boolean onlyVisible) { - return tableColumns.elementAt(columnIndex); - } -} diff --git a/core/src/net/sf/openrocket/gui/figure3d/ComponentRenderer.java b/core/src/net/sf/openrocket/gui/figure3d/ComponentRenderer.java deleted file mode 100644 index 80cdbfc0..00000000 --- a/core/src/net/sf/openrocket/gui/figure3d/ComponentRenderer.java +++ /dev/null @@ -1,340 +0,0 @@ -package net.sf.openrocket.gui.figure3d; - -import java.util.HashMap; -import java.util.Map; - -import javax.media.opengl.GL; -import javax.media.opengl.GL2; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.fixedfunc.GLLightingFunc; -import javax.media.opengl.fixedfunc.GLMatrixFunc; -import javax.media.opengl.glu.GLU; -import javax.media.opengl.glu.GLUquadric; -import javax.media.opengl.glu.GLUtessellator; -import javax.media.opengl.glu.GLUtessellatorCallback; -import javax.media.opengl.glu.GLUtessellatorCallbackAdapter; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; - -/* - * @author Bill Kuker - */ -public class ComponentRenderer { - private static final LogHelper log = Application.getLogger(); - - private int LOD = 80; - - GLU glu; - GLUquadric q; - GLUtessellator tobj; - - public ComponentRenderer() { - - } - - public void init(GLAutoDrawable drawable) { - glu = new GLU(); - q = glu.gluNewQuadric(); - tobj = GLU.gluNewTess(); - glu.gluQuadricTexture(q, true); - } - - private Map lists = new HashMap(); - private boolean clearDisplayLists = false; - public void updateFigure() { - clearDisplayLists = true; - } - - public void renderGeometry(GL2 gl, RocketComponent c) { - if (glu == null) - throw new IllegalStateException(this + " Not Initialized"); - - glu.gluQuadricNormals(q, GLU.GLU_SMOOTH); - - if ( clearDisplayLists ){ - log.debug("Clearing Display Lists"); - for ( int i : lists.values() ){ - gl.glDeleteLists(i,1); - } - lists.clear(); - clearDisplayLists = false; - } - if ( lists.containsKey(c) ){ - gl.glCallList(lists.get(c)); - } else { - int list = gl.glGenLists(1); - gl.glNewList(list, GL2.GL_COMPILE_AND_EXECUTE); - - Coordinate[] oo = c.toAbsolute(new Coordinate(0, 0, 0)); - - for (Coordinate o : oo) { - gl.glPushMatrix(); - - gl.glTranslated(o.x, o.y, o.z); - - if (c instanceof BodyTube) { - renderTube(gl, (BodyTube) c); - } else if (c instanceof LaunchLug) { - renderLug(gl, (LaunchLug) c); - } else if (c instanceof RingComponent) { - renderRing(gl, (RingComponent) c); - } else if (c instanceof Transition) { - renderTransition(gl, (Transition) c); - } else if (c instanceof MassObject) { - renderMassObject(gl, (MassObject) c); - } else if (c instanceof FinSet) { - renderFinSet(gl, (FinSet) c); - } else { - renderOther(gl, c); - } - gl.glPopMatrix(); - } - - gl.glEndList(); - lists.put(c, list); - } - } - - private void renderOther(GL2 gl, RocketComponent c) { - gl.glBegin(GL.GL_LINES); - for (Coordinate cc : c.getComponentBounds()) { - for (Coordinate ccc : c.getComponentBounds()) { - gl.glVertex3d(cc.x, cc.y, cc.z); - gl.glVertex3d(ccc.x, ccc.y, ccc.z); - } - } - gl.glEnd(); - } - - private void renderTransition(GL2 gl, Transition t) { - gl.glRotated(90, 0, 1.0, 0); - - if (t.getType() == Transition.Shape.CONICAL) { - glu.gluCylinder(q, t.getForeRadius(), t.getAftRadius(), - t.getLength(), LOD, 1); - } else { - TransitionRenderer.drawTransition(gl, t, LOD, LOD); - } - - // Render AFT shoulder - gl.glPushMatrix(); - gl.glTranslated(0, 0, t.getLength()); - - glu.gluCylinder(q, t.getAftShoulderRadius(), t.getAftShoulderRadius(), - t.getAftShoulderLength(), LOD, 1); - - gl.glRotated(180, 0, 1.0, 0); - - glu.gluDisk(q, t.getAftRadius(), t.getAftShoulderRadius(), LOD, 2); - - gl.glTranslated(0, 0, -t.getAftShoulderLength()); - - if (t.isFilled() || t.isAftShoulderCapped()) { - glu.gluDisk(q, t.getAftShoulderRadius(), 0, LOD, 2); - } - gl.glPopMatrix(); - - // Render Fore Shoulder - gl.glPushMatrix(); - gl.glRotated(180, 0, 1.0, 0); - - glu.gluCylinder(q, t.getForeShoulderRadius(), - t.getForeShoulderRadius(), t.getForeShoulderLength(), LOD, 1); - - gl.glRotated(180, 0, 1.0, 0); - - glu.gluDisk(q, t.getForeRadius(), t.getForeShoulderRadius(), LOD, 2); - - gl.glTranslated(0, 0, -t.getForeShoulderLength()); - - if (t.isFilled() || t.isForeShoulderCapped()) { - glu.gluDisk(q, t.getForeShoulderRadius(), 0, LOD, 2); - } - gl.glPopMatrix(); - - } - - private void renderTube(GL2 gl, BodyTube t) { - gl.glRotated(90, 0, 1.0, 0); - glu.gluCylinder(q, t.getOuterRadius(), t.getOuterRadius(), - t.getLength(), LOD, 1); - } - - private void renderRing(GL2 gl, RingComponent r) { - gl.glRotated(90, 0, 1.0, 0); - glu.gluCylinder(q, r.getOuterRadius(), r.getOuterRadius(), - r.getLength(), LOD, 1); - - gl.glRotated(180, 0, 1.0, 0); - glu.gluDisk(q, r.getInnerRadius(), r.getOuterRadius(), LOD, 2); - - gl.glRotated(180, 0, 1.0, 0); - gl.glTranslated(0, 0, r.getLength()); - glu.gluDisk(q, r.getInnerRadius(), r.getOuterRadius(), LOD, 2); - - gl.glTranslated(0, 0, -r.getLength()); - glu.gluCylinder(q, r.getInnerRadius(), r.getInnerRadius(), - r.getLength(), LOD, 1); - - } - - private void renderLug(GL2 gl, LaunchLug t) { - - gl.glRotated(90, 0, 1.0, 0); - glu.gluCylinder(q, t.getOuterRadius(), t.getOuterRadius(), - t.getLength(), LOD, 1); - } - - private void renderMassObject(GL2 gl, MassObject o) { - gl.glRotated(90, 0, 1.0, 0); - - MassObjectRenderer.drawMassObject(gl, o, LOD, LOD); - } - - private void renderFinSet(final GL2 gl, FinSet fs) { - - Coordinate finPoints[] = fs.getFinPointsWithTab(); - - double minX = Double.MAX_VALUE; - double minY = Double.MAX_VALUE; - double maxX = Double.MIN_VALUE; - double maxY = Double.MIN_VALUE; - - for (int i = 0; i < finPoints.length; i++) { - Coordinate c = finPoints[i]; - minX = Math.min(c.x, minX); - minY = Math.min(c.y, minY); - maxX = Math.max(c.x, maxX); - maxY = Math.max(c.y, maxY); - } - - gl.glMatrixMode(GL.GL_TEXTURE); - gl.glPushMatrix(); - gl.glScaled(1/(maxX-minX), 1/(maxY-minY), 0); - gl.glTranslated(-minX, -minY - fs.getBodyRadius(), 0); - gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); - - gl.glRotated(fs.getBaseRotation() * (180.0 / Math.PI), 1, 0, 0); - - for (int fin = 0; fin < fs.getFinCount(); fin++) { - - gl.glPushMatrix(); - - gl.glTranslated(fs.getLength() / 2, 0, 0); - gl.glRotated(fs.getCantAngle() * (180.0 / Math.PI), 0, 1, 0); - gl.glTranslated(-fs.getLength() / 2, 0, 0); - - GLUtessellatorCallback cb = new GLUtessellatorCallbackAdapter() { - @Override - public void vertex(Object vertexData) { - double d[] = (double[]) vertexData; - gl.glTexCoord2d(d[0], d[1]); - gl.glVertex3dv(d, 0); - } - - @Override - public void begin(int type) { - gl.glBegin(type); - } - - @Override - public void end() { - gl.glEnd(); - } - }; - - GLU.gluTessCallback(tobj, GLU.GLU_TESS_VERTEX, cb); - GLU.gluTessCallback(tobj, GLU.GLU_TESS_BEGIN, cb); - GLU.gluTessCallback(tobj, GLU.GLU_TESS_END, cb); - - GLU.gluTessBeginPolygon(tobj, null); - GLU.gluTessBeginContour(tobj); - gl.glNormal3f(0, 0, 1); - for (int i = finPoints.length - 1; i >= 0; i--) { - Coordinate c = finPoints[i]; - double[] p = new double[] { c.x, c.y + fs.getBodyRadius(), - c.z + fs.getThickness() / 2.0 }; - GLU.gluTessVertex(tobj, p, 0, p); - - } - GLU.gluTessEndContour(tobj); - GLU.gluTessEndPolygon(tobj); - - GLU.gluTessBeginPolygon(tobj, null); - GLU.gluTessBeginContour(tobj); - gl.glNormal3f(0, 0, -1); - for (int i = 0; i < finPoints.length; i++) { - Coordinate c = finPoints[i]; - double[] p = new double[] { c.x, c.y + fs.getBodyRadius(), - c.z - fs.getThickness() / 2.0 }; - GLU.gluTessVertex(tobj, p, 0, p); - - } - GLU.gluTessEndContour(tobj); - GLU.gluTessEndPolygon(tobj); - - // Strip around the edge - if (!(fs instanceof EllipticalFinSet)) - gl.glShadeModel(GLLightingFunc.GL_FLAT); - gl.glBegin(GL.GL_TRIANGLE_STRIP); - for (int i = 0; i <= finPoints.length; i++) { - Coordinate c = finPoints[i % finPoints.length]; - // if ( i > 1 ){ - Coordinate c2 = finPoints[(i - 1 + finPoints.length) - % finPoints.length]; - gl.glNormal3d(c2.y - c.y, c.x - c2.x, 0); - // } - gl.glTexCoord2d(c.x, c.y + fs.getBodyRadius()); - gl.glVertex3d(c.x, c.y + fs.getBodyRadius(), - c.z - fs.getThickness() / 2.0); - gl.glVertex3d(c.x, c.y + fs.getBodyRadius(), - c.z + fs.getThickness() / 2.0); - } - gl.glEnd(); - if (!(fs instanceof EllipticalFinSet)) - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - - gl.glPopMatrix(); - - gl.glRotated(360.0 / fs.getFinCount(), 1, 0, 0); - } - - gl.glMatrixMode(GL.GL_TEXTURE); - gl.glPopMatrix(); - gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); - - } - - public void renderMotor(final GL2 gl, final Coordinate c, double l, double r) { - final float outside[] = { 0.2f, 0.2f, 0.2f, 1.0f }; - gl.glMaterialfv(GL.GL_FRONT, GLLightingFunc.GL_DIFFUSE, outside, 0); - gl.glMaterialfv(GL.GL_FRONT, GLLightingFunc.GL_AMBIENT, outside, 0); - - gl.glPushMatrix(); - - gl.glTranslated(c.x, c.y, c.z); - - gl.glRotated(90, 0, 1.0, 0); - - glu.gluCylinder(q, r, r, l, LOD, 1); - - glu.gluDisk(q, r, 0, LOD, 2); - - gl.glTranslated(0, 0, l); - gl.glRotated(180, 0, 1.0, 0); - - glu.gluDisk(q, r, 0, LOD, 2); - - gl.glPopMatrix(); - } -} diff --git a/core/src/net/sf/openrocket/gui/figure3d/MassObjectRenderer.java b/core/src/net/sf/openrocket/gui/figure3d/MassObjectRenderer.java deleted file mode 100644 index 4c1d9344..00000000 --- a/core/src/net/sf/openrocket/gui/figure3d/MassObjectRenderer.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - ** License Applicability. Except to the extent portions of this file are - ** made subject to an alternative license as permitted in the SGI Free - ** Software License B, Version 2.0 (the "License"), the contents of this - ** file are subject only to the provisions of the License. You may not use - ** this file except in compliance with the License. You may obtain a copy - ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 - ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: - ** - ** http://oss.sgi.com/projects/FreeB - ** - ** Note that, as provided in the License, the Software is distributed on an - ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS - ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND - ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A - ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - ** - ** NOTE: The Original Code (as defined below) has been licensed to Sun - ** Microsystems, Inc. ("Sun") under the SGI Free Software License B - ** (Version 1.1), shown above ("SGI License"). Pursuant to Section - ** 3.2(3) of the SGI License, Sun is distributing the Covered Code to - ** you under an alternative license ("Alternative License"). This - ** Alternative License includes all of the provisions of the SGI License - ** except that Section 2.2 and 11 are omitted. Any differences between - ** the Alternative License and the SGI License are offered solely by Sun - ** and not by SGI. - ** - ** Original Code. The Original Code is: OpenGL Sample Implementation, - ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, - ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. - ** Copyright in any portions created by third parties is as indicated - ** elsewhere herein. All Rights Reserved. - ** - ** Additional Notice Provisions: The application programming interfaces - ** established by SGI in conjunction with the Original Code are The - ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released - ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version - ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X - ** Window System(R) (Version 1.3), released October 19, 1998. This software - ** was created using the OpenGL(R) version 1.2.1 Sample Implementation - ** published by SGI, but has not been independently verified as being - ** compliant with the OpenGL(R) version 1.2.1 Specification. - ** - ** $Date: 2009-03-04 17:23:34 -0800 (Wed, 04 Mar 2009) $ $Revision: 1856 $ - ** $Header$ - */ - -/* - * Copyright (c) 2002-2004 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any kind. ALL - * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, - * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN - * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR - * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR - * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR - * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE - * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, - * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF - * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for use - * in the design, construction, operation or maintenance of any nuclear - * facility. - */ -package net.sf.openrocket.gui.figure3d; - -import javax.media.opengl.GL; -import javax.media.opengl.GL2; - -import net.sf.openrocket.rocketcomponent.MassObject; - -public final class MassObjectRenderer { - private static final boolean textureFlag = true; - - private MassObjectRenderer() { - } - - public static final void drawMassObject(final GL2 gl, final MassObject o, - final int slices, final int stacks) { - - double da, r, dz; - double x, y, z, nz, nsign; - int i, j; - - nsign = 1.0f; - - da = 2.0f * PI / slices; - dz = o.getLength() / stacks; - - double ds = 1.0f / slices; - double dt = 1.0f / stacks; - double t = 0.0f; - z = 0.0f; - for (j = 0; j < stacks; j++) { - r = getRadius(o, z); - double rNext = getRadius(o, z + dz); - if (j == stacks - 1) - rNext = 0; - - if (j == stacks - 1) - rNext = 0; - - // Z component of normal vectors - nz = -(rNext - r) / dz; - - double s = 0.0f; - glBegin(gl, GL2.GL_QUAD_STRIP); - for (i = 0; i <= slices; i++) { - if (i == slices) { - x = sin(0.0f); - y = cos(0.0f); - } else { - x = sin((i * da)); - y = cos((i * da)); - } - if (nsign == 1.0f) { - normal3d(gl, (x * nsign), (y * nsign), (nz * nsign)); - TXTR_COORD(gl, s, t); - glVertex3d(gl, (x * r), (y * r), z); - normal3d(gl, (x * nsign), (y * nsign), (nz * nsign)); - TXTR_COORD(gl, s, t + dt); - glVertex3d(gl, (x * rNext), (y * rNext), (z + dz)); - } else { - normal3d(gl, x * nsign, y * nsign, nz * nsign); - TXTR_COORD(gl, s, t); - glVertex3d(gl, (x * r), (y * r), z); - normal3d(gl, x * nsign, y * nsign, nz * nsign); - TXTR_COORD(gl, s, t + dt); - glVertex3d(gl, (x * rNext), (y * rNext), (z + dz)); - } - s += ds; - } // for slices - glEnd(gl); - // r += dr; - t += dt; - z += dz; - } // for stacks - } - - private static final double getRadius(MassObject o, double z) { - double arc = Math.min(o.getLength(), 2 * o.getRadius()) * 0.35f; - double r = o.getRadius(); - if (z == 0 || z == o.getLength()) - return 0; - if (z < arc) { - double zz = z - arc; - return (r - arc) + Math.sqrt(arc * arc - zz * zz); - } - if (z > o.getLength() - arc) { - double zz = (z - o.getLength() + arc); - return (r - arc) + Math.sqrt(arc * arc - zz * zz); - } - return o.getRadius(); - } - - // ---------------------------------------------------------------------- - // Internals only below this point - // - - private static final double PI = Math.PI; - - private static final void glBegin(GL gl, int mode) { - gl.getGL2().glBegin(mode); - } - - private static final void glEnd(GL gl) { - gl.getGL2().glEnd(); - } - - private static final void glVertex3d(GL gl, double x, double y, double z) { - gl.getGL2().glVertex3d(x, y, z); - } - - private static final void glNormal3d(GL gl, double x, double y, double z) { - gl.getGL2().glNormal3d(x, y, z); - } - - private static final void glTexCoord2d(GL gl, double x, double y) { - gl.getGL2().glTexCoord2d(x, y); - } - - /** - * Call glNormal3f after scaling normal to unit length. - * - * @param x - * @param y - * @param z - */ - private static final void normal3d(GL gl, double x, double y, double z) { - double mag; - - mag = Math.sqrt(x * x + y * y + z * z); - if (mag > 0.00001F) { - x /= mag; - y /= mag; - z /= mag; - } - glNormal3d(gl, x, y, z); - } - - private static final void TXTR_COORD(GL gl, double x, double y) { - if (textureFlag) - glTexCoord2d(gl, x, y); - } - - private static final double sin(double r) { - return Math.sin(r); - } - - private static final double cos(double r) { - return Math.cos(r); - } -} diff --git a/core/src/net/sf/openrocket/gui/figure3d/Quick3dMain.java b/core/src/net/sf/openrocket/gui/figure3d/Quick3dMain.java deleted file mode 100644 index d7c2e842..00000000 --- a/core/src/net/sf/openrocket/gui/figure3d/Quick3dMain.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.sf.openrocket.gui.figure3d; -import java.awt.BorderLayout; - -import javax.swing.JFrame; -import javax.swing.JPanel; - -import net.sf.openrocket.database.ComponentPresetDatabase; -import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.DatabaseMotorFinder; -import net.sf.openrocket.file.openrocket.importt.OpenRocketLoader; -import net.sf.openrocket.gui.main.componenttree.ComponentTree; -import net.sf.openrocket.gui.scalefigure.RocketPanel; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.startup.Application; - -/** - * An application for quickly testing 3d figure witout all the OpenRocket user interface - * - * @author bkuker - * - */ -public class Quick3dMain { - - /** - * @param args - */ - public static void main(String[] args) throws Exception { - Application.setBaseTranslator(new ResourceBundleTranslator( - "l10n.messages")); - Application.setMotorSetDatabase(new ThrustCurveMotorSetDatabase(false) { - { - startLoading(); - } - - @Override - protected void loadMotors() { - } - }); - Application.setPreferences(new SwingPreferences()); - - // Must be done after localization is initialized - ComponentPresetDatabase componentPresetDao = new ComponentPresetDatabase() { - - @Override - protected void load() { - // This test app doesn't need any presets loaded - just an empty database. - } - - }; - Application.setComponentPresetDao( componentPresetDao ); - - OpenRocketDocument doc = new OpenRocketLoader().loadFromStream( - Quick3dMain.class.getResourceAsStream("/datafiles/examples/Clustered rocket design.ork"), - new DatabaseMotorFinder()); - - JFrame ff = new JFrame(); - ff.setSize(1200, 400); - ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - RocketPanel panel; - - panel = new RocketPanel(doc); - - ComponentTree ct = new ComponentTree(doc); - panel.setSelectionModel(ct.getSelectionModel()); - - JPanel p = new JPanel(); - p.setLayout(new BorderLayout()); - p.add(ct, BorderLayout.WEST); - p.add(panel, BorderLayout.CENTER); - ff.setContentPane(p); - ff.setVisible(true); - } -} diff --git a/core/src/net/sf/openrocket/gui/figure3d/RocketFigure3d.java b/core/src/net/sf/openrocket/gui/figure3d/RocketFigure3d.java deleted file mode 100644 index 8df1e850..00000000 --- a/core/src/net/sf/openrocket/gui/figure3d/RocketFigure3d.java +++ /dev/null @@ -1,628 +0,0 @@ -package net.sf.openrocket.gui.figure3d; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.SplashScreen; -import java.awt.event.MouseEvent; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import javax.media.opengl.GL; -import javax.media.opengl.GL2; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLCapabilities; -import javax.media.opengl.GLEventListener; -import javax.media.opengl.GLProfile; -import javax.media.opengl.awt.GLCanvas; -import javax.media.opengl.fixedfunc.GLLightingFunc; -import javax.media.opengl.fixedfunc.GLMatrixFunc; -import javax.media.opengl.glu.GLU; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import javax.swing.event.MouseInputAdapter; - -import net.sf.openrocket.gui.figureelements.CGCaret; -import net.sf.openrocket.gui.figureelements.CPCaret; -import net.sf.openrocket.gui.figureelements.FigureElement; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -import com.jogamp.opengl.util.awt.Overlay; - -/* - * @author Bill Kuker - */ -public class RocketFigure3d extends JPanel implements GLEventListener { - private static final long serialVersionUID = 1L; - private static final LogHelper log = Application.getLogger(); - - static { - //this allows the GL canvas and things like the motor selection - //drop down to z-order themselves. - JPopupMenu.setDefaultLightWeightPopupEnabled(false); - } - - private static final double fovY = 15.0; - private static double fovX = Double.NaN; - private static final int CARET_SIZE = 20; - - private Configuration configuration; - private GLCanvas canvas; - - - - private Overlay extrasOverlay, caretOverlay; - private BufferedImage cgCaretRaster, cpCaretRaster; - private volatile boolean redrawExtras = true; - - private final ArrayList relativeExtra = new ArrayList(); - private final ArrayList absoluteExtra = new ArrayList(); - - private double roll = 0; - private double yaw = 0; - - Point pickPoint = null; - MouseEvent pickEvent; - - float[] lightPosition = new float[] { 1, 4, 1, 0 }; - - RocketRenderer rr = new RocketRenderer(); - - public RocketFigure3d(Configuration config) { - this.configuration = config; - this.setLayout(new BorderLayout()); - - //Only initizlize GL if 3d is enabled. - if ( is3dEnabled() ){ - //Fixes a linux / X bug: Splash must be closed before GL Init - SplashScreen splash = SplashScreen.getSplashScreen(); - if ( splash != null ) - splash.close(); - - initGLCanvas(); - } - } - - /** - * Return true if 3d view is enabled. This may be toggled by the user at - * launch time. - * @return - */ - public static boolean is3dEnabled(){ - return System.getProperty("openrocket.3d.disable") == null; - } - - private void initGLCanvas(){ - log.debug("Initializing RocketFigure3D OpenGL Canvas"); - try { - log.debug("Setting up GL capabilities..."); - - log.verbose("GL - Getting Default Profile"); - GLProfile glp = GLProfile.getDefault(); - - log.verbose("GL - creating GLCapabilities"); - GLCapabilities caps = new GLCapabilities(glp); - - log.verbose("GL - setSampleBuffers"); - caps.setSampleBuffers(true); - - log.verbose("GL - setNumSamples"); - caps.setNumSamples(6); - - log.verbose("GL - setStencilBits"); - caps.setStencilBits(1); - - log.verbose("GL - Creating Canvas"); - canvas = new GLCanvas(caps); - - log.verbose("GL - Registering as GLEventListener on canvas"); - canvas.addGLEventListener(this); - - log.verbose("GL - Adding canvas to this JPanel"); - this.add(canvas, BorderLayout.CENTER); - - log.verbose("GL - Setting up mouse listeners"); - setupMouseListeners(); - - log.verbose("GL - Rasterizine Carets"); //reticulating splines? - rasterizeCarets(); - - } catch (Throwable t) { - log.error("An error occurred creating 3d View", t); - canvas = null; - this.add(new JLabel("Unable to load 3d Libraries: " - + t.getMessage())); - } - } - - /** - * Set up the standard rendering hints on the Graphics2D - */ - private static void setRenderingHints(Graphics2D g){ - g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - g.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - } - - /** - * Rasterize the carets into 2 buffered images that I can blit onto the - * 3d display every redraw without all of the caret shape rendering overhead - */ - private void rasterizeCarets(){ - Graphics2D g2d; - - //Rasterize a CG Caret - cgCaretRaster = new BufferedImage(CARET_SIZE, CARET_SIZE, BufferedImage.TYPE_4BYTE_ABGR); - g2d = cgCaretRaster.createGraphics(); - setRenderingHints(g2d); - - g2d.setBackground(new Color(0, 0, 0, 0)); - g2d.clearRect(0, 0, CARET_SIZE, CARET_SIZE); - - new CGCaret(CARET_SIZE/2,CARET_SIZE/2).paint(g2d, 1.0); - - g2d.dispose(); - - //Rasterize a CP Caret - cpCaretRaster = new BufferedImage(CARET_SIZE, CARET_SIZE, BufferedImage.TYPE_4BYTE_ABGR); - g2d = cpCaretRaster.createGraphics(); - setRenderingHints(g2d); - - g2d.setBackground(new Color(0, 0, 0, 0)); - g2d.clearRect(0, 0, CARET_SIZE, CARET_SIZE); - - new CPCaret(CARET_SIZE/2,CARET_SIZE/2).paint(g2d, 1.0); - - g2d.dispose(); - - } - - private void setupMouseListeners() { - MouseInputAdapter a = new MouseInputAdapter() { - int lastX; - int lastY; - MouseEvent pressEvent; - - @Override - public void mousePressed(MouseEvent e) { - lastX = e.getX(); - lastY = e.getY(); - pressEvent = e; - } - - @Override - public void mouseClicked(MouseEvent e) { - pickPoint = new Point(lastX, canvas.getHeight() - lastY); - pickEvent = e; - internalRepaint(); - } - - @Override - public void mouseDragged(MouseEvent e) { - int dx = lastX - e.getX(); - int dy = lastY - e.getY(); - lastX = e.getX(); - lastY = e.getY(); - - if (pressEvent.getButton() == MouseEvent.BUTTON1) { - if (Math.abs(dx) > Math.abs(dy)) { - setYaw(yaw - (float) dx / 100.0); - } else { - if ( yaw > Math.PI/2.0 && yaw < 3.0*Math.PI/2.0 ){ - dy = -dy; - } - setRoll(roll - (float) dy / 100.0); - } - } else { - lightPosition[0] -= 0.1f * dx; - lightPosition[1] += 0.1f * dy; - internalRepaint(); - } - } - }; - canvas.addMouseMotionListener(a); - canvas.addMouseListener(a); - } - - public void setConfiguration(Configuration configuration) { - this.configuration = configuration; - updateFigure(); - } - - @Override - public void display(GLAutoDrawable drawable) { - GL2 gl = drawable.getGL().getGL2(); - GLU glu = new GLU(); - - gl.glEnable(GL.GL_MULTISAMPLE); - - gl.glClearColor(1, 1, 1, 1); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - - setupView(gl, glu); - - if (pickPoint != null) { - gl.glDisable(GLLightingFunc.GL_LIGHTING); - final RocketComponent picked = rr.pick(drawable, configuration, - pickPoint, pickEvent.isShiftDown()?selection:null ); - if (csl != null && picked != null) { - final MouseEvent e = pickEvent; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - csl.componentClicked(new RocketComponent[] { picked }, - e); - } - }); - - } - pickPoint = null; - - gl.glClearColor(1, 1, 1, 1); - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); - - gl.glEnable(GLLightingFunc.GL_LIGHTING); - } - rr.render(drawable, configuration, selection); - - drawExtras(gl, glu); - drawCarets(gl, glu); - } - - - private void drawCarets(GL2 gl, GLU glu) { - final Graphics2D og2d = caretOverlay.createGraphics(); - setRenderingHints(og2d); - - og2d.setBackground(new Color(0, 0, 0, 0)); - og2d.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); - caretOverlay.markDirty(0, 0, canvas.getWidth(), canvas.getHeight()); - - // The existing relative Extras don't really work right for 3d. - Coordinate pCP = project(cp, gl, glu); - Coordinate pCG = project(cg, gl, glu); - - final int d = CARET_SIZE/2; - - //z order the carets - if (pCG.z < pCP.z) { - //Subtract half of the caret size, so they are centered ( The +/- d in each translate) - //Flip the sense of the Y coordinate from GL to normal (Y+ up/down) - og2d.drawRenderedImage( - cpCaretRaster, - AffineTransform.getTranslateInstance((pCP.x - d), - canvas.getHeight() - (pCP.y + d))); - og2d.drawRenderedImage( - cgCaretRaster, - AffineTransform.getTranslateInstance((pCG.x - d), - canvas.getHeight() - (pCG.y + d))); - } else { - og2d.drawRenderedImage( - cgCaretRaster, - AffineTransform.getTranslateInstance((pCG.x - d), - canvas.getHeight() - (pCG.y + d))); - og2d.drawRenderedImage( - cpCaretRaster, - AffineTransform.getTranslateInstance((pCP.x - d), - canvas.getHeight() - (pCP.y + d))); - } - og2d.dispose(); - - gl.glEnable(GL.GL_BLEND); - caretOverlay.drawAll(); - gl.glDisable(GL.GL_BLEND); - } - - /** - * Draw the extras overlay to the gl canvas. - * Re-blits the overlay every frame. Only re-renders the overlay - * when needed. - */ - private void drawExtras(GL2 gl, GLU glu){ - //Only re-render if needed - // redrawExtras: Some external change (new simulation data) means - // the data is out of date. - // extrasOverlay.contentsLost(): For some reason the buffer with this - // data is lost. - if ( redrawExtras || extrasOverlay.contentsLost() ){ - log.debug("Redrawing Overlay"); - - final Graphics2D og2d = extrasOverlay.createGraphics(); - setRenderingHints(og2d); - - og2d.setBackground(new Color(0, 0, 0, 0)); - og2d.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); - extrasOverlay.markDirty(0, 0, canvas.getWidth(), canvas.getHeight()); - - for (FigureElement e : relativeExtra) { - e.paint(og2d, 1); - } - Rectangle rect = this.getVisibleRect(); - - for (FigureElement e : absoluteExtra) { - e.paint(og2d, 1.0, rect); - } - og2d.dispose(); - - redrawExtras = false; - } - - //Re-blit to gl canvas every time - gl.glEnable(GL.GL_BLEND); - extrasOverlay.drawAll(); - gl.glDisable(GL.GL_BLEND); - } - - @Override - public void dispose(GLAutoDrawable drawable) { - log.verbose("GL - dispose() called"); - } - - @Override - public void init(GLAutoDrawable drawable) { - log.verbose("GL - init() called"); - rr.init(drawable); - - GL2 gl = drawable.getGL().getGL2(); - gl.glClearDepth(1.0f); // clear z-buffer to the farthest - - gl.glDepthFunc(GL.GL_LEQUAL); // the type of depth test to do - - float amb = 0.5f; - float dif = 1.0f; - gl.glLightfv(GLLightingFunc.GL_LIGHT1, GLLightingFunc.GL_AMBIENT, - new float[] { amb, amb, amb, 1 }, 0); - gl.glLightfv(GLLightingFunc.GL_LIGHT1, GLLightingFunc.GL_DIFFUSE, - new float[] { dif, dif, dif, 1 }, 0); - gl.glLightfv(GLLightingFunc.GL_LIGHT1, GLLightingFunc.GL_SPECULAR, - new float[] { dif, dif, dif, 1 }, 0); - - gl.glEnable(GLLightingFunc.GL_LIGHT1); - gl.glEnable(GLLightingFunc.GL_LIGHTING); - gl.glShadeModel(GLLightingFunc.GL_SMOOTH); - - gl.glEnable(GLLightingFunc.GL_NORMALIZE); - - extrasOverlay = new Overlay(drawable); - caretOverlay = new Overlay(drawable); - - log.verbose("GL - init() complete"); - } - - @Override - public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { - log.verbose("GL - reshape() called"); - GL2 gl = drawable.getGL().getGL2(); - GLU glu = new GLU(); - - double ratio = (double) w / (double) h; - fovX = fovY * ratio; - - gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); - gl.glLoadIdentity(); - glu.gluPerspective(fovY, ratio, 0.05f, 100f); - gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); - - redrawExtras = true; - log.verbose("GL - reshape() complete"); - } - - @SuppressWarnings("unused") - private static class Bounds { - double xMin, xMax, xSize; - double yMin, yMax, ySize; - double zMin, zMax, zSize; - double rMax; - } - - /** - * Calculates the bounds for the current configuration - * - * @return - */ - private Bounds calculateBounds() { - Bounds ret = new Bounds(); - Collection bounds = configuration.getBounds(); - for (Coordinate c : bounds) { - ret.xMax = Math.max(ret.xMax, c.x); - ret.xMin = Math.min(ret.xMin, c.x); - - ret.yMax = Math.max(ret.yMax, c.y); - ret.yMin = Math.min(ret.yMin, c.y); - - ret.zMax = Math.max(ret.zMax, c.z); - ret.zMin = Math.min(ret.zMin, c.z); - - double r = MathUtil.hypot(c.y, c.z); - ret.rMax = Math.max(ret.rMax, r); - } - ret.xSize = ret.xMax - ret.xMin; - ret.ySize = ret.yMax - ret.yMin; - ret.zSize = ret.zMax - ret.zMin; - return ret; - } - - private void setupView(GL2 gl, GLU glu) { - log.verbose("GL - setupView() called"); - gl.glLoadIdentity(); - - gl.glLightfv(GLLightingFunc.GL_LIGHT1, GLLightingFunc.GL_POSITION, - lightPosition, 0); - - // Get the bounds - Bounds b = calculateBounds(); - - // Calculate the distance needed to fit the bounds in both the X and Y - // direction - // Add 10% for space around it. - double dX = (b.xSize * 1.2 / 2.0) - / Math.tan(Math.toRadians(fovX / 2.0)); - double dY = (b.rMax * 2.0 * 1.2 / 2.0) - / Math.tan(Math.toRadians(fovY / 2.0)); - - // Move back the greater of the 2 distances - glu.gluLookAt(0, 0, Math.max(dX, dY), 0, 0, 0, 0, 1, 0); - - gl.glRotated(yaw * (180.0 / Math.PI), 0, 1, 0); - gl.glRotated(roll * (180.0 / Math.PI), 1, 0, 0); - - // Center the rocket in the view. - gl.glTranslated(-b.xMin - b.xSize / 2.0, 0, 0); - - //Change to LEFT Handed coordinates - gl.glScaled(1, 1, -1); - gl.glFrontFace(GL.GL_CW); - - //Flip textures for LEFT handed coords - gl.glMatrixMode(GL.GL_TEXTURE); - gl.glLoadIdentity(); - gl.glScaled(-1,1,1); - gl.glTranslated(-1,0,0); - gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); - - log.verbose("GL - setupView() complete"); - } - - /** - * Call when the rocket has changed - */ - public void updateFigure() { - log.debug("3D Figure Updated"); - rr.updateFigure(); - internalRepaint(); - } - - private void internalRepaint(){ - log.verbose("GL - internalRepaint() called"); - super.repaint(); - if (canvas != null) - canvas.display(); - log.verbose("GL - internalRepaint() complete"); - } - - @Override - public void repaint() { - log.verbose("GL - repaint() called"); - redrawExtras = true; - internalRepaint(); - log.verbose("GL - repaint() complete"); - } - - private Set selection = new HashSet(); - - public void setSelection(RocketComponent[] selection) { - this.selection.clear(); - if (selection != null) { - for (RocketComponent c : selection) - this.selection.add(c); - } - internalRepaint(); - } - - private void setRoll(double rot) { - if (MathUtil.equals(roll, rot)) - return; - this.roll = MathUtil.reduce360(rot); - internalRepaint(); - } - - private void setYaw(double rot) { - if (MathUtil.equals(yaw, rot)) - return; - this.yaw = MathUtil.reduce360(rot); - internalRepaint(); - } - - // ///////////// Extra methods - - private Coordinate project(Coordinate c, GL2 gl, GLU glu) { - log.verbose("GL - project() called"); - double[] mvmatrix = new double[16]; - double[] projmatrix = new double[16]; - int[] viewport = new int[4]; - - gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0); - gl.glGetDoublev(GLMatrixFunc.GL_MODELVIEW_MATRIX, mvmatrix, 0); - gl.glGetDoublev(GLMatrixFunc.GL_PROJECTION_MATRIX, projmatrix, 0); - - double out[] = new double[4]; - glu.gluProject(c.x, c.y, c.z, mvmatrix, 0, projmatrix, 0, viewport, 0, - out, 0); - - log.verbose("GL - peoject() complete"); - return new Coordinate(out[0], out[1], out[2]); - - } - - private Coordinate cp = new Coordinate(0, 0, 0); - private Coordinate cg = new Coordinate(0, 0, 0); - - public void setCG(Coordinate cg) { - this.cg = cg; - redrawExtras = true; - } - - public void setCP(Coordinate cp) { - this.cp = cp; - redrawExtras = true; - } - - public void addRelativeExtra(FigureElement p) { - relativeExtra.add(p); - redrawExtras = true; - } - - public void removeRelativeExtra(FigureElement p) { - relativeExtra.remove(p); - redrawExtras = true; - } - - public void clearRelativeExtra() { - relativeExtra.clear(); - redrawExtras = true; - } - - public void addAbsoluteExtra(FigureElement p) { - absoluteExtra.add(p); - redrawExtras = true; - } - - public void removeAbsoluteExtra(FigureElement p) { - absoluteExtra.remove(p); - redrawExtras = true; - } - - public void clearAbsoluteExtra() { - absoluteExtra.clear(); - redrawExtras = true; - } - - private ComponentSelectionListener csl; - - public static interface ComponentSelectionListener { - public void componentClicked(RocketComponent[] components, MouseEvent e); - } - - public void addComponentSelectionListener( - ComponentSelectionListener newListener) { - this.csl = newListener; - } - -} diff --git a/core/src/net/sf/openrocket/gui/figure3d/RocketRenderer.java b/core/src/net/sf/openrocket/gui/figure3d/RocketRenderer.java deleted file mode 100644 index 49341020..00000000 --- a/core/src/net/sf/openrocket/gui/figure3d/RocketRenderer.java +++ /dev/null @@ -1,303 +0,0 @@ -package net.sf.openrocket.gui.figure3d; - -import java.awt.Point; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Set; -import java.util.Vector; - -import javax.media.opengl.GL; -import javax.media.opengl.GL2; -import javax.media.opengl.GL2ES1; -import javax.media.opengl.GL2GL3; -import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.fixedfunc.GLLightingFunc; - -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Color; -import net.sf.openrocket.util.Coordinate; - -/* - * @author Bill Kuker - */ -public class RocketRenderer { - ComponentRenderer cr; - - private final float[] selectedEmissive = { 1, 0, 0, 1 }; - private final float[] colorBlack = { 0, 0, 0, 1 }; - private final float[] color = new float[4]; - - public void init(GLAutoDrawable drawable) { - cr = new ComponentRenderer(); - cr.init(drawable); - } - - public void updateFigure() { - cr.updateFigure(); - } - - private boolean isDrawn(RocketComponent c) { - return true; - } - - private boolean isDrawnTransparent(RocketComponent c) { - if (c instanceof BodyTube) - return true; - if (c instanceof NoseCone) - return false; - if (c instanceof SymmetricComponent) { - if (((SymmetricComponent) c).isFilled()) - return false; - } - if (c instanceof Transition) { - Transition t = (Transition) c; - return !t.isAftShoulderCapped() && !t.isForeShoulderCapped(); - } - return false; - } - - public RocketComponent pick(GLAutoDrawable drawable, - Configuration configuration, Point p, Set ignore) { - final GL2 gl = drawable.getGL().getGL2(); - gl.glEnable(GL.GL_DEPTH_TEST); - - //Store a vector of pickable parts. - final Vector pickParts = new Vector(); - - for (RocketComponent c : configuration) { - if ( ignore != null && ignore.contains(c) ) - continue; - - //Encode the index of the part as a color - //if index is 0x0ABC the color ends up as - //0xA0B0C000 with each nibble in the coresponding - //high bits of the RG and B channels. - gl.glColor4ub((byte) ((pickParts.size() >> 4) & 0xF0), - (byte) ((pickParts.size() << 0) & 0xF0), - (byte) ((pickParts.size() << 4) & 0xF0), (byte) 1); - pickParts.add(c); - - if (isDrawnTransparent(c)) { - gl.glEnable(GL.GL_CULL_FACE); - gl.glCullFace(GL.GL_FRONT); - cr.renderGeometry(gl, c); - gl.glDisable(GL.GL_CULL_FACE); - } else { - cr.renderGeometry(gl, c); - } - } - - ByteBuffer bb = ByteBuffer.allocateDirect(4); - - gl.glReadPixels(p.x, p.y, 1, 1, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, bb); - - final int pickColor = bb.getInt(); - final int pickIndex = ((pickColor >> 20) & 0xF00) | ((pickColor >> 16) & 0x0F0) - | ((pickColor >> 12) & 0x00F); - - if ( pickIndex < 0 || pickIndex > pickParts.size() - 1 ) - return null; - - return pickParts.get(pickIndex); - } - - public void render(GLAutoDrawable drawable, Configuration configuration, - Set selection) { - if (cr == null) - throw new IllegalStateException(this + " Not Initialized"); - - GL2 gl = drawable.getGL().getGL2(); - - gl.glEnable(GL.GL_DEPTH_TEST); // enables depth testing - gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); - - // Draw all inner components - for (RocketComponent c : configuration) { - if (isDrawn(c)) { - if (!isDrawnTransparent(c)) { - renderComponent(gl, c, 1.0f); - } - } - } - - renderMotors(gl, configuration); - - // Draw Tube and Transition back faces, blended with depth test - // so that they show up behind. - gl.glEnable(GL.GL_CULL_FACE); - gl.glCullFace(GL.GL_FRONT); - for (RocketComponent c : configuration) { - if (isDrawn(c)) { - if (isDrawnTransparent(c)) { - renderComponent(gl, c, 1.0f); - } - } - } - gl.glDisable(GL.GL_CULL_FACE); - - // Draw T&T front faces blended, without depth test - gl.glEnable(GL.GL_BLEND); - gl.glEnable(GL.GL_CULL_FACE); - gl.glCullFace(GL.GL_BACK); - for (RocketComponent c : configuration) { - if (isDrawn(c)) { - if (isDrawnTransparent(c)) { - renderComponent(gl, c, 0.2f); - } - } - } - gl.glDisable(GL.GL_BLEND); - gl.glDisable(GL.GL_CULL_FACE); - - gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_EMISSION, - selectedEmissive, 0); - gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_DIFFUSE, colorBlack, 0); - gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_AMBIENT, colorBlack, 0); - gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_SPECULAR, colorBlack, 0); - - gl.glDepthMask(false); - gl.glDisable(GL.GL_DEPTH_TEST); - gl.glEnable(GL.GL_STENCIL_TEST); - - for (RocketComponent c : configuration) { - if (selection.contains(c)) { - // So it is faster to do this once before the loop, - // but then the outlines are not as good if you multi-select. - // Not sure which to do. - - gl.glStencilMask(1); - gl.glDisable(GL.GL_SCISSOR_TEST); - gl.glClearStencil(0); - gl.glClear(GL.GL_STENCIL_BUFFER_BIT); - gl.glStencilMask(0); - - gl.glStencilFunc(GL.GL_ALWAYS, 1, 1); - gl.glStencilMask(1); - gl.glColorMask(false, false, false, false); - gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2GL3.GL_FILL); - gl.glStencilOp(GL.GL_KEEP, GL.GL_KEEP, GL.GL_REPLACE); - cr.renderGeometry(gl, c); - gl.glStencilMask(0); - - gl.glColorMask(true, true, true, true); - gl.glStencilFunc(GL.GL_NOTEQUAL, 1, 1); - gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2GL3.GL_LINE); - gl.glLineWidth(5.0f); - cr.renderGeometry(gl, c); - } - } - gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2GL3.GL_FILL); - gl.glDepthMask(true); - gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GLLightingFunc.GL_EMISSION, - colorBlack, 0); - gl.glDisable(GL.GL_STENCIL_TEST); - gl.glEnable(GL.GL_DEPTH_TEST); - } - - private void renderMotors(GL2 gl, Configuration configuration) { - String motorID = configuration.getMotorConfigurationID(); - Iterator iterator = configuration.motorIterator(); - while (iterator.hasNext()) { - MotorMount mount = iterator.next(); - Motor motor = mount.getMotor(motorID); - double length = motor.getLength(); - double radius = motor.getDiameter() / 2; - - Coordinate[] position = ((RocketComponent) mount) - .toAbsolute(new Coordinate(((RocketComponent) mount) - .getLength() + mount.getMotorOverhang() - length)); - - for (int i = 0; i < position.length; i++) { - cr.renderMotor(gl, position[i], length, radius); - } - } - - } - - - public void renderComponent(GL2 gl, RocketComponent c, float alpha) { - gl.glLightModeli(GL2ES1.GL_LIGHT_MODEL_TWO_SIDE, 1); - - getOutsideColor(c, alpha, color); - gl.glMaterialfv(GL.GL_FRONT, GLLightingFunc.GL_DIFFUSE, color, 0); - gl.glMaterialfv(GL.GL_FRONT, GLLightingFunc.GL_AMBIENT, color, 0); - - getSpecularColor(c, alpha, color); - gl.glMaterialfv(GL.GL_FRONT, GLLightingFunc.GL_SPECULAR, color, 0); - gl.glMateriali(GL.GL_FRONT, GLLightingFunc.GL_SHININESS, - getShininess(c)); - - getInsideColor(c, alpha, color); - gl.glMaterialfv(GL.GL_BACK, GLLightingFunc.GL_DIFFUSE, color, 0); - gl.glMaterialfv(GL.GL_BACK, GLLightingFunc.GL_AMBIENT, color, 0); - - cr.renderGeometry(gl, c); - } - - private int getShininess(RocketComponent c) { - if (c instanceof ExternalComponent) { - switch (((ExternalComponent) c).getFinish()) { - case ROUGH: - return 10; - case UNFINISHED: - return 30; - case NORMAL: - return 40; - case SMOOTH: - return 80; - case POLISHED: - return 128; - } - return 100; - } else { - return 20; - } - } - - private void getSpecularColor(RocketComponent c, float alpha, float[] out) { - int shine = getShininess(c); - float m = (float) shine / 128.0f; - float d = 0.9f; - getOutsideColor(c, alpha, out); - out[0] = Math.max(out[0], d) * m; - out[1] = Math.max(out[1], d) * m; - out[2] = Math.max(out[2], d) * m; - } - - private void getInsideColor(RocketComponent c, float alpha, float[] out) { - float d = 0.4f; - getOutsideColor(c, alpha, out); - out[0] *= d; - out[1] *= d; - out[2] *= d; - } - - private HashMap, Color> defaultColorCache = new HashMap, Color>(); - private void getOutsideColor(RocketComponent c, float alpha, float[] out) { - Color col; - col = c.getColor(); - if (col == null){ - if ( defaultColorCache.containsKey(c.getClass()) ){ - col = defaultColorCache.get(c.getClass()); - } else { - col = Application.getPreferences().getDefaultColor(c.getClass()); - defaultColorCache.put(c.getClass(), col); - } - } - - out[0] = Math.max(0.2f, (float) col.getRed() / 255f); - out[1] = Math.max(0.2f, (float) col.getGreen() / 255f); - out[2] = Math.max(0.2f, (float) col.getBlue() / 255f); - out[3] = alpha; - } -} diff --git a/core/src/net/sf/openrocket/gui/figure3d/TransitionRenderer.java b/core/src/net/sf/openrocket/gui/figure3d/TransitionRenderer.java deleted file mode 100644 index 3789a780..00000000 --- a/core/src/net/sf/openrocket/gui/figure3d/TransitionRenderer.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - ** License Applicability. Except to the extent portions of this file are - ** made subject to an alternative license as permitted in the SGI Free - ** Software License B, Version 2.0 (the "License"), the contents of this - ** file are subject only to the provisions of the License. You may not use - ** this file except in compliance with the License. You may obtain a copy - ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 - ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: - ** - ** http://oss.sgi.com/projects/FreeB - ** - ** Note that, as provided in the License, the Software is distributed on an - ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS - ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND - ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A - ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - ** - ** NOTE: The Original Code (as defined below) has been licensed to Sun - ** Microsystems, Inc. ("Sun") under the SGI Free Software License B - ** (Version 1.1), shown above ("SGI License"). Pursuant to Section - ** 3.2(3) of the SGI License, Sun is distributing the Covered Code to - ** you under an alternative license ("Alternative License"). This - ** Alternative License includes all of the provisions of the SGI License - ** except that Section 2.2 and 11 are omitted. Any differences between - ** the Alternative License and the SGI License are offered solely by Sun - ** and not by SGI. - ** - ** Original Code. The Original Code is: OpenGL Sample Implementation, - ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, - ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. - ** Copyright in any portions created by third parties is as indicated - ** elsewhere herein. All Rights Reserved. - ** - ** Additional Notice Provisions: The application programming interfaces - ** established by SGI in conjunction with the Original Code are The - ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released - ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version - ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X - ** Window System(R) (Version 1.3), released October 19, 1998. This software - ** was created using the OpenGL(R) version 1.2.1 Sample Implementation - ** published by SGI, but has not been independently verified as being - ** compliant with the OpenGL(R) version 1.2.1 Specification. - ** - ** $Date: 2009-03-04 17:23:34 -0800 (Wed, 04 Mar 2009) $ $Revision: 1856 $ - ** $Header$ - */ - -/* - * Copyright (c) 2002-2004 LWJGL Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of 'LWJGL' nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any kind. ALL - * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, - * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN - * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR - * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR - * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR - * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE - * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, - * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF - * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for use - * in the design, construction, operation or maintenance of any nuclear - * facility. - */ -package net.sf.openrocket.gui.figure3d; - -import javax.media.opengl.GL; -import javax.media.opengl.GL2; - -import net.sf.openrocket.rocketcomponent.Transition; - -public final class TransitionRenderer { - private static final boolean textureFlag = true; - - private TransitionRenderer() { - } - - public static final void drawTransition(final GL2 gl, final Transition tr, - final int slices, final int stacks) { - - double da, r, dz; - double x, y, z, nz, nsign; - int i, j; - - nsign = 1.0f; - - da = 2.0f * PI / slices; - dz = (double) tr.getLength() / stacks; - - double ds = 1.0f / slices; - double dt = 1.0f / stacks; - double t = 0.0f; - z = 0.0f; - r = (double) tr.getForeRadius(); - for (j = 0; j < stacks; j++) { - r = (double) tr.getRadius(z); - double rNext = (double) tr.getRadius(z + dz); - - if (j == stacks - 1) - rNext = (double) tr.getRadius(tr.getLength()); - - // Z component of normal vectors - nz = -(rNext - r) / dz; - - double s = 0.0f; - glBegin(gl, GL2.GL_QUAD_STRIP); - for (i = 0; i <= slices; i++) { - if (i == slices) { - x = sin(0.0f); - y = cos(0.0f); - } else { - x = sin((i * da)); - y = cos((i * da)); - } - if (nsign == 1.0f) { - normal3d(gl, (x * nsign), (y * nsign), (nz * nsign)); - TXTR_COORD(gl, s, t); - glVertex3d(gl, (x * r), (y * r), z); - normal3d(gl, (x * nsign), (y * nsign), (nz * nsign)); - TXTR_COORD(gl, s, t + dt); - glVertex3d(gl, (x * rNext), (y * rNext), (z + dz)); - } else { - normal3d(gl, x * nsign, y * nsign, nz * nsign); - TXTR_COORD(gl, s, t); - glVertex3d(gl, (x * r), (y * r), z); - normal3d(gl, x * nsign, y * nsign, nz * nsign); - TXTR_COORD(gl, s, t + dt); - glVertex3d(gl, (x * rNext), (y * rNext), (z + dz)); - } - s += ds; - } // for slices - glEnd(gl); - // r += dr; - t += dt; - z += dz; - } // for stacks - - } - - // ---------------------------------------------------------------------- - // Internals only below this point - // - - private static final double PI = (double) Math.PI; - - private static final void glBegin(GL gl, int mode) { - gl.getGL2().glBegin(mode); - } - - private static final void glEnd(GL gl) { - gl.getGL2().glEnd(); - } - - private static final void glVertex3d(GL gl, double x, double y, double z) { - gl.getGL2().glVertex3d(x, y, z); - } - - private static final void glNormal3d(GL gl, double x, double y, double z) { - gl.getGL2().glNormal3d(x, y, z); - } - - private static final void glTexCoord2d(GL gl, double x, double y) { - gl.getGL2().glTexCoord2d(x, y); - } - - /** - * Call glNormal3f after scaling normal to unit length. - * - * @param x - * @param y - * @param z - */ - private static final void normal3d(GL gl, double x, double y, double z) { - double mag; - - mag = (double) Math.sqrt(x * x + y * y + z * z); - if (mag > 0.00001F) { - x /= mag; - y /= mag; - z /= mag; - } - glNormal3d(gl, x, y, z); - } - - private static final void TXTR_COORD(GL gl, double x, double y) { - if (textureFlag) - glTexCoord2d(gl, x, y); - } - - private static final double sin(double r) { - return (double) Math.sin(r); - } - - private static final double cos(double r) { - return (double) Math.cos(r); - } -} diff --git a/core/src/net/sf/openrocket/gui/figureelements/CGCaret.java b/core/src/net/sf/openrocket/gui/figureelements/CGCaret.java deleted file mode 100644 index 14a8a677..00000000 --- a/core/src/net/sf/openrocket/gui/figureelements/CGCaret.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.sf.openrocket.gui.figureelements; - -import java.awt.Color; -import java.awt.geom.Area; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Rectangle2D; - -/** - * A mark indicating the position of the center of gravity. It is a blue circle with every - * second quarter filled with blue. - * - * @author Sampo Niskanen - */ - -public class CGCaret extends Caret { - private static final float RADIUS = 7; - - private static Area caret = null; - - /** - * Create a new CGCaret at the specified coordinates. - */ - public CGCaret(double x, double y) { - super(x,y); - } - - /** - * Returns the Area corresponding to the caret. The Area object is created only once, - * after which the object is cloned for new copies. - */ - @Override - protected Area getCaret() { - if (caret != null) { - return (Area)caret.clone(); - } - - Ellipse2D.Float e = new Ellipse2D.Float(-RADIUS,-RADIUS,2*RADIUS,2*RADIUS); - caret = new Area(e); - - Area a; - a = new Area(new Rectangle2D.Float(-RADIUS,-RADIUS,RADIUS,RADIUS)); - caret.subtract(a); - a = new Area(new Rectangle2D.Float(0,0,RADIUS,RADIUS)); - caret.subtract(a); - - a = new Area(new Ellipse2D.Float(-RADIUS,-RADIUS,2*RADIUS,2*RADIUS)); - a.subtract(new Area(new Ellipse2D.Float(-RADIUS*0.9f,-RADIUS*0.9f, - 2*0.9f*RADIUS,2*0.9f*RADIUS))); - caret.add(a); - - return (Area) caret.clone(); - } - - /** - * Return the color of the caret (blue). - */ - @Override - protected Color getColor() { - return Color.BLUE; - } - -} diff --git a/core/src/net/sf/openrocket/gui/figureelements/CPCaret.java b/core/src/net/sf/openrocket/gui/figureelements/CPCaret.java deleted file mode 100644 index 09e9cceb..00000000 --- a/core/src/net/sf/openrocket/gui/figureelements/CPCaret.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.gui.figureelements; - -import java.awt.Color; -import java.awt.geom.Area; -import java.awt.geom.Ellipse2D; - -/** - * A mark indicating the position of the center of pressure. It is a red filled circle - * inside a slightly larger red circle. - * - * @author Sampo Niskanen - */ - -public class CPCaret extends Caret { - private static final float RADIUS = 7; - - private static Area caret = null; - - /** - * Create a new CPCaret at the specified coordinates. - */ - public CPCaret(double x, double y) { - super(x,y); - } - - /** - * Returns the Area object of the caret. The Area object is created only once, - * after which new copies are cloned from it. - */ - @Override - protected Area getCaret() { - if (caret != null) { - return (Area)caret.clone(); - } - - Ellipse2D.Float e = new Ellipse2D.Float(-RADIUS,-RADIUS,2*RADIUS,2*RADIUS); - caret = new Area(e); - - caret.subtract(new Area(new Ellipse2D.Float(-RADIUS*0.9f,-RADIUS*0.9f, - 2*0.9f*RADIUS,2*0.9f*RADIUS))); - - caret.add(new Area(new Ellipse2D.Float(-RADIUS*0.75f,-RADIUS*0.75f, - 2*0.75f*RADIUS,2*0.75f*RADIUS))); - - return (Area) caret.clone(); - } - - - /** - * Return the color of the caret (red). - */ - @Override - protected Color getColor() { - return Color.RED; - } -} diff --git a/core/src/net/sf/openrocket/gui/figureelements/Caret.java b/core/src/net/sf/openrocket/gui/figureelements/Caret.java deleted file mode 100644 index b82731ff..00000000 --- a/core/src/net/sf/openrocket/gui/figureelements/Caret.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.sf.openrocket.gui.figureelements; - - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.AffineTransform; -import java.awt.geom.Area; - -public abstract class Caret implements FigureElement { - private double x,y; - - /** - * Creates a new caret at the specified coordinates. - */ - public Caret(double x, double y) { - this.x = x; - this.y = y; - } - - /** - * Sets the position of the caret to the new coordinates. - */ - public void setPosition(double x, double y) { - this.x = x; - this.y = y; - } - - /** - * Paints the caret to the Graphics2D element. - */ - public void paint(Graphics2D g2, double scale) { - Area caret = getCaret(); - AffineTransform t = new AffineTransform(1.0/scale, 0, 0, 1.0/scale, x, y); - caret.transform(t); - - g2.setColor(getColor()); - g2.fill(caret); - } - - - public void paint(Graphics2D g2, double scale, Rectangle visible) { - throw new UnsupportedOperationException("paint() with rectangle unsupported."); - } - - /** - * Return the Area object corresponding to the mark. - */ - protected abstract Area getCaret(); - - /** - * Return the color to be used when drawing the mark. - */ - protected abstract Color getColor(); -} diff --git a/core/src/net/sf/openrocket/gui/figureelements/FigureElement.java b/core/src/net/sf/openrocket/gui/figureelements/FigureElement.java deleted file mode 100644 index 953d1918..00000000 --- a/core/src/net/sf/openrocket/gui/figureelements/FigureElement.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.sf.openrocket.gui.figureelements; - -import java.awt.Graphics2D; -import java.awt.Rectangle; - -public interface FigureElement { - - public void paint(Graphics2D g2, double scale); - - public void paint(Graphics2D g2, double scale, Rectangle visible); - -} diff --git a/core/src/net/sf/openrocket/gui/figureelements/RocketInfo.java b/core/src/net/sf/openrocket/gui/figureelements/RocketInfo.java deleted file mode 100644 index 39fb32a5..00000000 --- a/core/src/net/sf/openrocket/gui/figureelements/RocketInfo.java +++ /dev/null @@ -1,439 +0,0 @@ -package net.sf.openrocket.gui.figureelements; - -import static net.sf.openrocket.util.Chars.ALPHA; -import static net.sf.openrocket.util.Chars.THETA; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.font.GlyphVector; -import java.awt.geom.Rectangle2D; - -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.MathUtil; - - -/** - * A FigureElement that draws text at different positions in the figure - * with general data about the rocket. - * - * @author Sampo Niskanen - */ -public class RocketInfo implements FigureElement { - - private static final Translator trans = Application.getTranslator(); - // Margin around the figure edges, pixels - private static final int MARGIN = 8; - - // Font to use - private static final Font FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 11); - private static final Font SMALLFONT = new Font(Font.SANS_SERIF, Font.PLAIN, 9); - - - private final Caret cpCaret = new CPCaret(0,0); - private final Caret cgCaret = new CGCaret(0,0); - - private final Configuration configuration; - private final UnitGroup stabilityUnits; - - private double cg = 0, cp = 0; - private double length = 0, diameter = 0; - private double mass = 0; - private double aoa = Double.NaN, theta = Double.NaN, mach = Application.getPreferences().getDefaultMach(); - - private WarningSet warnings = null; - - private boolean calculatingData = false; - private FlightData flightData = null; - - private Graphics2D g2 = null; - private float line = 0; - private float x1, x2, y1, y2; - - - - - - public RocketInfo(Configuration configuration) { - this.configuration = configuration; - this.stabilityUnits = UnitGroup.stabilityUnits(configuration); - } - - - @Override - public void paint(Graphics2D g2, double scale) { - throw new UnsupportedOperationException("paint() must be called with coordinates"); - } - - @Override - public void paint(Graphics2D g2, double scale, Rectangle visible) { - this.g2 = g2; - this.line = FONT.getLineMetrics("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", - g2.getFontRenderContext()).getHeight(); - - x1 = visible.x + MARGIN; - x2 = visible.x + visible.width - MARGIN; - y1 = visible.y + line ; - y2 = visible.y + visible.height - MARGIN; - - drawMainInfo(); - drawStabilityInfo(); - drawWarnings(); - drawFlightInformation(); - } - - - public void setCG(double cg) { - this.cg = cg; - } - - public void setCP(double cp) { - this.cp = cp; - } - - public void setLength(double length) { - this.length = length; - } - - public void setDiameter(double diameter) { - this.diameter = diameter; - } - - public void setMass(double mass) { - this.mass = mass; - } - - public void setWarnings(WarningSet warnings) { - this.warnings = warnings.clone(); - } - - public void setAOA(double aoa) { - this.aoa = aoa; - } - - public void setTheta(double theta) { - this.theta = theta; - } - - public void setMach(double mach) { - this.mach = mach; - } - - - public void setFlightData(FlightData data) { - this.flightData = data; - } - - public void setCalculatingData(boolean calc) { - this.calculatingData = calc; - } - - - - - private void drawMainInfo() { - GlyphVector name = createText(configuration.getRocket().getName()); - GlyphVector lengthLine = createText( - //// Length - trans.get("RocketInfo.lengthLine.Length") +" " + UnitGroup.UNITS_LENGTH.getDefaultUnit().toStringUnit(length) + - //// , max. diameter - trans.get("RocketInfo.lengthLine.maxdiameter") +" " + - UnitGroup.UNITS_LENGTH.getDefaultUnit().toStringUnit(diameter)); - - String massText; - if (configuration.hasMotors()) - //// Mass with motors - massText = trans.get("RocketInfo.massText1") +" "; - else - //// Mass with no motors - massText = trans.get("RocketInfo.massText2") +" "; - - massText += UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(mass); - - GlyphVector massLine = createText(massText); - - - g2.setColor(Color.BLACK); - - g2.drawGlyphVector(name, x1, y1); - g2.drawGlyphVector(lengthLine, x1, y1+line); - g2.drawGlyphVector(massLine, x1, y1+2*line); - - } - - - private void drawStabilityInfo() { - String at; - //// at M= - at = trans.get("RocketInfo.at")+UnitGroup.UNITS_COEFFICIENT.getDefaultUnit().toStringUnit(mach); - if (!Double.isNaN(aoa)) { - at += " "+ALPHA+"=" + UnitGroup.UNITS_ANGLE.getDefaultUnit().toStringUnit(aoa); - } - if (!Double.isNaN(theta)) { - at += " "+THETA+"=" + UnitGroup.UNITS_ANGLE.getDefaultUnit().toStringUnit(theta); - } - - GlyphVector cgValue = createText( - getCg()); - GlyphVector cpValue = createText( - getCp()); - GlyphVector stabValue = createText( - getStability()); - //// CG: - GlyphVector cgText = createText(trans.get("RocketInfo.cgText") +" "); - //// CP: - GlyphVector cpText = createText(trans.get("RocketInfo.cpText") +" "); - //// Stability: - GlyphVector stabText = createText(trans.get("RocketInfo.stabText") + " "); - GlyphVector atText = createSmallText(at); - - Rectangle2D cgRect = cgValue.getVisualBounds(); - Rectangle2D cpRect = cpValue.getVisualBounds(); - Rectangle2D cgTextRect = cgText.getVisualBounds(); - Rectangle2D cpTextRect = cpText.getVisualBounds(); - Rectangle2D stabRect = stabValue.getVisualBounds(); - Rectangle2D stabTextRect = stabText.getVisualBounds(); - Rectangle2D atTextRect = atText.getVisualBounds(); - - double unitWidth = MathUtil.max(cpRect.getWidth(), cgRect.getWidth(), - stabRect.getWidth()); - double textWidth = Math.max(cpTextRect.getWidth(), cgTextRect.getWidth()); - - - g2.setColor(Color.BLACK); - - g2.drawGlyphVector(stabValue, (float)(x2-stabRect.getWidth()), y1); - g2.drawGlyphVector(cgValue, (float)(x2-cgRect.getWidth()), y1+line); - g2.drawGlyphVector(cpValue, (float)(x2-cpRect.getWidth()), y1+2*line); - - g2.drawGlyphVector(stabText, (float)(x2-unitWidth-stabTextRect.getWidth()), y1); - g2.drawGlyphVector(cgText, (float)(x2-unitWidth-cgTextRect.getWidth()), y1+line); - g2.drawGlyphVector(cpText, (float)(x2-unitWidth-cpTextRect.getWidth()), y1+2*line); - - cgCaret.setPosition(x2 - unitWidth - textWidth - 10, y1+line-0.3*line); - cgCaret.paint(g2, 1.7); - - cpCaret.setPosition(x2 - unitWidth - textWidth - 10, y1+2*line-0.3*line); - cpCaret.paint(g2, 1.7); - - float atPos; - if (unitWidth + textWidth + 10 > atTextRect.getWidth()) { - atPos = (float)(x2-(unitWidth+textWidth+10+atTextRect.getWidth())/2); - } else { - atPos = (float)(x2 - atTextRect.getWidth()); - } - - g2.setColor(Color.GRAY); - g2.drawGlyphVector(atText, atPos, y1 + 3*line); - - } - - /** - * Get the mass, in default mass units. - * - * @return the mass - */ - public double getMass() { - return mass; - } - - /** - * Get the mass in specified mass units. - * - * @param u UnitGroup.MASS - * - * @return the mass - */ - public String getMass(Unit u) { - return u.toStringUnit(mass); - } - - /** - * Get the stability, in calibers. - * - * @return the current stability margin - */ - public String getStability () { - return stabilityUnits.getDefaultUnit().toStringUnit(cp-cg); - } - - /** - * Get the center of pressure in default length units. - * - * @return the distance from the tip to the center of pressure, in default length units - */ - public String getCp () { - return getCp(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - - /** - * Get the center of pressure in default length units. - * - * @param u UnitGroup.LENGTH - * - * @return the distance from the tip to the center of pressure, in default length units - */ - public String getCp (Unit u) { - return u.toStringUnit(cp); - } - - /** - * Get the center of gravity in default length units. - * - * @return the distance from the tip to the center of gravity, in default length units - */ - public String getCg () { - return getCg(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - - /** - * Get the center of gravity in specified length units. - * - * @param u UnitGroup.LENGTH - * @return the distance from the tip to the center of gravity, in specified units - */ - public String getCg (Unit u) { - return u.toStringUnit(cg); - } - - /** - * Get the flight data for the current motor configuration. - * - * @return flight data, or null - */ - public FlightData getFlightData () { - return flightData; - } - - private void drawWarnings() { - if (warnings == null || warnings.isEmpty()) - return; - - GlyphVector[] texts = new GlyphVector[warnings.size()+1]; - double max = 0; - - //// Warning: - texts[0] = createText(trans.get("RocketInfo.Warning")); - int i=1; - for (Warning w: warnings) { - texts[i] = createText(w.toString()); - i++; - } - - for (GlyphVector v: texts) { - Rectangle2D rect = v.getVisualBounds(); - if (rect.getWidth() > max) - max = rect.getWidth(); - } - - - float y = y2 - line * warnings.size(); - g2.setColor(new Color(255,0,0,130)); - - for (GlyphVector v: texts) { - Rectangle2D rect = v.getVisualBounds(); - g2.drawGlyphVector(v, (float)(x2 - max/2 - rect.getWidth()/2), y); - y += line; - } - } - - - private void drawFlightInformation() { - double height = drawFlightData(); - - if (calculatingData) { - //// Calculating... - GlyphVector calculating = createText(trans.get("RocketInfo.Calculating")); - g2.setColor(Color.BLACK); - g2.drawGlyphVector(calculating, x1, (float)(y2-height)); - } - } - - - private double drawFlightData() { - if (flightData == null) - return 0; - - double width=0; - - //// Apogee: - GlyphVector apogee = createText(trans.get("RocketInfo.Apogee")+" "); - //// Max. velocity: - GlyphVector maxVelocity = createText(trans.get("RocketInfo.Maxvelocity") +" "); - //// Max. acceleration: - GlyphVector maxAcceleration = createText(trans.get("RocketInfo.Maxacceleration") + " "); - - GlyphVector apogeeValue, velocityValue, accelerationValue; - if (!Double.isNaN(flightData.getMaxAltitude())) { - apogeeValue = createText( - UnitGroup.UNITS_DISTANCE.toStringUnit(flightData.getMaxAltitude())); - } else { - //// N/A - apogeeValue = createText(trans.get("RocketInfo.apogeeValue")); - } - if (!Double.isNaN(flightData.getMaxVelocity())) { - velocityValue = createText( - UnitGroup.UNITS_VELOCITY.toStringUnit(flightData.getMaxVelocity()) + - //// (Mach - " " +trans.get("RocketInfo.Mach") +" " + - UnitGroup.UNITS_COEFFICIENT.toString(flightData.getMaxMachNumber()) + ")"); - } else { - //// N/A - velocityValue = createText(trans.get("RocketInfo.velocityValue")); - } - if (!Double.isNaN(flightData.getMaxAcceleration())) { - accelerationValue = createText( - UnitGroup.UNITS_ACCELERATION.toStringUnit(flightData.getMaxAcceleration())); - } else { - //// N/A - accelerationValue = createText(trans.get("RocketInfo.accelerationValue")); - } - - Rectangle2D rect; - rect = apogee.getVisualBounds(); - width = MathUtil.max(width, rect.getWidth()); - - rect = maxVelocity.getVisualBounds(); - width = MathUtil.max(width, rect.getWidth()); - - rect = maxAcceleration.getVisualBounds(); - width = MathUtil.max(width, rect.getWidth()); - - width += 5; - - if (!calculatingData) - g2.setColor(new Color(0,0,127)); - else - g2.setColor(new Color(0,0,127,127)); - - - g2.drawGlyphVector(apogee, (float)x1, (float)(y2-2*line)); - g2.drawGlyphVector(maxVelocity, (float)x1, (float)(y2-line)); - g2.drawGlyphVector(maxAcceleration, (float)x1, (float)(y2)); - - g2.drawGlyphVector(apogeeValue, (float)(x1+width), (float)(y2-2*line)); - g2.drawGlyphVector(velocityValue, (float)(x1+width), (float)(y2-line)); - g2.drawGlyphVector(accelerationValue, (float)(x1+width), (float)(y2)); - - return 3*line; - } - - - - private GlyphVector createText(String text) { - return FONT.createGlyphVector(g2.getFontRenderContext(), text); - } - - private GlyphVector createSmallText(String text) { - return SMALLFONT.createGlyphVector(g2.getFontRenderContext(), text); - } - -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/GuidedTourSelectionDialog.java b/core/src/net/sf/openrocket/gui/help/tours/GuidedTourSelectionDialog.java deleted file mode 100644 index d3a74a3d..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/GuidedTourSelectionDialog.java +++ /dev/null @@ -1,192 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.List; - -import javax.swing.AbstractListModel; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.text.html.HTMLDocument; -import javax.swing.text.html.StyleSheet; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.components.StyledLabel.Style; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Named; - -public class GuidedTourSelectionDialog extends JDialog { - - private static final Translator trans = Application.getTranslator(); - - private static GuidedTourSelectionDialog instance = null; - - - private final SlideSetManager slideSetManager; - private final List tourNames; - - private SlideShowDialog slideShowDialog; - - private JList tourList; - private JEditorPane tourDescription; - private JLabel tourLength; - - - public GuidedTourSelectionDialog(Window parent) { - super(parent, trans.get("title"), ModalityType.MODELESS); - - slideSetManager = SlideSetManager.getSlideSetManager(); - tourNames = slideSetManager.getSlideSetNames(); - - JPanel panel = new JPanel(new MigLayout("fill")); - - panel.add(new StyledLabel(trans.get("lbl.selectTour"), Style.BOLD), "spanx, wrap rel"); - - tourList = new JList(new TourListModel()); - tourList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - tourList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - updateText(); - } - }); - tourList.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - startTour(); - } - } - }); - panel.add(new JScrollPane(tourList), "grow, gapright unrel, w 200lp, h 250lp"); - - - - // Sub-panel containing description and start button - JPanel sub = new JPanel(new MigLayout("fill, ins 0")); - sub.add(new StyledLabel(trans.get("lbl.description"), -1), "wrap rel"); - - tourDescription = new JEditorPane("text/html", ""); - tourDescription.setEditable(false); - StyleSheet ss = slideSetManager.getSlideSet(tourNames.get(0)).getStyleSheet(); - ((HTMLDocument) tourDescription.getDocument()).getStyleSheet().addStyleSheet(ss); - sub.add(new JScrollPane(tourDescription), "grow, wrap rel"); - - tourLength = new StyledLabel(-1); - sub.add(tourLength, "wrap unrel"); - - JButton start = new JButton(trans.get("btn.start")); - start.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - startTour(); - } - }); - sub.add(start, "growx"); - - panel.add(sub, "grow, wrap para, w 350lp, h 250lp"); - - - - JButton close = new JButton(trans.get("button.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - GuidedTourSelectionDialog.this.dispose(); - } - }); - panel.add(close, "spanx, right"); - - this.add(panel); - GUIUtil.setDisposableDialogOptions(this, close); - GUIUtil.rememberWindowPosition(this); - tourList.setSelectedIndex(0); - } - - - private void startTour() { - SlideSet ss = getSelectedSlideSet(); - if (ss == null) { - return; - } - - if (slideShowDialog != null && !slideShowDialog.isVisible()) { - closeTour(); - } - - if (slideShowDialog == null) { - slideShowDialog = new SlideShowDialog(this); - } - - slideShowDialog.setSlideSet(ss, 0); - slideShowDialog.setVisible(true); - } - - - private void closeTour() { - if (slideShowDialog != null) { - slideShowDialog.dispose(); - slideShowDialog = null; - } - } - - - private void updateText() { - SlideSet ss = getSelectedSlideSet(); - if (ss != null) { - tourDescription.setText(ss.getDescription()); - tourLength.setText(trans.get("lbl.length") + " " + ss.getSlideCount()); - } else { - tourDescription.setText(""); - tourLength.setText(trans.get("lbl.length")); - } - } - - - @SuppressWarnings("unchecked") - private SlideSet getSelectedSlideSet() { - return ((Named) tourList.getSelectedValue()).get(); - } - - private class TourListModel extends AbstractListModel { - - @Override - public Object getElementAt(int index) { - String name = tourNames.get(index); - SlideSet set = slideSetManager.getSlideSet(name); - return new Named(set, set.getTitle()); - } - - @Override - public int getSize() { - return tourNames.size(); - } - - } - - - public static void showDialog(Window parent) { - if (instance != null && instance.isVisible()) { - instance.setVisible(true); - instance.toFront(); - } else { - instance = new GuidedTourSelectionDialog(parent); - instance.setVisible(true); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/Slide.java b/core/src/net/sf/openrocket/gui/help/tours/Slide.java deleted file mode 100644 index 45ec129e..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/Slide.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.lang.ref.SoftReference; -import java.net.URL; - -import javax.imageio.ImageIO; - -import net.sf.openrocket.util.BugException; - -/** - * An individual slide in a guided tour. It contains a image (or reference to an - * image file) plus a text description (in HTML). - * - * @author Sampo Niskanen - */ -public class Slide { - private static final String NO_IMAGE = "none"; - - private final String imageFile; - private SoftReference imageReference = null; - - private final String text; - - - - public Slide(String imageFile, String text) { - this.imageFile = imageFile; - this.text = text; - } - - - - public BufferedImage getImage() { - - if (imageFile.equals(NO_IMAGE)) { - return new BufferedImage(0, 0, BufferedImage.TYPE_INT_ARGB); - } - - // Check the cache - if (imageReference != null) { - BufferedImage image = imageReference.get(); - if (image != null) { - return image; - } - } - - // Otherwise load and cache - BufferedImage image = loadImage(); - imageReference = new SoftReference(image); - - return image; - } - - public String getText() { - return text; - } - - - - private BufferedImage loadImage() { - BufferedImage img; - - try { - URL url = ClassLoader.getSystemResource(imageFile); - if (url != null) { - img = ImageIO.read(url); - } else { - throw new BugException("Could not find image " + imageFile); - } - } catch (IOException e) { - throw new BugException("Error reading image " + imageFile, e); - } - - return img; - } -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/SlideSet.java b/core/src/net/sf/openrocket/gui/help/tours/SlideSet.java deleted file mode 100644 index 459bda23..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/SlideSet.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.util.ArrayList; -import java.util.List; - -import javax.swing.text.html.StyleSheet; - -/** - * A set of slides that composes a tour. - * - * A slide set contains a (localized, plain-text) title for the tour, a (possibly - * multiline, HTML-formatted) description and a number of slides. - * - * @author Sampo Niskanen - */ -public class SlideSet { - - private String title = ""; - private String description = ""; - private final List slides = new ArrayList(); - private StyleSheet styleSheet = new StyleSheet(); - - - - public String getTitle() { - return title; - } - - public void setTitle(String name) { - this.title = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - - public Slide getSlide(int index) { - return this.slides.get(index); - } - - public void addSlide(Slide slide) { - this.slides.add(slide); - } - - public int getSlideCount() { - return this.slides.size(); - } - - public StyleSheet getStyleSheet() { - return styleSheet; - } - - public void setStyleSheet(StyleSheet styleSheet) { - this.styleSheet = styleSheet; - } - -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/SlideSetLoader.java b/core/src/net/sf/openrocket/gui/help/tours/SlideSetLoader.java deleted file mode 100644 index 1a32cb47..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/SlideSetLoader.java +++ /dev/null @@ -1,173 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sf.openrocket.util.BugException; - -/** - * Class that loads a slide set from a file. - * - * @author Sampo Niskanen - */ -public class SlideSetLoader { - - private static final Pattern NEW_SLIDE_PATTERN = Pattern.compile("^\\[(.*)\\]$"); - - private final String baseDir; - private TextLineReader source; - private Locale locale; - - - - - /** - * Constructor. - * - * @param baseDir The base directory from which to load from. It is prepended to the loaded - * file names and image file names. - */ - public SlideSetLoader(String baseDir) { - this(baseDir, Locale.getDefault()); - } - - - /** - * Constructor. - * - * @param baseDir The base directory from which to load from. It is prepended to the loaded - * file names and image file names. - * @param locale The locale for which the files are loaded. - */ - public SlideSetLoader(String baseDir, Locale locale) { - if (baseDir.length() > 0 && !baseDir.endsWith("/")) { - baseDir = baseDir + "/"; - } - this.baseDir = baseDir; - this.locale = locale; - } - - - /** - * Load a slide set from a file. The base directory is prepended to the - * file name first. - * - * @param filename the file to read in the base directory. - * @return the slide set - */ - public SlideSet load(String filename) throws IOException { - String file = baseDir + filename; - InputStream in = getLocalizedFile(file); - - try { - InputStreamReader reader = new InputStreamReader(in, "UTF-8"); - return load(reader); - } finally { - in.close(); - } - } - - - private InputStream getLocalizedFile(String filename) throws IOException { - for (String file : generateLocalizedFiles(filename)) { - InputStream in = ClassLoader.getSystemResourceAsStream(file); - if (in != null) { - return in; - } - } - throw new FileNotFoundException("File '" + filename + "' not found."); - } - - private List generateLocalizedFiles(String filename) { - String base, ext; - int index = filename.lastIndexOf('.'); - if (index >= 0) { - base = filename.substring(0, index); - ext = filename.substring(index); - } else { - base = filename; - ext = ""; - } - - - List list = new ArrayList(); - list.add(base + "_" + locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant() + ext); - list.add(base + "_" + locale.getLanguage() + "_" + locale.getCountry() + ext); - list.add(base + "_" + locale.getLanguage() + ext); - list.add(base + ext); - return list; - } - - - /** - * Load slide set from a reader. - * - * @param reader the reader to read from. - * @return the slide set. - */ - public SlideSet load(Reader reader) throws IOException { - source = new TextLineReader(reader); - - // Read title and description - String title = source.next(); - StringBuilder desc = new StringBuilder(); - while (!nextLineStartsSlide()) { - if (desc.length() > 0) { - desc.append('\n'); - } - desc.append(source.next()); - } - - // Create the slide set - SlideSet set = new SlideSet(); - set.setTitle(title); - set.setDescription(desc.toString()); - - - // Read the slides - while (source.hasNext()) { - Slide s = readSlide(); - set.addSlide(s); - } - - return set; - } - - - private Slide readSlide() { - - String imgLine = source.next(); - Matcher matcher = NEW_SLIDE_PATTERN.matcher(imgLine); - if (!matcher.matches()) { - throw new BugException("Line did not match new slide pattern: " + imgLine); - } - - String imageFile = matcher.group(1); - - StringBuffer desc = new StringBuffer(); - while (source.hasNext() && !nextLineStartsSlide()) { - if (desc.length() > 0) { - desc.append('\n'); - } - desc.append(source.next()); - } - - return new Slide(baseDir + imageFile, desc.toString()); - } - - - - private boolean nextLineStartsSlide() { - return NEW_SLIDE_PATTERN.matcher(source.peek()).matches(); - } - - -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/SlideSetManager.java b/core/src/net/sf/openrocket/gui/help/tours/SlideSetManager.java deleted file mode 100644 index 0d9e3815..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/SlideSetManager.java +++ /dev/null @@ -1,165 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.text.html.StyleSheet; - -import net.sf.openrocket.util.BugException; - -/** - * A manager that loads a number of slide sets from a defined base directory - * and provides access to them. - * - * @author Sampo Niskanen - */ -public class SlideSetManager { - private static final String TOURS_BASE_DIR = "datafiles/tours"; - - private static final String TOURS_FILE = "tours.txt"; - private static final String STYLESHEET_FILE = "style.css"; - - private static SlideSetManager slideSetManager = null; - - - private final String baseDir; - private final Map slideSets = new LinkedHashMap(); - - - /** - * Sole constructor. - * - * @param baseDir the base directory containing the tours and style files. - */ - public SlideSetManager(String baseDir) { - if (baseDir.length() > 0 && !baseDir.endsWith("/")) { - baseDir = baseDir + "/"; - } - this.baseDir = baseDir; - } - - - /** - * Load all the tours. - */ - public void load() throws IOException { - slideSets.clear(); - - List tours = loadTourList(); - StyleSheet styleSheet = loadStyleSheet(); - - for (String fileAndDir : tours) { - String base; - String file; - - String fullFileAndDir = baseDir + fileAndDir; - int index = fullFileAndDir.lastIndexOf('/'); - if (index >= 0) { - base = fullFileAndDir.substring(0, index); - file = fullFileAndDir.substring(index + 1); - } else { - base = ""; - file = ""; - } - - SlideSetLoader loader = new SlideSetLoader(base); - SlideSet set = loader.load(file); - set.setStyleSheet(styleSheet); - slideSets.put(fileAndDir, set); - } - - } - - - /** - * Return a set containing all the slide set names. - */ - public List getSlideSetNames() { - return new ArrayList(slideSets.keySet()); - } - - /** - * Retrieve an individual slide set. - * - * @param name the name of the slide set to retrieve. - * @return the slide set (never null) - * @throws IllegalArgumentException if the slide set with the name does not exist. - */ - public SlideSet getSlideSet(String name) { - SlideSet s = slideSets.get(name); - if (s == null) { - throw new IllegalArgumentException("Slide set with name '" + name + "' not found."); - } - return s; - } - - - private List loadTourList() throws IOException { - InputStream in = ClassLoader.getSystemResourceAsStream(baseDir + TOURS_FILE); - if (in == null) { - throw new FileNotFoundException("File '" + baseDir + TOURS_FILE + "' not found."); - } - - try { - - List tours = new ArrayList(); - TextLineReader reader = new TextLineReader(in); - while (reader.hasNext()) { - tours.add(reader.next()); - } - return tours; - - } finally { - in.close(); - } - } - - - private StyleSheet loadStyleSheet() throws IOException { - InputStream in = ClassLoader.getSystemResourceAsStream(baseDir + STYLESHEET_FILE); - if (in == null) { - throw new FileNotFoundException("File '" + baseDir + STYLESHEET_FILE + "' not found."); - } - - try { - - StyleSheet ss = new StyleSheet(); - InputStreamReader reader = new InputStreamReader(in, "UTF-8"); - ss.loadRules(reader, null); - return ss; - - } finally { - in.close(); - } - - } - - - - /** - * Return a singleton implementation that has loaded the default tours. - */ - public static SlideSetManager getSlideSetManager() { - if (slideSetManager == null) { - try { - SlideSetManager ssm = new SlideSetManager(TOURS_BASE_DIR); - ssm.load(); - - if (ssm.getSlideSetNames().isEmpty()) { - throw new FileNotFoundException("No tours found."); - } - - slideSetManager = ssm; - } catch (IOException e) { - throw new BugException(e); - } - } - return slideSetManager; - } -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/SlideShowComponent.java b/core/src/net/sf/openrocket/gui/help/tours/SlideShowComponent.java deleted file mode 100644 index 842e4a86..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/SlideShowComponent.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.awt.Dimension; - -import javax.swing.JEditorPane; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.event.HyperlinkListener; -import javax.swing.text.html.HTMLDocument; -import javax.swing.text.html.StyleSheet; - -import net.sf.openrocket.gui.components.ImageDisplayComponent; - -/** - * Component that displays a single slide, with the image on top and - * text below it. The portions are resizeable. - * - * @author Sampo Niskanen - */ -public class SlideShowComponent extends JSplitPane { - - private final int WIDTH = 600; - private final int HEIGHT_IMAGE = 400; - private final int HEIGHT_TEXT = 100; - - private final ImageDisplayComponent imageDisplay; - private final JEditorPane textPane; - - - public SlideShowComponent() { - super(VERTICAL_SPLIT); - - imageDisplay = new ImageDisplayComponent(); - imageDisplay.setPreferredSize(new Dimension(WIDTH, HEIGHT_IMAGE)); - this.setLeftComponent(imageDisplay); - - textPane = new JEditorPane("text/html", ""); - textPane.setEditable(false); - textPane.setPreferredSize(new Dimension(WIDTH, HEIGHT_TEXT)); - - JScrollPane scrollPanel = new JScrollPane(textPane); - this.setRightComponent(scrollPanel); - - this.setResizeWeight(((double) HEIGHT_IMAGE) / (HEIGHT_IMAGE + HEIGHT_TEXT)); - } - - - - public void setSlide(Slide slide) { - this.imageDisplay.setImage(slide.getImage()); - this.textPane.setText(slide.getText()); - this.textPane.setCaretPosition(0); - } - - - /** - * Replace the current HTML style sheet with a new style sheet. - */ - public void setStyleSheet(StyleSheet newStyleSheet) { - HTMLDocument doc = (HTMLDocument) textPane.getDocument(); - StyleSheet base = doc.getStyleSheet(); - StyleSheet[] linked = base.getStyleSheets(); - if (linked != null) { - for (StyleSheet ss : linked) { - base.removeStyleSheet(ss); - } - } - - base.addStyleSheet(newStyleSheet); - } - - - public void addHyperlinkListener(HyperlinkListener listener) { - textPane.addHyperlinkListener(listener); - } - -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/SlideShowDialog.java b/core/src/net/sf/openrocket/gui/help/tours/SlideShowDialog.java deleted file mode 100644 index 981bf1cc..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/SlideShowDialog.java +++ /dev/null @@ -1,173 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.KeyStroke; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Chars; - -public class SlideShowDialog extends JDialog { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private SlideShowComponent slideShowComponent; - private SlideSet slideSet; - private int position; - - private JButton nextButton; - private JButton prevButton; - private JButton closeButton; - - - public SlideShowDialog(Window parent) { - super(parent, ModalityType.MODELESS); - - JPanel panel = new JPanel(new MigLayout("fill")); - - slideShowComponent = new SlideShowComponent(); - slideShowComponent.addHyperlinkListener(new SlideShowLinkListener(parent)); - panel.add(slideShowComponent, "spanx, grow, wrap para"); - - - JPanel sub = new JPanel(new MigLayout("ins 0, fill")); - - prevButton = new JButton(Chars.LEFT_ARROW + " " + trans.get("btn.prev")); - prevButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Clicked previous button"); - setPosition(position - 1); - } - }); - sub.add(prevButton, "left"); - - - - nextButton = new JButton(trans.get("btn.next") + " " + Chars.RIGHT_ARROW); - nextButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Clicked next button"); - setPosition(position + 1); - } - }); - sub.add(nextButton, "left, gapleft para"); - - - sub.add(new JPanel(), "growx"); - - - closeButton = new JButton(trans.get("button.close")); - closeButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SlideShowDialog.this.dispose(); - } - }); - sub.add(closeButton, "right"); - - - panel.add(sub, "growx"); - - this.add(panel); - updateEnabled(); - addKeyActions(); - GUIUtil.setDisposableDialogOptions(this, nextButton); - nextButton.grabFocus(); - GUIUtil.rememberWindowPosition(this); - GUIUtil.rememberWindowSize(this); - // this.setAlwaysOnTop(true); - } - - public void setSlideSet(SlideSet slideSet, int position) { - this.slideSet = slideSet; - this.setTitle(slideSet.getTitle() + " " + Chars.EMDASH + " OpenRocket"); - slideShowComponent.setStyleSheet(slideSet.getStyleSheet()); - setPosition(position); - } - - public void setPosition(int position) { - if (this.slideSet == null) { - throw new BugException("setPosition called when slideSet is null"); - } - - if (position < 0 || position >= slideSet.getSlideCount()) { - throw new BugException("position exceeds slide count, position=" + position + - " slideCount=" + slideSet.getSlideCount()); - } - - this.position = position; - slideShowComponent.setSlide(slideSet.getSlide(position)); - updateEnabled(); - } - - - private void updateEnabled() { - if (slideSet == null) { - prevButton.setEnabled(false); - nextButton.setEnabled(false); - return; - } - - prevButton.setEnabled(position > 0); - nextButton.setEnabled(position < slideSet.getSlideCount() - 1); - } - - - - - - private void addKeyActions() { - Action next = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - log.user("Key action for next slide"); - if (position < slideSet.getSlideCount() - 1) { - setPosition(position + 1); - } - } - }; - - Action previous = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - log.user("Key action for previous slide"); - if (position > 0) { - setPosition(position - 1); - } - } - }; - - String nextKey = "slide:next"; - String prevKey = "slide:previous"; - - JRootPane root = this.getRootPane(); - root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), nextKey); - root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, 0), nextKey); - root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), prevKey); - root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, 0), prevKey); - - root.getActionMap().put(nextKey, next); - root.getActionMap().put(prevKey, previous); - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/SlideShowLinkListener.java b/core/src/net/sf/openrocket/gui/help/tours/SlideShowLinkListener.java deleted file mode 100644 index 6973b370..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/SlideShowLinkListener.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.awt.Desktop; -import java.awt.Window; -import java.net.URL; - -import javax.swing.JOptionPane; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkEvent.EventType; -import javax.swing.event.HyperlinkListener; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -public class SlideShowLinkListener implements HyperlinkListener { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private final Window parent; - - public SlideShowLinkListener(Window parent) { - this.parent = parent; - } - - @Override - public void hyperlinkUpdate(HyperlinkEvent event) { - - if (event.getEventType() != EventType.ACTIVATED) { - return; - } - - URL url = event.getURL(); - if (url != null && (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equals("https"))) { - - if (Desktop.isDesktopSupported()) { - try { - Desktop.getDesktop().browse(url.toURI()); - } catch (Exception e) { - // Ignore - } - } - - } else { - - String name = event.getDescription(); - try { - SlideSet ss = SlideSetManager.getSlideSetManager().getSlideSet(name); - - SlideShowDialog dialog = new SlideShowDialog(parent); - dialog.setSlideSet(ss, 0); - dialog.setVisible(true); - } catch (IllegalArgumentException e) { - log.warn("Guided tour '" + name + "' not found"); - JOptionPane.showMessageDialog(parent, - trans.get("error.msg"), trans.get("error.title"), JOptionPane.WARNING_MESSAGE); - } - - } - - } -} diff --git a/core/src/net/sf/openrocket/gui/help/tours/TextLineReader.java b/core/src/net/sf/openrocket/gui/help/tours/TextLineReader.java deleted file mode 100644 index fd3ddaf0..00000000 --- a/core/src/net/sf/openrocket/gui/help/tours/TextLineReader.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.sf.openrocket.gui.help.tours; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.Charset; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import net.sf.openrocket.util.BugException; - -/** - * Read from a Reader object one line at a time, ignoring blank lines, - * preceding and trailing whitespace and comment lines starting with '#'. - * - * @author Sampo Niskanen - */ -public class TextLineReader implements Iterator { - - private static final Charset UTF8 = Charset.forName("UTF-8"); - - - - private final BufferedReader reader; - - private String next = null; - - /** - * Read from an input stream with UTF-8 character encoding. - */ - public TextLineReader(InputStream inputStream) { - this(new InputStreamReader(inputStream, UTF8)); - } - - - /** - * Read from a reader. - */ - public TextLineReader(Reader reader) { - if (reader instanceof BufferedReader) { - this.reader = (BufferedReader) reader; - } else { - this.reader = new BufferedReader(reader); - } - } - - - /** - * Test whether the file has more lines available. - */ - @Override - public boolean hasNext() { - if (next != null) { - return true; - } - - try { - next = readLine(); - } catch (IOException e) { - throw new BugException(e); - } - - return next != null; - } - - - /** - * Retrieve the next non-blank, non-comment line. - */ - @Override - public String next() { - if (hasNext()) { - String ret = next; - next = null; - return ret; - } - - throw new NoSuchElementException("End of file reached"); - } - - - /** - * Peek what the next line would be. - */ - public String peek() { - if (hasNext()) { - return next; - } - - throw new NoSuchElementException("End of file reached"); - } - - - private String readLine() throws IOException { - - while (true) { - // Read the next line - String line = reader.readLine(); - if (line == null) { - return null; - } - - // Check whether to accept the line - line = line.trim(); - if (line.length() > 0 && line.charAt(0) != '#') { - return line; - } - } - - } - - - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported"); - } - -} diff --git a/core/src/net/sf/openrocket/gui/main/BasicFrame.java b/core/src/net/sf/openrocket/gui/main/BasicFrame.java deleted file mode 100644 index bdfcbd4a..00000000 --- a/core/src/net/sf/openrocket/gui/main/BasicFrame.java +++ /dev/null @@ -1,1548 +0,0 @@ -package net.sf.openrocket.gui.main; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.GeneralRocketLoader; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.file.RocketLoader; -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.file.openrocket.OpenRocketSaver; -import net.sf.openrocket.file.rocksim.export.RocksimSaver; -import net.sf.openrocket.gui.StorageOptionChooser; -import net.sf.openrocket.gui.configdialog.ComponentConfigDialog; -import net.sf.openrocket.gui.customexpression.CustomExpressionDialog; -import net.sf.openrocket.gui.dialogs.AboutDialog; -import net.sf.openrocket.gui.dialogs.BugReportDialog; -import net.sf.openrocket.gui.dialogs.ComponentAnalysisDialog; -import net.sf.openrocket.gui.dialogs.DebugLogDialog; -import net.sf.openrocket.gui.dialogs.DetailDialog; -import net.sf.openrocket.gui.dialogs.ExampleDesignDialog; -import net.sf.openrocket.gui.dialogs.LicenseDialog; -import net.sf.openrocket.gui.dialogs.MotorDatabaseLoadingDialog; -import net.sf.openrocket.gui.dialogs.PrintDialog; -import net.sf.openrocket.gui.dialogs.ScaleDialog; -import net.sf.openrocket.gui.dialogs.SwingWorkerDialog; -import net.sf.openrocket.gui.dialogs.WarningDialog; -import net.sf.openrocket.gui.dialogs.optimization.GeneralOptimizationDialog; -import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog; -import net.sf.openrocket.gui.help.tours.GuidedTourSelectionDialog; -import net.sf.openrocket.gui.main.componenttree.ComponentTree; -import net.sf.openrocket.gui.scalefigure.RocketPanel; -import net.sf.openrocket.gui.util.FileHelper; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.gui.util.OpenFileWorker; -import net.sf.openrocket.gui.util.SaveFileWorker; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MemoryManagement; -import net.sf.openrocket.util.MemoryManagement.MemoryData; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.TestRockets; - -import javax.swing.Action; -import javax.swing.BorderFactory; -import javax.swing.InputMap; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JSplitPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingUtilities; -import javax.swing.border.BevelBorder; -import javax.swing.border.TitledBorder; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Toolkit; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.ExecutionException; - -public class BasicFrame extends JFrame { - private static final LogHelper log = Application.getLogger(); - - /** - * The RocketLoader instance used for loading all rocket designs. - */ - private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader(); - - private static final RocketSaver ROCKET_SAVER = new OpenRocketSaver(); - - private static final Translator trans = Application.getTranslator(); - - public static final int COMPONENT_TAB = 0; - public static final int SIMULATION_TAB = 1; - - - /** - * List of currently open frames. When the list goes empty - * it is time to exit the application. - */ - private static final ArrayList frames = new ArrayList(); - - - /** - * Whether "New" and "Open" should replace this frame. - * Should be set to false on the first rocket modification. - */ - private boolean replaceable = false; - - - - private final OpenRocketDocument document; - private final Rocket rocket; - - private JTabbedPane tabbedPane; - private RocketPanel rocketpanel; - private ComponentTree tree = null; - - private final DocumentSelectionModel selectionModel; - private final TreeSelectionModel componentSelectionModel; - private final ListSelectionModel simulationSelectionModel; - - /** Actions available for rocket modifications */ - private final RocketActions actions; - - - - - /** - * Sole constructor. Creates a new frame based on the supplied document - * and adds it to the current frames list. - * - * @param document the document to show. - */ - public BasicFrame(OpenRocketDocument document) { - log.debug("Instantiating new BasicFrame"); - - this.document = document; - this.rocket = document.getRocket(); - this.rocket.getDefaultConfiguration().setAllStages(); - - // Create the component tree selection model that will be used - componentSelectionModel = new DefaultTreeSelectionModel(); - componentSelectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - - // Obtain the simulation selection model that will be used - SimulationPanel simulationPanel = new SimulationPanel(document); - simulationSelectionModel = simulationPanel.getSimulationListSelectionModel(); - - // Combine into a DocumentSelectionModel - selectionModel = new DocumentSelectionModel(document); - selectionModel.attachComponentTreeSelectionModel(componentSelectionModel); - selectionModel.attachSimulationListSelectionModel(simulationSelectionModel); - - - actions = new RocketActions(document, selectionModel, this); - - - log.debug("Constructing the BasicFrame UI"); - - // The main vertical split pane - JSplitPane vertical = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); - vertical.setResizeWeight(0.5); - this.add(vertical); - - - // The top tabbed pane - tabbedPane = new JTabbedPane(); - //// Rocket design - tabbedPane.addTab(trans.get("BasicFrame.tab.Rocketdesign"), null, designTab()); - //// Flight simulations - tabbedPane.addTab(trans.get("BasicFrame.tab.Flightsim"), null, simulationPanel); - - vertical.setTopComponent(tabbedPane); - - - - // Bottom segment, rocket figure - - rocketpanel = new RocketPanel(document); - vertical.setBottomComponent(rocketpanel); - - rocketpanel.setSelectionModel(tree.getSelectionModel()); - - - createMenu(); - - - rocket.addComponentChangeListener(new ComponentChangeListener() { - @Override - public void componentChanged(ComponentChangeEvent e) { - setTitle(); - } - }); - - setTitle(); - this.pack(); - - - // Set initial window size - Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); - size.width = size.width * 9 / 10; - size.height = size.height * 9 / 10; - this.setSize(size); - - // Remember changed size - GUIUtil.rememberWindowSize(this); - - this.setLocationByPlatform(true); - - GUIUtil.setWindowIcons(this); - - this.validate(); - vertical.setDividerLocation(0.4); - setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - closeAction(); - } - }); - - frames.add(this); - log.debug("BasicFrame instantiation complete"); - } - - - /** - * Construct the "Rocket design" tab. This contains a horizontal split pane - * with the left component the design tree and the right component buttons - * for adding components. - */ - private JComponent designTab() { - JSplitPane horizontal = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true); - horizontal.setResizeWeight(0.5); - - - // Upper-left segment, component tree - - JPanel panel = new JPanel(new MigLayout("fill, flowy", "", "[grow]")); - - tree = new ComponentTree(document); - tree.setSelectionModel(componentSelectionModel); - - // Remove JTree key events that interfere with menu accelerators - InputMap im = SwingUtilities.getUIInputMap(tree, JComponent.WHEN_FOCUSED); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK), null); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), null); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), null); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK), null); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK), null); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK), null); - im.put(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK), null); - - - - // Double-click opens config dialog - MouseListener ml = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - int selRow = tree.getRowForLocation(e.getX(), e.getY()); - TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); - if (selRow != -1) { - if ((e.getClickCount() == 2) && !ComponentConfigDialog.isDialogVisible()) { - // Double-click - RocketComponent c = (RocketComponent) selPath.getLastPathComponent(); - ComponentConfigDialog.showDialog(BasicFrame.this, - BasicFrame.this.document, c); - } - } - } - }; - tree.addMouseListener(ml); - - // Update dialog when selection is changed - componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(TreeSelectionEvent e) { - // Scroll tree to the selected item - TreePath path = componentSelectionModel.getSelectionPath(); - if (path == null) - return; - tree.scrollPathToVisible(path); - - if (!ComponentConfigDialog.isDialogVisible()) - return; - RocketComponent c = (RocketComponent) path.getLastPathComponent(); - ComponentConfigDialog.showDialog(BasicFrame.this, - BasicFrame.this.document, c); - } - }); - - // Place tree inside scroll pane - JScrollPane scroll = new JScrollPane(tree); - panel.add(scroll, "spany, grow, wrap"); - - - // Buttons - JButton button = new JButton(actions.getMoveUpAction()); - panel.add(button, "sizegroup buttons, aligny 65%"); - - button = new JButton(actions.getMoveDownAction()); - panel.add(button, "sizegroup buttons, aligny 0%"); - - button = new JButton(actions.getEditAction()); - panel.add(button, "sizegroup buttons"); - - button = new JButton(actions.getNewStageAction()); - panel.add(button, "sizegroup buttons"); - - button = new JButton(actions.getDeleteAction()); - button.setIcon(null); - button.setMnemonic(0); - panel.add(button, "sizegroup buttons"); - - horizontal.setLeftComponent(panel); - - - // Upper-right segment, component addition buttons - - panel = new JPanel(new MigLayout("fill, insets 0", "[0::]")); - - scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - scroll.setViewportView(new ComponentAddButtons(document, componentSelectionModel, - scroll.getViewport())); - scroll.setBorder(null); - scroll.setViewportBorder(null); - - TitledBorder border = BorderFactory.createTitledBorder(trans.get("BasicFrame.title.Addnewcomp")); - GUIUtil.changeFontStyle(border, Font.BOLD); - scroll.setBorder(border); - - panel.add(scroll, "grow"); - - horizontal.setRightComponent(panel); - - return horizontal; - } - - - - /** - * Return the currently selected rocket component, or null if none selected. - */ - private RocketComponent getSelectedComponent() { - TreePath path = componentSelectionModel.getSelectionPath(); - if (path == null) - return null; - tree.scrollPathToVisible(path); - - return (RocketComponent) path.getLastPathComponent(); - } - - - /** - * Creates the menu for the window. - */ - private void createMenu() { - JMenuBar menubar = new JMenuBar(); - JMenu menu; - JMenuItem item; - - //// File - menu = new JMenu(trans.get("main.menu.file")); - menu.setMnemonic(KeyEvent.VK_F); - //// File-handling related tasks - menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.desc")); - menubar.add(menu); - - //// New - item = new JMenuItem(trans.get("main.menu.file.new"), KeyEvent.VK_N); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); - item.setMnemonic(KeyEvent.VK_N); - //// Create a new rocket design - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.new.desc")); - item.setIcon(Icons.FILE_NEW); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("New... selected"); - newAction(); - closeIfReplaceable(); - } - }); - menu.add(item); - - //// Open... - item = new JMenuItem(trans.get("main.menu.file.open"), KeyEvent.VK_O); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); - //// Open a rocket design - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrocketdesign")); - item.setIcon(Icons.FILE_OPEN); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Open... selected"); - openAction(); - } - }); - menu.add(item); - - //// Open Recent... - item = new MRUDesignFileAction(trans.get("main.menu.file.openRecent"), this); - //// Open a recent rocket design - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openrecentrocketdesign")); - item.setIcon(Icons.FILE_OPEN); - menu.add(item); - - //// Open example... - item = new JMenuItem(trans.get("main.menu.file.openExample")); - //// Open an example rocket design - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Openexamplerocketdesign")); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, - ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)); - item.setIcon(Icons.FILE_OPEN_EXAMPLE); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Open example... selected"); - URL[] urls = ExampleDesignDialog.selectExampleDesigns(BasicFrame.this); - if (urls != null) { - for (URL u : urls) { - log.user("Opening example " + u); - open(u, BasicFrame.this); - } - } - } - }); - menu.add(item); - - menu.addSeparator(); - - //// Save - item = new JMenuItem(trans.get("main.menu.file.save"), KeyEvent.VK_S); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); - //// Save the current rocket design - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesign")); - item.setIcon(Icons.FILE_SAVE); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Save selected"); - saveAction(); - } - }); - menu.add(item); - - //// Save as... - item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, - ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)); - //// Save the current rocket design to a new file - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.SavecurRocketdesnewfile")); - item.setIcon(Icons.FILE_SAVE_AS); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Save as... selected"); - saveAsAction(); - } - }); - menu.add(item); - - //// Print... - item = new JMenuItem(trans.get("main.menu.file.print"), KeyEvent.VK_P); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK)); - //// Print parts list and fin template - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.file.print.desc")); - item.setIcon(Icons.FILE_PRINT); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Print action selected"); - printAction(); - } - }); - menu.add(item); - - - menu.addSeparator(); - - //// Close - item = new JMenuItem(trans.get("main.menu.file.close"), KeyEvent.VK_C); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)); - //// Close the current rocket design - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Closedesign")); - item.setIcon(Icons.FILE_CLOSE); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Close selected"); - closeAction(); - } - }); - menu.add(item); - - menu.addSeparator(); - - //// Quit - item = new JMenuItem(trans.get("main.menu.file.quit"), KeyEvent.VK_Q); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); - //// Quit the program - item.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.item.Quitprogram")); - item.setIcon(Icons.FILE_QUIT); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Quit selected"); - quitAction(); - } - }); - menu.add(item); - - - - //// Edit - menu = new JMenu(trans.get("main.menu.edit")); - menu.setMnemonic(KeyEvent.VK_E); - //// Rocket editing - menu.getAccessibleContext().setAccessibleDescription(trans.get("BasicFrame.menu.Rocketedt")); - menubar.add(menu); - - - Action action = UndoRedoAction.newUndoAction(document); - item = new JMenuItem(action); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); - item.setMnemonic(KeyEvent.VK_U); - //// Undo the previous operation - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.undo.desc")); - - menu.add(item); - - action = UndoRedoAction.newRedoAction(document); - item = new JMenuItem(action); - item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, ActionEvent.CTRL_MASK)); - item.setMnemonic(KeyEvent.VK_R); - //// Redo the previously undone operation - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.redo.desc")); - menu.add(item); - - menu.addSeparator(); - - - item = new JMenuItem(actions.getCutAction()); - menu.add(item); - - item = new JMenuItem(actions.getCopyAction()); - menu.add(item); - - item = new JMenuItem(actions.getPasteAction()); - menu.add(item); - - item = new JMenuItem(actions.getDeleteAction()); - menu.add(item); - - menu.addSeparator(); - - - - item = new JMenuItem(trans.get("main.menu.edit.resize")); - item.setIcon(Icons.EDIT_SCALE); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.resize.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Scale... selected"); - ScaleDialog dialog = new ScaleDialog(document, getSelectedComponent(), BasicFrame.this); - dialog.setVisible(true); - dialog.dispose(); - } - }); - menu.add(item); - - - - //// Preferences - item = new JMenuItem(trans.get("main.menu.edit.preferences")); - item.setIcon(Icons.PREFERENCES); - //// Setup the application preferences - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.edit.preferences.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Preferences selected"); - PreferencesDialog.showPreferences(BasicFrame.this); - } - }); - menu.add(item); - - - - - //// Analyze - menu = new JMenu(trans.get("main.menu.analyze")); - menu.setMnemonic(KeyEvent.VK_A); - //// Analyzing the rocket - menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.desc")); - menubar.add(menu); - - //// Component analysis - item = new JMenuItem(trans.get("main.menu.analyze.componentAnalysis"), KeyEvent.VK_C); - //// Analyze the rocket components separately - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.componentAnalysis.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Component analysis selected"); - ComponentAnalysisDialog.showDialog(rocketpanel); - } - }); - menu.add(item); - - //// Optimize - item = new JMenuItem(trans.get("main.menu.analyze.optimization"), KeyEvent.VK_O); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.optimization.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Rocket optimization selected"); - new GeneralOptimizationDialog(document, BasicFrame.this).setVisible(true); - } - }); - menu.add(item); - - //// Custom expressions - item = new JMenuItem(trans.get("main.menu.analyze.customExpressions"), KeyEvent.VK_E); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.analyze.customExpressions.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.debug("Custom expressions selected"); - new CustomExpressionDialog(document, BasicFrame.this).setVisible(true); - } - }); - menu.add(item); - - //// Debug - // (shown if openrocket.debug.menu is defined) - if (System.getProperty("openrocket.debug.menu") != null) { - menubar.add(makeDebugMenu()); - } - - - - //// Help - - menu = new JMenu(trans.get("main.menu.help")); - menu.setMnemonic(KeyEvent.VK_H); - menu.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.desc")); - menubar.add(menu); - - - // Guided tours - - item = new JMenuItem(trans.get("main.menu.help.tours"), KeyEvent.VK_L); - item.setIcon(Icons.HELP_TOURS); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.tours.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Guided tours selected"); - GuidedTourSelectionDialog.showDialog(BasicFrame.this); - } - }); - menu.add(item); - - menu.addSeparator(); - - //// Bug report - item = new JMenuItem(trans.get("main.menu.help.bugReport"), KeyEvent.VK_B); - item.setIcon(Icons.HELP_BUG_REPORT); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.bugReport.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Bug report selected"); - BugReportDialog.showBugReportDialog(BasicFrame.this); - } - }); - menu.add(item); - - //// Debug log - item = new JMenuItem(trans.get("main.menu.help.debugLog")); - item.setIcon(Icons.HELP_DEBUG_LOG); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.debugLog.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Debug log selected"); - new DebugLogDialog(BasicFrame.this).setVisible(true); - } - }); - menu.add(item); - - menu.addSeparator(); - - - //// License - item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L); - item.setIcon(Icons.HELP_LICENSE); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.license.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("License selected"); - new LicenseDialog(BasicFrame.this).setVisible(true); - } - }); - menu.add(item); - - - //// About - item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A); - item.setIcon(Icons.HELP_ABOUT); - item.getAccessibleContext().setAccessibleDescription(trans.get("main.menu.help.about.desc")); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("About selected"); - new AboutDialog(BasicFrame.this).setVisible(true); - } - }); - menu.add(item); - - - this.setJMenuBar(menubar); - } - - private JMenu makeDebugMenu() { - JMenu menu; - JMenuItem item; - - /* - * This menu is intentionally left untranslated. - */ - - //// Debug menu - menu = new JMenu("Debug"); - //// OpenRocket debugging tasks - menu.getAccessibleContext().setAccessibleDescription("OpenRocket debugging tasks"); - - //// What is this menu? - item = new JMenuItem("What is this menu?"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("What is this menu? selected"); - JOptionPane.showMessageDialog(BasicFrame.this, - new Object[] { - "The 'Debug' menu includes actions for testing and debugging " + - "OpenRocket.", " ", - "The menu is made visible by defining the system property " + - "'openrocket.debug.menu' when starting OpenRocket.", - "It should not be visible by default." }, - "Debug menu", JOptionPane.INFORMATION_MESSAGE); - } - }); - menu.add(item); - - menu.addSeparator(); - - //// Create test rocket - item = new JMenuItem("Create test rocket"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Create test rocket selected"); - JTextField field = new JTextField(); - int sel = JOptionPane.showOptionDialog(BasicFrame.this, new Object[] { - "Input text key to generate random rocket:", - field - }, "Generate random test rocket", JOptionPane.DEFAULT_OPTION, - JOptionPane.QUESTION_MESSAGE, null, new Object[] { - "Random", "OK" - }, "OK"); - - Rocket r; - if (sel == 0) { - r = new TestRockets(null).makeTestRocket(); - } else if (sel == 1) { - r = new TestRockets(field.getText()).makeTestRocket(); - } else { - return; - } - - OpenRocketDocument doc = new OpenRocketDocument(r); - doc.setSaved(true); - BasicFrame frame = new BasicFrame(doc); - frame.setVisible(true); - } - }); - menu.add(item); - - - - item = new JMenuItem("Create 'Iso-Haisu'"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Create Iso-Haisu selected"); - Rocket r = TestRockets.makeIsoHaisu(); - OpenRocketDocument doc = new OpenRocketDocument(r); - doc.setSaved(true); - BasicFrame frame = new BasicFrame(doc); - frame.setVisible(true); - } - }); - menu.add(item); - - - item = new JMenuItem("Create 'Big Blue'"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Create Big Blue selected"); - Rocket r = TestRockets.makeBigBlue(); - OpenRocketDocument doc = new OpenRocketDocument(r); - doc.setSaved(true); - BasicFrame frame = new BasicFrame(doc); - frame.setVisible(true); - } - }); - menu.add(item); - - menu.addSeparator(); - - - item = new JMenuItem("Memory statistics"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Memory statistics selected"); - - // Get discarded but remaining objects (this also runs System.gc multiple times) - List objects = MemoryManagement.getRemainingCollectableObjects(); - StringBuilder sb = new StringBuilder(); - sb.append("Objects that should have been garbage-collected but have not been:\n"); - int count = 0; - for (MemoryData data : objects) { - Object o = data.getReference().get(); - if (o == null) - continue; - sb.append("Age ").append(System.currentTimeMillis() - data.getRegistrationTime()) - .append(" ms: ").append(o).append('\n'); - count++; - // Explicitly null the strong reference to avoid possibility of invisible references - o = null; - } - sb.append("Total: " + count); - - // Get basic memory stats - System.gc(); - long max = Runtime.getRuntime().maxMemory(); - long free = Runtime.getRuntime().freeMemory(); - long used = max - free; - String[] stats = new String[4]; - stats[0] = "Memory usage:"; - stats[1] = String.format(" Max memory: %.1f MB", max / 1024.0 / 1024.0); - stats[2] = String.format(" Used memory: %.1f MB (%.0f%%)", used / 1024.0 / 1024.0, 100.0 * used / max); - stats[3] = String.format(" Free memory: %.1f MB (%.0f%%)", free / 1024.0 / 1024.0, 100.0 * free / max); - - - DetailDialog.showDetailedMessageDialog(BasicFrame.this, stats, sb.toString(), - "Memory statistics", JOptionPane.INFORMATION_MESSAGE); - } - }); - menu.add(item); - - //// Exhaust memory - item = new JMenuItem("Exhaust memory"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Exhaust memory selected"); - LinkedList data = new LinkedList(); - int count = 0; - final int bytesPerArray = 10240; - try { - while (true) { - byte[] array = new byte[bytesPerArray]; - for (int i = 0; i < bytesPerArray; i++) { - array[i] = (byte) i; - } - data.add(array); - count++; - } - } catch (OutOfMemoryError error) { - data = null; - long size = bytesPerArray * (long) count; - String s = String.format("OutOfMemory occurred after %d iterations (approx. %.1f MB consumed)", - count, size / 1024.0 / 1024.0); - log.debug(s, error); - JOptionPane.showMessageDialog(BasicFrame.this, s); - } - } - }); - menu.add(item); - - - menu.addSeparator(); - - //// Exception here - item = new JMenuItem("Exception here"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Exception here selected"); - throw new RuntimeException("Testing exception from menu action listener"); - } - }); - menu.add(item); - - item = new JMenuItem("Exception from EDT"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Exception from EDT selected"); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - throw new RuntimeException("Testing exception from " + - "later invoked EDT thread"); - } - }); - } - }); - menu.add(item); - - item = new JMenuItem("Exception from other thread"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Exception from other thread selected"); - new Thread() { - @Override - public void run() { - throw new RuntimeException("Testing exception from newly created thread"); - } - }.start(); - } - }); - menu.add(item); - - item = new JMenuItem("OutOfMemoryError here"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("OutOfMemoryError here selected"); - throw new OutOfMemoryError("Testing OutOfMemoryError from menu action listener"); - } - }); - menu.add(item); - - - menu.addSeparator(); - - - item = new JMenuItem("Test popup"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - log.user("Test popup selected"); - JPanel panel = new JPanel(); - panel.add(new JTextField(40)); - panel.add(new JSpinner()); - JPopupMenu popup = new JPopupMenu(); - popup.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); - popup.add(panel); - popup.show(BasicFrame.this, -50, 100); - } - }); - menu.add(item); - - - - - return menu; - } - - - /** - * Select the tab on the main pane. - * - * @param tab one of {@link #COMPONENT_TAB} or {@link #SIMULATION_TAB}. - */ - public void selectTab(int tab) { - tabbedPane.setSelectedIndex(tab); - } - - - - private void openAction() { - JFileChooser chooser = new JFileChooser(); - - chooser.addChoosableFileFilter(FileHelper.ALL_DESIGNS_FILTER); - chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER); - chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER); - chooser.setFileFilter(FileHelper.ALL_DESIGNS_FILTER); - - chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setMultiSelectionEnabled(true); - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - int option = chooser.showOpenDialog(this); - if (option != JFileChooser.APPROVE_OPTION) { - log.user("Decided not to open files, option=" + option); - return; - } - - ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory()); - - File[] files = chooser.getSelectedFiles(); - log.user("Opening files " + Arrays.toString(files)); - - for (File file : files) { - log.info("Opening file: " + file); - if (open(file, this)) { - MRUDesignFile opts = MRUDesignFile.getInstance(); - opts.addFile(file.getAbsolutePath()); - } - } - } - - void closeIfReplaceable() { - // Close previous window if replacing - if (replaceable && document.isSaved()) { - // We are replacing the frame, make new window have current location - BasicFrame newFrame = frames.get(frames.size() - 1); - newFrame.setLocation(this.getLocation()); - - log.info("Closing window because it is replaceable"); - closeAction(); - } - - } - /** - * Open a file based on a URL. - * @param url the file to open. - * @param parent the parent window for dialogs. - * @return true if opened successfully. - */ - private static boolean open(URL url, BasicFrame parent) { - String filename = null; - - // First figure out the file name from the URL - - // Try using URI.getPath(); - try { - URI uri = url.toURI(); - filename = uri.getPath(); - } catch (URISyntaxException ignore) { - } - - // Try URL-decoding the URL - if (filename == null) { - try { - filename = URLDecoder.decode(url.toString(), "UTF-8"); - } catch (UnsupportedEncodingException ignore) { - } - } - - // Last resort - if (filename == null) { - filename = ""; - } - - // Remove path from filename - if (filename.lastIndexOf('/') >= 0) { - filename = filename.substring(filename.lastIndexOf('/') + 1); - } - - - // Open the file - log.info("Opening file from url=" + url + " filename=" + filename); - try { - InputStream is = url.openStream(); - open(is, filename, parent); - } catch (IOException e) { - log.warn("Error opening file" + e); - JOptionPane.showMessageDialog(parent, - "An error occurred while opening the file " + filename, - "Error loading file", JOptionPane.ERROR_MESSAGE); - } - - return false; - } - - - /** - * Open the specified file from an InputStream in a new design frame. If an error - * occurs, an error dialog is shown and false is returned. - * - * @param stream the stream to load from. - * @param filename the file name to display in dialogs (not set to the document). - * @param parent the parent component for which a progress dialog is opened. - * @return whether the file was successfully loaded and opened. - */ - private static boolean open(InputStream stream, String filename, Window parent) { - OpenFileWorker worker = new OpenFileWorker(stream, ROCKET_LOADER); - return open(worker, filename, null, parent); - } - - - /** - * Open the specified file in a new design frame. If an error occurs, an error - * dialog is shown and false is returned. - * - * @param file the file to open. - * @param parent the parent component for which a progress dialog is opened. - * @return whether the file was successfully loaded and opened. - */ - public static boolean open(File file, Window parent) { - OpenFileWorker worker = new OpenFileWorker(file, ROCKET_LOADER); - return open(worker, file.getName(), file, parent); - } - - - /** - * Open the specified file using the provided worker. - * - * @param worker the OpenFileWorker that loads the file. - * @param filename the file name to display in dialogs. - * @param file the File to set the document to (may be null). - * @param parent - * @return - */ - private static boolean open(OpenFileWorker worker, String filename, File file, Window parent) { - - MotorDatabaseLoadingDialog.check(parent); - - // Open the file in a Swing worker thread - log.info("Starting OpenFileWorker"); - if (!SwingWorkerDialog.runWorker(parent, "Opening file", "Reading " + filename + "...", worker)) { - // User cancelled the operation - log.info("User cancelled the OpenFileWorker"); - return false; - } - - - // Handle the document - OpenRocketDocument doc = null; - try { - - doc = worker.get(); - - } catch (ExecutionException e) { - - Throwable cause = e.getCause(); - - if (cause instanceof FileNotFoundException) { - - log.warn("File not found", cause); - JOptionPane.showMessageDialog(parent, - "File not found: " + filename, - "Error opening file", JOptionPane.ERROR_MESSAGE); - return false; - - } else if (cause instanceof RocketLoadException) { - - log.warn("Error loading the file", cause); - JOptionPane.showMessageDialog(parent, - "Unable to open file '" + filename + "': " - + cause.getMessage(), - "Error opening file", JOptionPane.ERROR_MESSAGE); - return false; - - } else { - - throw new BugException("Unknown error when opening file", e); - - } - - } catch (InterruptedException e) { - throw new BugException("EDT was interrupted", e); - } - - if (doc == null) { - throw new BugException("Document loader returned null"); - } - - - // Show warnings - WarningSet warnings = worker.getRocketLoader().getWarnings(); - if (!warnings.isEmpty()) { - log.info("Warnings while reading file: " + warnings); - WarningDialog.showWarnings(parent, - new Object[] { - //// The following problems were encountered while opening - trans.get("BasicFrame.WarningDialog.txt1") + " " + filename + ".", - //// Some design features may not have been loaded correctly. - trans.get("BasicFrame.WarningDialog.txt2") - }, - //// Warnings while opening file - trans.get("BasicFrame.WarningDialog.title"), warnings); - } - - - // Set document state - doc.setFile(file); - doc.setSaved(true); - - - // Open the frame - log.debug("Opening new frame with the document"); - BasicFrame frame = new BasicFrame(doc); - frame.setVisible(true); - - if ( parent != null && parent instanceof BasicFrame ) { - ((BasicFrame)parent).closeIfReplaceable(); - } - return true; - } - - /** - * "Save" action. If the design is new, then this is identical to "Save As", with a default file filter for .ork. - * If the rocket being edited previously was opened from a .ork file, then it will be saved immediately to the same - * file. But clicking on 'Save' for an existing design file with a .rkt will bring up a confirmation dialog because - * it's potentially a destructive write (loss of some fidelity if it's truly an original Rocksim generated file). - * - * @return true if the file was saved, false otherwise - */ - private boolean saveAction() { - File file = document.getFile(); - if (file == null) { - log.info("Document does not contain file, opening save as dialog instead"); - return saveAsAction(); - } - log.info("Saving document to " + file); - - if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) { - return saveAsRocksim(file); - } - return saveAs(file); - } - - /** - * "Save As" action. - * - * Never should a .rkt file contain an OpenRocket content, or an .ork file contain a Rocksim design. Regardless of - * what extension the user has chosen, it would violate the Principle of Least Astonishment to do otherwise - * (and we want to make doing the wrong thing really hard to do). So always force the appropriate extension. - * - * This can result in some odd looking filenames (MyDesign.rkt.ork, MyDesign.rkt.ork.rkt, etc.) if the user is - * not paying attention, but the user can control that by modifying the filename in the dialog. - * - * @return true if the file was saved, false otherwise - */ - private boolean saveAsAction() { - File file = null; - - StorageOptionChooser storageChooser = - new StorageOptionChooser(document, document.getDefaultStorageOptions()); - final JFileChooser chooser = new JFileChooser(); - chooser.addChoosableFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER); - chooser.addChoosableFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER); - - //Force the file filter to match the file extension that was opened. Will default to OR if the file is null. - if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(document.getFile())) { - chooser.setFileFilter(FileHelper.ROCKSIM_DESIGN_FILTER); - } - else { - chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER); - } - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - chooser.setAccessory(storageChooser); - if (document.getFile() != null) { - chooser.setSelectedFile(document.getFile()); - } - - int option = chooser.showSaveDialog(BasicFrame.this); - if (option != JFileChooser.APPROVE_OPTION) { - log.user("User decided not to save, option=" + option); - return false; - } - - file = chooser.getSelectedFile(); - if (file == null) { - log.user("User did not select a file"); - return false; - } - - ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory()); - storageChooser.storeOptions(document.getDefaultStorageOptions()); - - if (chooser.getFileFilter().equals(FileHelper.ROCKSIM_DESIGN_FILTER)) { - return saveAsRocksim(file); - } - else { - file = FileHelper.forceExtension(file, "ork"); - return FileHelper.confirmWrite(file, this) && saveAs(file); - } - } - - /** - * Perform the writing of the design to the given file in Rocksim format. - * - * @param file the chosen file - * - * @return true if the file was written - */ - private boolean saveAsRocksim(File file) { - file = FileHelper.forceExtension(file, "rkt"); - if (!FileHelper.confirmWrite(file, this)) { - return false; - } - - try { - new RocksimSaver().save(file, document); - return true; - } catch (IOException e) { - return false; - } - } - - /** - * Perform the writing of the design to the given file in OpenRocket format. - * - * @param file the chosen file - * - * @return true if the file was written - */ - private boolean saveAs(File file) { - log.info("Saving document as " + file); - boolean saved = false; - - if (!StorageOptionChooser.verifyStorageOptions(document, this)) { - // User cancelled the dialog - log.user("User cancelled saving in storage options dialog"); - return false; - } - - - SaveFileWorker worker = new SaveFileWorker(document, file, ROCKET_SAVER); - - if (!SwingWorkerDialog.runWorker(this, "Saving file", - "Writing " + file.getName() + "...", worker)) { - - // User cancelled the save - log.user("User cancelled the save, deleting the file"); - file.delete(); - return false; - } - - try { - worker.get(); - document.setFile(file); - document.setSaved(true); - saved = true; - setTitle(); - } catch (ExecutionException e) { - - Throwable cause = e.getCause(); - - if (cause instanceof IOException) { - log.warn("An I/O error occurred while saving " + file, cause); - JOptionPane.showMessageDialog(this, new String[] { - "An I/O error occurred while saving:", - e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE); - return false; - } else { - Reflection.handleWrappedException(e); - } - - } catch (InterruptedException e) { - throw new BugException("EDT was interrupted", e); - } - - return saved; - } - - - private boolean closeAction() { - if (!document.isSaved()) { - log.info("Confirming whether to save the design"); - ComponentConfigDialog.hideDialog(); - int result = JOptionPane.showConfirmDialog(this, - trans.get("BasicFrame.dlg.lbl1") + rocket.getName() + - trans.get("BasicFrame.dlg.lbl2") + " " + - trans.get("BasicFrame.dlg.lbl3"), - trans.get("BasicFrame.dlg.title"), JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); - if (result == JOptionPane.YES_OPTION) { - // Save - log.user("User requested file save"); - if (!saveAction()) { - log.info("File save was interrupted, not closing"); - return false; - } - } else if (result == JOptionPane.NO_OPTION) { - // Don't save: No-op - log.user("User requested to discard design"); - } else { - // Cancel or close - log.user("User cancelled closing, result=" + result); - return false; - } - } - - // Rocket has been saved or discarded - log.debug("Disposing window"); - this.dispose(); - - ComponentConfigDialog.hideDialog(); - ComponentAnalysisDialog.hideDialog(); - - frames.remove(this); - if (frames.isEmpty()) { - log.info("Last frame closed, exiting"); - System.exit(0); - } - return true; - } - - - - /** - * - */ - public void printAction() { - Double rotation = rocketpanel.getFigure().getRotation(); - if (rotation == null) { - rotation = 0d; - } - new PrintDialog(this, document, rotation).setVisible(true); - } - - /** - * Open a new design window with a basic rocket+stage. - */ - public static void newAction() { - log.info("New action initiated"); - - Rocket rocket = new Rocket(); - Stage stage = new Stage(); - //// Sustainer - stage.setName(trans.get("BasicFrame.StageName.Sustainer")); - rocket.addChild(stage); - OpenRocketDocument doc = new OpenRocketDocument(rocket); - doc.setSaved(true); - - BasicFrame frame = new BasicFrame(doc); - frame.replaceable = true; - frame.setVisible(true); - // kruland commented this out - I don't like it. - //ComponentConfigDialog.showDialog(frame, doc, rocket); - } - - /** - * Quit the application. Confirms saving unsaved designs. The action of File->Quit. - */ - public static void quitAction() { - log.info("Quit action initiated"); - for (int i = frames.size() - 1; i >= 0; i--) { - log.debug("Closing frame " + frames.get(i)); - if (!frames.get(i).closeAction()) { - // Close canceled - log.info("Quit was cancelled"); - return; - } - } - // Should not be reached, but just in case - log.error("Should already have exited application"); - System.exit(0); - } - - - /** - * Set the title of the frame, taking into account the name of the rocket, file it - * has been saved to (if any) and saved status. - */ - private void setTitle() { - File file = document.getFile(); - boolean saved = document.isSaved(); - String title; - - title = rocket.getName(); - if (file != null) { - title = title + " (" + file.getName() + ")"; - } - if (!saved) - title = "*" + title; - - setTitle(title); - } - - - - /** - * Find a currently open BasicFrame containing the specified rocket. This method - * can be used to map a Rocket to a BasicFrame from GUI methods. - * - * @param rocket the Rocket. - * @return the corresponding BasicFrame, or null if none found. - */ - public static BasicFrame findFrame(Rocket rocket) { - for (BasicFrame f : frames) { - if (f.rocket == rocket) { - log.debug("Found frame " + f + " for rocket " + rocket); - return f; - } - } - log.debug("Could not find frame for rocket " + rocket); - return null; - } - - /** - * Find a currently open document by the rocket object. This method can be used - * to map a Rocket to OpenRocketDocument from GUI methods. - * - * @param rocket the Rocket. - * @return the corresponding OpenRocketDocument, or null if not found. - */ - public static OpenRocketDocument findDocument(Rocket rocket) { - BasicFrame frame = findFrame(rocket); - if (frame != null) { - return frame.document; - } else { - return null; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/main/ClipboardListener.java b/core/src/net/sf/openrocket/gui/main/ClipboardListener.java deleted file mode 100644 index 87fd4456..00000000 --- a/core/src/net/sf/openrocket/gui/main/ClipboardListener.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.sf.openrocket.gui.main; - -public interface ClipboardListener { - - public void clipboardChanged(); - -} diff --git a/core/src/net/sf/openrocket/gui/main/ComponentAddButtons.java b/core/src/net/sf/openrocket/gui/main/ComponentAddButtons.java deleted file mode 100644 index fa92a671..00000000 --- a/core/src/net/sf/openrocket/gui/main/ComponentAddButtons.java +++ /dev/null @@ -1,651 +0,0 @@ -package net.sf.openrocket.gui.main; - - -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JViewport; -import javax.swing.Scrollable; -import javax.swing.SwingConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.configdialog.ComponentConfigDialog; -import net.sf.openrocket.gui.main.componenttree.ComponentTreeModel; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.BodyComponent; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.ShockCord; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Pair; -import net.sf.openrocket.util.Reflection; - -/** - * A component that contains addition buttons to add different types of rocket components - * to a rocket. It enables and disables buttons according to the current selection of a - * TreeSelectionModel. - * - * @author Sampo Niskanen - */ - -public class ComponentAddButtons extends JPanel implements Scrollable { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private static final int ROWS = 3; - private static final int MAXCOLS = 6; - private static final String BUTTONPARAM = "grow, sizegroup buttons"; - - private static final int GAP = 5; - private static final int EXTRASPACE = 0; - - private final ComponentButton[][] buttons; - - private final OpenRocketDocument document; - private final TreeSelectionModel selectionModel; - private final JViewport viewport; - private final MigLayout layout; - - private final int width, height; - - - public ComponentAddButtons(OpenRocketDocument document, TreeSelectionModel model, - JViewport viewport) { - - super(); - String constaint = "[min!]"; - for (int i = 1; i < MAXCOLS; i++) - constaint = constaint + GAP + "[min!]"; - - layout = new MigLayout("fill", constaint); - setLayout(layout); - this.document = document; - this.selectionModel = model; - this.viewport = viewport; - - buttons = new ComponentButton[ROWS][]; - int row = 0; - - //////////////////////////////////////////// - - //// Body components and fin sets - addButtonRow(trans.get("compaddbuttons.Bodycompandfinsets"), row, - //// Nose cone - new BodyComponentButton(NoseCone.class, trans.get("compaddbuttons.Nosecone")), - //// Body tube - new BodyComponentButton(BodyTube.class, trans.get("compaddbuttons.Bodytube")), - //// Transition - new BodyComponentButton(Transition.class, trans.get("compaddbuttons.Transition")), - //// Trapezoidal - new FinButton(TrapezoidFinSet.class, trans.get("compaddbuttons.Trapezoidal")), // TODO: MEDIUM: freer fin placing - //// Elliptical - new FinButton(EllipticalFinSet.class, trans.get("compaddbuttons.Elliptical")), - //// Freeform - new FinButton(FreeformFinSet.class, trans.get("compaddbuttons.Freeform")), - //// Launch lug - new FinButton(LaunchLug.class, trans.get("compaddbuttons.Launchlug"))); - - row++; - - - ///////////////////////////////////////////// - - //// Inner component - addButtonRow(trans.get("compaddbuttons.Innercomponent"), row, - //// Inner tube - new ComponentButton(InnerTube.class, trans.get("compaddbuttons.Innertube")), - //// Coupler - new ComponentButton(TubeCoupler.class, trans.get("compaddbuttons.Coupler")), - //// Centering\nring - new ComponentButton(CenteringRing.class, trans.get("compaddbuttons.Centeringring")), - //// Bulkhead - new ComponentButton(Bulkhead.class, trans.get("compaddbuttons.Bulkhead")), - //// Engine\nblock - new ComponentButton(EngineBlock.class, trans.get("compaddbuttons.Engineblock"))); - - row++; - - //////////////////////////////////////////// - - //// Mass objects - addButtonRow(trans.get("compaddbuttons.Massobjects"), row, - //// Parachute - new ComponentButton(Parachute.class, trans.get("compaddbuttons.Parachute")), - //// Streamer - new ComponentButton(Streamer.class, trans.get("compaddbuttons.Streamer")), - //// Shock cord - new ComponentButton(ShockCord.class, trans.get("compaddbuttons.Shockcord")), - // new ComponentButton("Motor clip"), - // new ComponentButton("Payload"), - //// Mass\ncomponent - new ComponentButton(MassComponent.class, trans.get("compaddbuttons.Masscomponent"))); - - - // Get maximum button size - int w = 0, h = 0; - - for (row = 0; row < buttons.length; row++) { - for (int col = 0; col < buttons[row].length; col++) { - Dimension d = buttons[row][col].getPreferredSize(); - if (d.width > w) - w = d.width; - if (d.height > h) - h = d.height; - } - } - - // Set all buttons to maximum size - width = w; - height = h; - Dimension d = new Dimension(width, height); - for (row = 0; row < buttons.length; row++) { - for (int col = 0; col < buttons[row].length; col++) { - buttons[row][col].setMinimumSize(d); - buttons[row][col].setPreferredSize(d); - buttons[row][col].getComponent(0).validate(); - } - } - - // Add viewport listener if viewport provided - if (viewport != null) { - viewport.addChangeListener(new ChangeListener() { - private int oldWidth = -1; - - public void stateChanged(ChangeEvent e) { - Dimension d = ComponentAddButtons.this.viewport.getExtentSize(); - if (d.width != oldWidth) { - oldWidth = d.width; - flowButtons(); - } - } - }); - } - - add(new JPanel(), "grow"); - } - - - /** - * Adds a row of buttons to the panel. - * @param label Label placed before the row - * @param row Row number - * @param b List of ComponentButtons to place on the row - */ - private void addButtonRow(String label, int row, ComponentButton... b) { - if (row > 0) - add(new JLabel(label), "span, gaptop unrel, wrap"); - else - add(new JLabel(label), "span, gaptop 0, wrap"); - - int col = 0; - buttons[row] = new ComponentButton[b.length]; - - for (int i = 0; i < b.length; i++) { - buttons[row][col] = b[i]; - if (i < b.length - 1) - add(b[i], BUTTONPARAM); - else - add(b[i], BUTTONPARAM + ", wrap"); - col++; - } - } - - - /** - * Flows the buttons in all rows of the panel. If a button would come too close - * to the right edge of the viewport, "newline" is added to its constraints flowing - * it to the next line. - */ - private void flowButtons() { - if (viewport == null) - return; - - int w; - - Dimension d = viewport.getExtentSize(); - - for (int row = 0; row < buttons.length; row++) { - w = 0; - for (int col = 0; col < buttons[row].length; col++) { - w += GAP + width; - String param = BUTTONPARAM + ",width " + width + "!,height " + height + "!"; - - if (w + EXTRASPACE > d.width) { - param = param + ",newline"; - w = GAP + width; - } - if (col == buttons[row].length - 1) - param = param + ",wrap"; - layout.setComponentConstraints(buttons[row][col], param); - } - } - revalidate(); - } - - - - /** - * Class for a component button. - */ - private class ComponentButton extends JButton implements TreeSelectionListener { - protected Class componentClass = null; - private Constructor constructor = null; - - /** Only label, no icon. */ - public ComponentButton(String text) { - this(text, null, null); - } - - /** - * Constructor with icon and label. The icon and label are placed into the button. - * The label may contain "\n" as a newline. - */ - public ComponentButton(String text, Icon enabled, Icon disabled) { - super(); - setLayout(new MigLayout("fill, flowy, insets 0, gap 0", "", "")); - - add(new JLabel(), "push, sizegroup spacing"); - - // Add Icon - if (enabled != null) { - JLabel label = new JLabel(enabled); - if (disabled != null) - label.setDisabledIcon(disabled); - add(label, "growx"); - } - - // Add labels - String[] l = text.split("\n"); - for (int i = 0; i < l.length; i++) { - add(new StyledLabel(l[i], SwingConstants.CENTER, -3.0f), "growx"); - } - - add(new JLabel(), "push, sizegroup spacing"); - - valueChanged(null); // Update enabled status - selectionModel.addTreeSelectionListener(this); - } - - - /** - * Main constructor that should be used. The generated component type is specified - * and the text. The icons are fetched based on the component type. - */ - public ComponentButton(Class c, String text) { - this(text, ComponentIcons.getLargeIcon(c), ComponentIcons.getLargeDisabledIcon(c)); - - if (c == null) - return; - - componentClass = c; - - try { - constructor = c.getConstructor(); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException("Unable to get default " + - "constructor for class " + c, e); - } - } - - - /** - * Return whether the current component is addable when the component c is selected. - * c is null if there is no selection. The default is to use c.isCompatible(class). - */ - public boolean isAddable(RocketComponent c) { - if (c == null) - return false; - if (componentClass == null) - return false; - return c.isCompatible(componentClass); - } - - /** - * Return the position to add the component if component c is selected currently. - * The first element of the returned array is the RocketComponent to add the component - * to, and the second (if non-null) an Integer telling the position of the component. - * A return value of null means that the user cancelled addition of the component. - * If the Integer is null, the component is added at the end of the sibling - * list. By default returns the end of the currently selected component. - * - * @param c The component currently selected - * @return The position to add the new component to, or null if should not add. - */ - public Pair getAdditionPosition(RocketComponent c) { - return new Pair(c, null); - } - - /** - * Updates the enabled status of the button. - * TODO: LOW: What about updates to the rocket tree? - */ - public void valueChanged(TreeSelectionEvent e) { - updateEnabled(); - } - - /** - * Sets the enabled status of the button and all subcomponents. - */ - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - Component[] c = getComponents(); - for (int i = 0; i < c.length; i++) - c[i].setEnabled(enabled); - } - - - /** - * Update the enabled status of the button. - */ - private void updateEnabled() { - RocketComponent c = null; - TreePath p = selectionModel.getSelectionPath(); - if (p != null) - c = (RocketComponent) p.getLastPathComponent(); - setEnabled(isAddable(c)); - } - - - @Override - protected void fireActionPerformed(ActionEvent event) { - super.fireActionPerformed(event); - log.user("Adding component of type " + componentClass.getSimpleName()); - RocketComponent c = null; - Integer position = null; - - TreePath p = selectionModel.getSelectionPath(); - if (p != null) - c = (RocketComponent) p.getLastPathComponent(); - - Pair pos = getAdditionPosition(c); - if (pos == null) { - // Cancel addition - log.info("No position to add component"); - return; - } - c = pos.getU(); - position = pos.getV(); - - - if (c == null) { - // Should not occur - Application.getExceptionHandler().handleErrorCondition("ERROR: Could not place new component."); - updateEnabled(); - return; - } - - if (constructor == null) { - Application.getExceptionHandler().handleErrorCondition("ERROR: Construction of type not supported yet."); - return; - } - - RocketComponent component; - try { - component = (RocketComponent) constructor.newInstance(); - } catch (InstantiationException e) { - throw new BugException("Could not construct new instance of class " + constructor, e); - } catch (IllegalAccessException e) { - throw new BugException("Could not construct new instance of class " + constructor, e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - - // Next undo position is set by opening the configuration dialog - document.addUndoPosition("Add " + component.getComponentName()); - - log.info("Adding component " + component.getComponentName() + " to component " + c.getComponentName() + - " position=" + position); - - if (position == null) - c.addChild(component); - else - c.addChild(component, position); - - // Select new component and open config dialog - selectionModel.setSelectionPath(ComponentTreeModel.makeTreePath(component)); - - JFrame parent = null; - for (Component comp = ComponentAddButtons.this; comp != null; comp = comp.getParent()) { - if (comp instanceof JFrame) { - parent = (JFrame) comp; - break; - } - } - - ComponentConfigDialog.showDialog(parent, document, component); - } - } - - /** - * A class suitable for BodyComponents. Addition is allowed ... - */ - private class BodyComponentButton extends ComponentButton { - - public BodyComponentButton(Class c, String text) { - super(c, text); - } - - public BodyComponentButton(String text, Icon enabled, Icon disabled) { - super(text, enabled, disabled); - } - - public BodyComponentButton(String text) { - super(text); - } - - @Override - public boolean isAddable(RocketComponent c) { - if (super.isAddable(c)) - return true; - // Handled separately: - if (c instanceof BodyComponent) - return true; - if (c == null || c instanceof Rocket) - return true; - return false; - } - - @Override - public Pair getAdditionPosition(RocketComponent c) { - if (super.isAddable(c)) // Handled automatically - return super.getAdditionPosition(c); - - - if (c == null || c instanceof Rocket) { - // Add as last body component of the last stage - Rocket rocket = document.getRocket(); - return new Pair(rocket.getChild(rocket.getStageCount() - 1), - null); - } - - if (!(c instanceof BodyComponent)) - return null; - RocketComponent parent = c.getParent(); - if (parent == null) { - throw new BugException("Component " + c.getComponentName() + " is the root component, " + - "componentClass=" + componentClass); - } - - // Check whether to insert between or at the end. - // 0 = ask, 1 = in between, 2 = at the end - int pos = Application.getPreferences().getChoice(Preferences.BODY_COMPONENT_INSERT_POSITION_KEY, 2, 0); - if (pos == 0) { - if (parent.getChildPosition(c) == parent.getChildCount() - 1) - pos = 2; // Selected component is the last component - else - pos = askPosition(); - } - - switch (pos) { - case 0: - // Cancel - return null; - case 1: - // Insert after current position - return new Pair(parent, parent.getChildPosition(c) + 1); - case 2: - // Insert at the end of the parent - return new Pair(parent, null); - default: - Application.getExceptionHandler().handleErrorCondition("ERROR: Bad position type: " + pos); - return null; - } - } - - private int askPosition() { - //// Insert here - //// Add to the end - //// Cancel - Object[] options = { trans.get("compaddbuttons.askPosition.Inserthere"), - trans.get("compaddbuttons.askPosition.Addtotheend"), - trans.get("compaddbuttons.askPosition.Cancel") }; - - JPanel panel = new JPanel(new MigLayout()); - //// Do not ask me again - JCheckBox check = new JCheckBox(trans.get("compaddbuttons.Donotaskmeagain")); - panel.add(check, "wrap"); - //// You can change the default operation in the preferences. - panel.add(new StyledLabel(trans.get("compaddbuttons.lbl.Youcanchange"), -2)); - - int sel = JOptionPane.showOptionDialog(null, // parent component - //// Insert the component after the current component or as the last component? - new Object[] { - trans.get("compaddbuttons.lbl.insertcomp"), - panel }, - //// Select component position - trans.get("compaddbuttons.Selectcomppos"), // title - JOptionPane.DEFAULT_OPTION, // default selections - JOptionPane.QUESTION_MESSAGE, // dialog type - null, // icon - options, // options - options[0]); // initial value - - switch (sel) { - case JOptionPane.CLOSED_OPTION: - case 2: - // Cancel - return 0; - case 0: - // Insert - sel = 1; - break; - case 1: - // Add - sel = 2; - break; - default: - Application.getExceptionHandler().handleErrorCondition("ERROR: JOptionPane returned " + sel); - return 0; - } - - if (check.isSelected()) { - // Save the preference - Application.getPreferences().putInt(Preferences.BODY_COMPONENT_INSERT_POSITION_KEY, sel); - } - return sel; - } - - } - - - - /** - * Class for fin sets, that attach only to BodyTubes. - */ - private class FinButton extends ComponentButton { - public FinButton(Class c, String text) { - super(c, text); - } - - public FinButton(String text, Icon enabled, Icon disabled) { - super(text, enabled, disabled); - } - - public FinButton(String text) { - super(text); - } - - @Override - public boolean isAddable(RocketComponent c) { - if (c == null) - return false; - return (c.getClass().equals(BodyTube.class)); - } - } - - - - ///////// Scrolling functionality - - @Override - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - - @Override - public int getScrollableBlockIncrement(Rectangle visibleRect, - int orientation, int direction) { - if (orientation == SwingConstants.VERTICAL) - return visibleRect.height * 8 / 10; - return 10; - } - - - @Override - public boolean getScrollableTracksViewportHeight() { - return false; - } - - - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - - - @Override - public int getScrollableUnitIncrement(Rectangle visibleRect, - int orientation, int direction) { - return 10; - } - -} diff --git a/core/src/net/sf/openrocket/gui/main/ComponentIcons.java b/core/src/net/sf/openrocket/gui/main/ComponentIcons.java deleted file mode 100644 index b0071caa..00000000 --- a/core/src/net/sf/openrocket/gui/main/ComponentIcons.java +++ /dev/null @@ -1,183 +0,0 @@ -package net.sf.openrocket.gui.main; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.URL; -import java.util.HashMap; - -import javax.imageio.ImageIO; -import javax.swing.Icon; -import javax.swing.ImageIcon; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.ShockCord; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.startup.Application; - - -public class ComponentIcons { - private static final Translator trans = Application.getTranslator(); - - private static final String ICON_DIRECTORY = "pix/componenticons/"; - private static final String SMALL_SUFFIX = "-small.png"; - private static final String LARGE_SUFFIX = "-large.png"; - - private static final HashMap, ImageIcon> SMALL_ICONS = - new HashMap, ImageIcon>(); - private static final HashMap, ImageIcon> LARGE_ICONS = - new HashMap, ImageIcon>(); - private static final HashMap, ImageIcon> DISABLED_ICONS = - new HashMap, ImageIcon>(); - - static { - //// Nose cone - load("nosecone", trans.get("ComponentIcons.Nosecone"), NoseCone.class); - //// Body tube - load("bodytube", trans.get("ComponentIcons.Bodytube"), BodyTube.class); - //// Transition - load("transition", trans.get("ComponentIcons.Transition"), Transition.class); - //// Trapezoidal fin set - load("trapezoidfin", trans.get("ComponentIcons.Trapezoidalfinset"), TrapezoidFinSet.class); - //// Elliptical fin set - load("ellipticalfin", trans.get("ComponentIcons.Ellipticalfinset"), EllipticalFinSet.class); - //// Freeform fin set - load("freeformfin", trans.get("ComponentIcons.Freeformfinset"), FreeformFinSet.class); - //// Launch lug - load("launchlug", trans.get("ComponentIcons.Launchlug"), LaunchLug.class); - //// Inner tube - load("innertube", trans.get("ComponentIcons.Innertube"), InnerTube.class); - //// Tube coupler - load("tubecoupler", trans.get("ComponentIcons.Tubecoupler"), TubeCoupler.class); - //// Centering ring - load("centeringring", trans.get("ComponentIcons.Centeringring"), CenteringRing.class); - //// Bulk head - load("bulkhead", trans.get("ComponentIcons.Bulkhead"), Bulkhead.class); - //// Engine block - load("engineblock", trans.get("ComponentIcons.Engineblock"), EngineBlock.class); - //// Parachute - load("parachute", trans.get("ComponentIcons.Parachute"), Parachute.class); - //// Streamer - load("streamer", trans.get("ComponentIcons.Streamer"), Streamer.class); - //// Shock cord - load("shockcord", trans.get("ComponentIcons.Shockcord"), ShockCord.class); - //// Mass component - load("mass", trans.get("ComponentIcons.Masscomponent"), MassComponent.class); - } - - private static void load(String filename, String name, Class componentClass) { - ImageIcon icon = loadSmall(ICON_DIRECTORY + filename + SMALL_SUFFIX, name); - SMALL_ICONS.put(componentClass, icon); - - ImageIcon[] icons = loadLarge(ICON_DIRECTORY + filename + LARGE_SUFFIX, name); - LARGE_ICONS.put(componentClass, icons[0]); - DISABLED_ICONS.put(componentClass, icons[1]); - } - - - /** - * Return the small icon for a component type. - * - * @param c the component class. - * @return the icon, or null if none available. - */ - public static Icon getSmallIcon(Class c) { - return SMALL_ICONS.get(c); - } - - /** - * Return the large icon for a component type. - * - * @param c the component class. - * @return the icon, or null if none available. - */ - public static Icon getLargeIcon(Class c) { - return LARGE_ICONS.get(c); - } - - /** - * Return the large disabled icon for a component type. - * - * @param c the component class. - * @return the icon, or null if none available. - */ - public static Icon getLargeDisabledIcon(Class c) { - return DISABLED_ICONS.get(c); - } - - - - - private static ImageIcon loadSmall(String file, String desc) { - URL url = ClassLoader.getSystemResource(file); - if (url == null) { - Application.getExceptionHandler().handleErrorCondition("ERROR: Couldn't find file: " + file); - return null; - } - return new ImageIcon(url, desc); - } - - - private static ImageIcon[] loadLarge(String file, String desc) { - ImageIcon[] icons = new ImageIcon[2]; - - URL url = ClassLoader.getSystemResource(file); - if (url != null) { - BufferedImage bi, bi2; - try { - bi = ImageIO.read(url); - bi2 = ImageIO.read(url); // How the fsck can one duplicate a BufferedImage??? - } catch (IOException e) { - Application.getExceptionHandler().handleErrorCondition("ERROR: Couldn't read file: " + file, e); - return new ImageIcon[] { null, null }; - } - - icons[0] = new ImageIcon(bi, desc); - - // Create disabled icon - if (false) { // Fade using alpha - - int rgb[] = bi2.getRGB(0, 0, bi2.getWidth(), bi2.getHeight(), null, 0, bi2.getWidth()); - for (int i = 0; i < rgb.length; i++) { - final int alpha = (rgb[i] >> 24) & 0xFF; - rgb[i] = (rgb[i] & 0xFFFFFF) | (alpha / 3) << 24; - - //rgb[i] = (rgb[i]&0xFFFFFF) | ((rgb[i]>>1)&0x3F000000); - } - bi2.setRGB(0, 0, bi2.getWidth(), bi2.getHeight(), rgb, 0, bi2.getWidth()); - - } else { // Raster alpha - - for (int x = 0; x < bi.getWidth(); x++) { - for (int y = 0; y < bi.getHeight(); y++) { - if ((x + y) % 2 == 0) { - bi2.setRGB(x, y, 0); - } - } - } - - } - - //// (disabled) - icons[1] = new ImageIcon(bi2, desc + " " + trans.get("ComponentIcons.disabled")); - - return icons; - } else { - Application.getExceptionHandler().handleErrorCondition("ERROR: Couldn't find file: " + file); - return new ImageIcon[] { null, null }; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/main/DocumentSelectionListener.java b/core/src/net/sf/openrocket/gui/main/DocumentSelectionListener.java deleted file mode 100644 index 055f1116..00000000 --- a/core/src/net/sf/openrocket/gui/main/DocumentSelectionListener.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.sf.openrocket.gui.main; - -public interface DocumentSelectionListener { - - public static final int COMPONENT_SELECTION_CHANGE = 1; - public static final int SIMULATION_SELECTION_CHANGE = 2; - - /** - * Called when the selection changes. - * - * @param changeType a bitmask of the type of change. - */ - public void valueChanged(int changeType); - -} diff --git a/core/src/net/sf/openrocket/gui/main/DocumentSelectionModel.java b/core/src/net/sf/openrocket/gui/main/DocumentSelectionModel.java deleted file mode 100644 index 409620cb..00000000 --- a/core/src/net/sf/openrocket/gui/main/DocumentSelectionModel.java +++ /dev/null @@ -1,211 +0,0 @@ -package net.sf.openrocket.gui.main; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.main.componenttree.ComponentTreeModel; -import net.sf.openrocket.rocketcomponent.RocketComponent; - -public class DocumentSelectionModel { - - private static final Simulation[] NO_SIMULATION = new Simulation[0]; - - private final ComponentTreeSelectionListener componentTreeSelectionListener = - new ComponentTreeSelectionListener(); - private final SimulationListSelectionListener simulationListSelectionListener = - new SimulationListSelectionListener(); - - - private final OpenRocketDocument document; - - private RocketComponent componentSelection = null; - private Simulation[] simulationSelection = NO_SIMULATION; - - private TreeSelectionModel componentTreeSelectionModel = null; - private ListSelectionModel simulationListSelectionModel = null; - - private final List listeners = - new ArrayList(); - - - - public DocumentSelectionModel(OpenRocketDocument document) { - this.document = document; - } - - - - - /** - * Return the currently selected simulations. Returns an empty array if none - * are selected. - * - * @return an array of the currently selected simulations, may be of zero length. - */ - public Simulation[] getSelectedSimulations() { - return Arrays.copyOf(simulationSelection, simulationSelection.length); - } - - public void setSelectedSimulations(Simulation[] sims) { - simulationSelection = sims; - clearComponentSelection(); - - simulationListSelectionModel.clearSelection(); - for (Simulation s: sims) { - int index = document.getSimulationIndex(s); - if (index >= 0) { - simulationListSelectionModel.addSelectionInterval(index, index); - } - } - } - - /** - * Return the currently selected rocket component. Returns null - * if no rocket component is selected. - * - * @return the currently selected rocket component, or null. - */ - public RocketComponent getSelectedComponent() { - return componentSelection; - } - - public void setSelectedComponent(RocketComponent component) { - componentSelection = component; - clearSimulationSelection(); - - TreePath path = ComponentTreeModel.makeTreePath(component); - componentTreeSelectionModel.setSelectionPath(path); - } - - - - - - public void attachComponentTreeSelectionModel(TreeSelectionModel model) { - if (componentTreeSelectionModel != null) - componentTreeSelectionModel.removeTreeSelectionListener( - componentTreeSelectionListener); - - componentTreeSelectionModel = model; - if (model != null) - model.addTreeSelectionListener(componentTreeSelectionListener); - clearComponentSelection(); - } - - - - public void attachSimulationListSelectionModel(ListSelectionModel model) { - if (simulationListSelectionModel != null) - simulationListSelectionModel.removeListSelectionListener( - simulationListSelectionListener); - - simulationListSelectionModel = model; - if (model != null) - model.addListSelectionListener(simulationListSelectionListener); - clearSimulationSelection(); - } - - - - public void clearSimulationSelection() { - if (simulationSelection.length == 0) - return; - - simulationSelection = NO_SIMULATION; - if (simulationListSelectionModel != null) - simulationListSelectionModel.clearSelection(); - - fireDocumentSelection(DocumentSelectionListener.SIMULATION_SELECTION_CHANGE); - } - - - public void clearComponentSelection() { - if (componentSelection == null) - return; - - componentSelection = null; - if (componentTreeSelectionModel != null) - componentTreeSelectionModel.clearSelection(); - - fireDocumentSelection(DocumentSelectionListener.COMPONENT_SELECTION_CHANGE); - } - - - - public void addDocumentSelectionListener(DocumentSelectionListener l) { - listeners.add(l); - } - - public void removeDocumentSelectionListener(DocumentSelectionListener l) { - listeners.remove(l); - } - - protected void fireDocumentSelection(int type) { - DocumentSelectionListener[] array = - listeners.toArray(new DocumentSelectionListener[0]); - - for (DocumentSelectionListener l: array) { - l.valueChanged(type); - } - } - - - - private class ComponentTreeSelectionListener implements TreeSelectionListener { - - @Override - public void valueChanged(TreeSelectionEvent e) { - TreePath path = componentTreeSelectionModel.getSelectionPath(); - if (path == null) { - componentSelection = null; - fireDocumentSelection(DocumentSelectionListener.COMPONENT_SELECTION_CHANGE); - return; - } - - componentSelection = (RocketComponent)path.getLastPathComponent(); - - clearSimulationSelection(); - fireDocumentSelection(DocumentSelectionListener.COMPONENT_SELECTION_CHANGE); - } - - } - - private class SimulationListSelectionListener implements ListSelectionListener { - - @Override - public void valueChanged(ListSelectionEvent e) { - int min = simulationListSelectionModel.getMinSelectionIndex(); - int max = simulationListSelectionModel.getMaxSelectionIndex(); - if (min < 0 || max < 0) { - simulationSelection = NO_SIMULATION; - fireDocumentSelection(DocumentSelectionListener.SIMULATION_SELECTION_CHANGE); - return; - } - - ArrayList list = new ArrayList(); - for (int i = min; i <= max; i++) { - if (simulationListSelectionModel.isSelectedIndex(i) && - (i < document.getSimulationCount())) { - list.add(document.getSimulation(i)); - } - } - simulationSelection = list.toArray(NO_SIMULATION); - - clearComponentSelection(); - fireDocumentSelection(DocumentSelectionListener.SIMULATION_SELECTION_CHANGE); - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/main/MRUDesignFile.java b/core/src/net/sf/openrocket/gui/main/MRUDesignFile.java deleted file mode 100644 index f32d23e8..00000000 --- a/core/src/net/sf/openrocket/gui/main/MRUDesignFile.java +++ /dev/null @@ -1,179 +0,0 @@ -package net.sf.openrocket.gui.main; - -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; - -import javax.swing.event.EventListenerList; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.List; - -/** - * Implements a most-recently-used list backed by preferences. This is modified/adapted from an example on the - * Netbeans wiki. - */ -public class MRUDesignFile { - - public static final String MRU_FILE_LIST_PROPERTY = "MRUFileList"; - - public static final int MAX_SIZE = 9; - - private List mruFileList; - - private static MRUDesignFile instance; // The single instance - - private EventListenerList listenerList; - - static { - instance = new MRUDesignFile(); - } - - /** - * Returns the single instance, creating one if it's the first time this method is called. - * - * @return The single instance. - */ - public static MRUDesignFile getInstance() { - return instance; - } - - /** - * Constructor. - */ - protected MRUDesignFile() { - mruFileList = new ArrayList(MAX_SIZE); - listenerList = new EventListenerList(); - retrieve(); - } - - /** - * Get the current most-recently-used list of design files. - * - * @return a list that contains absolute file names - */ - public List getMRUFileList() { - return mruFileList; - } - - /** - * Set the most-recently-used list to the given parameter and fire change events. - * - * @param list - */ - public void setMRUFileList(List list) { - this.mruFileList.clear(); - this.mruFileList.addAll(list.subList(0, Math.min(list.size(), MAX_SIZE))); - firePropertyChange(MRU_FILE_LIST_PROPERTY, null, mruFileList); - store(); - } - - /** - * Remove a file from the MRU list and fire change events. - * - * @param absolutePath the filename to be removed - */ - public void removeFile(String absolutePath) { - mruFileList.remove(absolutePath); - firePropertyChange(MRU_FILE_LIST_PROPERTY, null, mruFileList); - store(); - } - - /** - * Add a file to the MRU list and fire change events. - * - * @param absolutePath the filename to be added - */ - public void addFile(String absolutePath) { - // remove the old - mruFileList.remove(absolutePath); - - // add to the top - mruFileList.add(0, absolutePath); - while (mruFileList.size() > MAX_SIZE) { - mruFileList.remove(mruFileList.size() - 1); - } - firePropertyChange(MRU_FILE_LIST_PROPERTY, null, mruFileList); - store(); - } - - /** - * Clear all existing MRU references in the preferences backing store. - */ - private void clear() { - Preferences prefs = getPreferences(); - - for (int i = 0; i < MAX_SIZE; i++) { - prefs.putString(MRU_FILE_LIST_PROPERTY + i, null); - } - } - - /** - * Store the MRU list into the preferences backing store. - */ - protected void store() { - Preferences prefs = getPreferences(); - - // clear the backing store - clear(); - - for (int i = 0; i < mruFileList.size(); i++) { - String str = mruFileList.get(i); - prefs.putString(MRU_FILE_LIST_PROPERTY + i, str); - } - } - - /** - * Load the MRU list from the backing store. - */ - protected void retrieve() { - mruFileList.clear(); - Preferences prefs = getPreferences(); - - for (int i = 0; i < MAX_SIZE; i++) { - String str = prefs.getString(MRU_FILE_LIST_PROPERTY + i, null); - if (str != null) { - mruFileList.add(str); - } - else { - break; - } - } - } - - /** - * {@inheritDoc} - */ - public void addPropertyChangeListener(PropertyChangeListener listener) { - listenerList.add(PropertyChangeListener.class, listener); - } - - /** - * {@inheritDoc} - */ - public void removePropertyChangeListener(PropertyChangeListener listener) { - listenerList.remove(PropertyChangeListener.class, listener); - } - - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - // Guaranteed to return a non-null array - Object[] listeners = listenerList.getListenerList(); - // Process the listeners last to first, notifying - // those that are interested in this event - PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, oldValue, newValue); - for (int i = listeners.length - 2; i >= 0; i -= 2) { - if (listeners[i] == PropertyChangeListener.class) { - ((PropertyChangeListener) listeners[i + 1]).propertyChange(event); - } - } - } - - /** - * Return the Preferences - * - * @return Preferences - */ - protected final Preferences getPreferences() { - return Application.getPreferences(); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/main/MRUDesignFileAction.java b/core/src/net/sf/openrocket/gui/main/MRUDesignFileAction.java deleted file mode 100644 index 8757eaa2..00000000 --- a/core/src/net/sf/openrocket/gui/main/MRUDesignFileAction.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.sf.openrocket.gui.main; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.List; - -/** - * Implements a menu for the Most-Recently-Used Open Rocket design files. - */ -public final class MRUDesignFileAction extends JMenu { - - /** - * The window to which an open design file action will be parented to (typically an instance of BasicFrame). - */ - private Window parent; - - /** - * Constructor. - * - * @param s the I18N menu string - * @param theParent the window to which an open design file action will be parented to (typically an instance of - * BasicFrame). - */ - public MRUDesignFileAction(String s, Window theParent) { - super(s); - - parent = theParent; - MRUDesignFile opts = MRUDesignFile.getInstance(); - opts.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - if (!evt.getPropertyName().equals(MRUDesignFile.MRU_FILE_LIST_PROPERTY)) { - return; - } - updateMenu(); - } - }); - - updateMenu(); - } - - /** - * Create menu items. - */ - private void updateMenu() { - removeAll(); - List list = MRUDesignFile.getInstance().getMRUFileList(); - for (String name : list) { - Action action = createAction(name); - action.putValue(Action.NAME, name); - JMenuItem menuItem = new JMenuItem(action); - add(menuItem); - } - } - - /** - * When a user clicks on one of the recently used design files, open it. - * - * @param file the design file name (absolute path) - * - * @return the action to open a design file - */ - private Action createAction(String file) { - Action action = new AbstractAction() { - public void actionPerformed(ActionEvent e) { - String command = e.getActionCommand(); - if (BasicFrame.open(new File(command), parent)) { - MRUDesignFile.getInstance().addFile(command); - } - else { - MRUDesignFile.getInstance().removeFile(command); - } - } - }; - - action.putValue(Action.ACTION_COMMAND_KEY, file); - return action; - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/main/OpenRocketClipboard.java b/core/src/net/sf/openrocket/gui/main/OpenRocketClipboard.java deleted file mode 100644 index 5541efb0..00000000 --- a/core/src/net/sf/openrocket/gui/main/OpenRocketClipboard.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.sf.openrocket.gui.main; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.rocketcomponent.RocketComponent; - -public final class OpenRocketClipboard { - - private static RocketComponent clipboardComponent = null; - private static Simulation[] clipboardSimulations = null; - - private static List listeners = new ArrayList(); - - private OpenRocketClipboard() { - // Disallow instantiation - } - - - /** - * Return the RocketComponent contained in the clipboard, or - * null. The component is returned verbatim, and must be copied - * before attaching to any rocket design! - * - * @return the rocket component contained in the clipboard, or null - * if the clipboard does not currently contain a rocket component. - */ - public static RocketComponent getClipboardComponent() { - return clipboardComponent; - } - - - public static void setClipboard(RocketComponent component) { - clipboardComponent = component; - clipboardSimulations = null; - fireClipboardChanged(); - } - - - public static Simulation[] getClipboardSimulations() { - if (clipboardSimulations == null || clipboardSimulations.length == 0) - return null; - return clipboardSimulations.clone(); - } - - public static void setClipboard(Simulation[] simulations) { - clipboardSimulations = simulations.clone(); - clipboardComponent = null; - fireClipboardChanged(); - } - - - - public static void addClipboardListener(ClipboardListener listener) { - listeners.add(listener); - } - - public static void removeClipboardListener(ClipboardListener listener) { - listeners.remove(listener); - } - - private static void fireClipboardChanged() { - ClipboardListener[] array = listeners.toArray(new ClipboardListener[0]); - for (ClipboardListener l: array) { - l.clipboardChanged(); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/main/RocketActions.java b/core/src/net/sf/openrocket/gui/main/RocketActions.java deleted file mode 100644 index a8da9c7e..00000000 --- a/core/src/net/sf/openrocket/gui/main/RocketActions.java +++ /dev/null @@ -1,705 +0,0 @@ -package net.sf.openrocket.gui.main; - - -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.util.ArrayList; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JCheckBox; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.KeyStroke; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.configdialog.ComponentConfigDialog; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; -import net.sf.openrocket.util.Pair; - - - -/** - * A class that holds Actions for common rocket and simulation operations such as - * cut/copy/paste/delete etc. - * - * @author Sampo Niskanen - */ -public class RocketActions { - - public static final KeyStroke CUT_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_X, - ActionEvent.CTRL_MASK); - public static final KeyStroke COPY_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_C, - ActionEvent.CTRL_MASK); - public static final KeyStroke PASTE_KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_V, - ActionEvent.CTRL_MASK); - - private final OpenRocketDocument document; - private final Rocket rocket; - private final BasicFrame parentFrame; - private final DocumentSelectionModel selectionModel; - - - private final RocketAction deleteComponentAction; - private final RocketAction deleteSimulationAction; - private final RocketAction deleteAction; - private final RocketAction cutAction; - private final RocketAction copyAction; - private final RocketAction pasteAction; - private final RocketAction editAction; - private final RocketAction newStageAction; - private final RocketAction moveUpAction; - private final RocketAction moveDownAction; - private static final Translator trans = Application.getTranslator(); - - - public RocketActions(OpenRocketDocument document, DocumentSelectionModel selectionModel, - BasicFrame parentFrame) { - this.document = document; - this.rocket = document.getRocket(); - this.selectionModel = selectionModel; - this.parentFrame = parentFrame; - - // Add action also to updateActions() - this.deleteAction = new DeleteAction(); - this.deleteComponentAction = new DeleteComponentAction(); - this.deleteSimulationAction = new DeleteSimulationAction(); - this.cutAction = new CutAction(); - this.copyAction = new CopyAction(); - this.pasteAction = new PasteAction(); - this.editAction = new EditAction(); - this.newStageAction = new NewStageAction(); - this.moveUpAction = new MoveUpAction(); - this.moveDownAction = new MoveDownAction(); - - OpenRocketClipboard.addClipboardListener(this.pasteAction); - updateActions(); - - // Update all actions when tree selection or rocket changes - - selectionModel.addDocumentSelectionListener(new DocumentSelectionListener() { - @Override - public void valueChanged(int changeType) { - updateActions(); - } - }); - document.getRocket().addComponentChangeListener(new ComponentChangeListener() { - @Override - public void componentChanged(ComponentChangeEvent e) { - updateActions(); - } - }); - } - - /** - * Update the state of all of the actions. - */ - private void updateActions() { - deleteAction.clipboardChanged(); - cutAction.clipboardChanged(); - copyAction.clipboardChanged(); - pasteAction.clipboardChanged(); - editAction.clipboardChanged(); - newStageAction.clipboardChanged(); - moveUpAction.clipboardChanged(); - moveDownAction.clipboardChanged(); - } - - - - - public Action getDeleteComponentAction() { - return deleteAction; - } - - public Action getDeleteSimulationAction() { - return deleteAction; - } - - public Action getDeleteAction() { - return deleteAction; - } - - public Action getCutAction() { - return cutAction; - } - - public Action getCopyAction() { - return copyAction; - } - - public Action getPasteAction() { - return pasteAction; - } - - public Action getEditAction() { - return editAction; - } - - public Action getNewStageAction() { - return newStageAction; - } - - public Action getMoveUpAction() { - return moveUpAction; - } - - public Action getMoveDownAction() { - return moveDownAction; - } - - - - //////// Helper methods for the actions - - private boolean isDeletable(RocketComponent c) { - // Sanity check - if (c == null || c.getParent() == null) - return false; - - // Cannot remove Rocket - if (c instanceof Rocket) - return false; - - // Cannot remove last stage - if ((c instanceof Stage) && (c.getParent().getChildCount() == 1)) { - return false; - } - - return true; - } - - private void delete(RocketComponent c) { - if (!isDeletable(c)) { - throw new IllegalArgumentException("Report bug! Component " + c + - " not deletable."); - } - - RocketComponent parent = c.getParent(); - parent.removeChild(c); - } - - private boolean isCopyable(RocketComponent c) { - if (c==null) - return false; - if (c instanceof Rocket) - return false; - return true; - } - - - private boolean isSimulationSelected() { - Simulation[] selection = selectionModel.getSelectedSimulations(); - return (selection != null && selection.length > 0); - } - - - - private boolean verifyDeleteSimulation() { - boolean verify = Application.getPreferences().getBoolean(Preferences.CONFIRM_DELETE_SIMULATION, true); - if (verify) { - JPanel panel = new JPanel(new MigLayout()); - //// Do not ask me again - JCheckBox dontAsk = new JCheckBox(trans.get("RocketActions.checkbox.Donotaskmeagain")); - panel.add(dontAsk,"wrap"); - //// You can change the default operation in the preferences. - panel.add(new StyledLabel(trans.get("RocketActions.lbl.Youcanchangedefop"),-2)); - - int ret = JOptionPane.showConfirmDialog( - parentFrame, - new Object[] { - //// Delete the selected simulations? - trans.get("RocketActions.showConfirmDialog.lbl1"), - //// This operation cannot be undone. - trans.get("RocketActions.showConfirmDialog.lbl2"), - "", - panel }, - //// Delete simulations - trans.get("RocketActions.showConfirmDialog.title"), - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE); - if (ret != JOptionPane.OK_OPTION) - return false; - - if (dontAsk.isSelected()) { - Application.getPreferences().putBoolean(Preferences.CONFIRM_DELETE_SIMULATION, false); - } - } - - return true; - } - - - /** - * Return the component and position to which the current clipboard - * should be pasted. Returns null if the clipboard is empty or if the - * clipboard cannot be pasted to the current selection. - * - * @param clipboard the component on the clipboard. - * @return a Pair with both components defined, or null. - */ - private Pair getPastePosition(RocketComponent clipboard) { - RocketComponent selected = selectionModel.getSelectedComponent(); - if (selected == null) - return null; - - if (clipboard == null) - return null; - - if (selected.isCompatible(clipboard)) - return new Pair(selected, selected.getChildCount()); - - RocketComponent parent = selected.getParent(); - if (parent != null && parent.isCompatible(clipboard)) { - int index = parent.getChildPosition(selected) + 1; - return new Pair(parent, index); - } - - return null; - } - - - - - - /////// Action classes - - private abstract class RocketAction extends AbstractAction implements ClipboardListener { - public abstract void clipboardChanged(); - } - - - /** - * Action that deletes the selected component. - */ - private class DeleteComponentAction extends RocketAction { - public DeleteComponentAction() { - //// Delete - this.putValue(NAME, trans.get("RocketActions.DelCompAct.Delete")); - //// Delete the selected component. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.DelCompAct.ttip.Delete")); - this.putValue(MNEMONIC_KEY, KeyEvent.VK_D); -// this.putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); - this.putValue(SMALL_ICON, Icons.EDIT_DELETE); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent c = selectionModel.getSelectedComponent(); - - if (isDeletable(c)) { - ComponentConfigDialog.hideDialog(); - - document.addUndoPosition("Delete " + c.getComponentName()); - delete(c); - } - } - - @Override - public void clipboardChanged() { - this.setEnabled(isDeletable(selectionModel.getSelectedComponent())); - } - } - - - - /** - * Action that deletes the selected component. - */ - private class DeleteSimulationAction extends RocketAction { - public DeleteSimulationAction() { - //// Delete - this.putValue(NAME, trans.get("RocketActions.DelSimuAct.Delete")); - //// Delete the selected simulation. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.DelSimuAct.ttip.Delete")); - this.putValue(MNEMONIC_KEY, KeyEvent.VK_D); -// this.putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); - this.putValue(SMALL_ICON, Icons.EDIT_DELETE); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - Simulation[] sims = selectionModel.getSelectedSimulations(); - if (sims.length > 0) { - if (verifyDeleteSimulation()) { - for (Simulation s: sims) { - document.removeSimulation(s); - } - } - } - } - - @Override - public void clipboardChanged() { - this.setEnabled(isSimulationSelected()); - } - } - - - - /** - * Action that deletes the selected component. - */ - private class DeleteAction extends RocketAction { - public DeleteAction() { - //// Delete - this.putValue(NAME, trans.get("RocketActions.DelAct.Delete")); - //// Delete the selected component or simulation. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.DelAct.ttip.Delete")); - this.putValue(MNEMONIC_KEY, KeyEvent.VK_D); - this.putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); - this.putValue(SMALL_ICON, Icons.EDIT_DELETE); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - if (isSimulationSelected()) { - deleteSimulationAction.actionPerformed(e); - parentFrame.selectTab(BasicFrame.SIMULATION_TAB); - } else { - deleteComponentAction.actionPerformed(e); - parentFrame.selectTab(BasicFrame.COMPONENT_TAB); - } - } - - @Override - public void clipboardChanged() { - this.setEnabled(isDeletable(selectionModel.getSelectedComponent()) || - isSimulationSelected()); - } - } - - - - /** - * Action the cuts the selected component (copies to clipboard and deletes). - */ - private class CutAction extends RocketAction { - public CutAction() { - //// Cut - this.putValue(NAME, trans.get("RocketActions.CutAction.Cut")); - this.putValue(MNEMONIC_KEY, KeyEvent.VK_T); - this.putValue(ACCELERATOR_KEY, CUT_KEY_STROKE); - //// Cut this component or simulation to the clipboard and remove from this design - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.CutAction.ttip.Cut")); - this.putValue(SMALL_ICON, Icons.EDIT_CUT); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent c = selectionModel.getSelectedComponent(); - Simulation[] sims = selectionModel.getSelectedSimulations(); - - if (isDeletable(c) && isCopyable(c)) { - ComponentConfigDialog.hideDialog(); - - document.addUndoPosition("Cut " + c.getComponentName()); - OpenRocketClipboard.setClipboard(c.copy()); - delete(c); - parentFrame.selectTab(BasicFrame.COMPONENT_TAB); - } else if (isSimulationSelected()) { - - Simulation[] simsCopy = new Simulation[sims.length]; - for (int i=0; i < sims.length; i++) { - simsCopy[i] = sims[i].copy(); - } - OpenRocketClipboard.setClipboard(simsCopy); - - for (Simulation s: sims) { - document.removeSimulation(s); - } - parentFrame.selectTab(BasicFrame.SIMULATION_TAB); - } - } - - @Override - public void clipboardChanged() { - RocketComponent c = selectionModel.getSelectedComponent(); - this.setEnabled((isDeletable(c) && isCopyable(c)) || isSimulationSelected()); - } - } - - - - /** - * Action that copies the selected component to the clipboard. - */ - private class CopyAction extends RocketAction { - public CopyAction() { - //// Copy - this.putValue(NAME, trans.get("RocketActions.CopyAct.Copy")); - this.putValue(MNEMONIC_KEY, KeyEvent.VK_C); - this.putValue(ACCELERATOR_KEY, COPY_KEY_STROKE); - //// Copy this component (and subcomponents) to the clipboard. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.CopyAct.Copy")); - this.putValue(SMALL_ICON, Icons.EDIT_COPY); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent c = selectionModel.getSelectedComponent(); - Simulation[] sims = selectionModel.getSelectedSimulations(); - - if (isCopyable(c)) { - OpenRocketClipboard.setClipboard(c.copy()); - parentFrame.selectTab(BasicFrame.COMPONENT_TAB); - } else if (sims.length >= 0) { - - Simulation[] simsCopy = new Simulation[sims.length]; - for (int i=0; i < sims.length; i++) { - simsCopy[i] = sims[i].copy(); - } - OpenRocketClipboard.setClipboard(simsCopy); - parentFrame.selectTab(BasicFrame.SIMULATION_TAB); - } - } - - @Override - public void clipboardChanged() { - this.setEnabled(isCopyable(selectionModel.getSelectedComponent()) || - isSimulationSelected()); - } - - } - - - - /** - * Action that pastes the current clipboard to the selected position. - * It first tries to paste the component to the end of the selected component - * as a child, and after that as a sibling after the selected component. - */ - private class PasteAction extends RocketAction { - public PasteAction() { - //// Paste - this.putValue(NAME, trans.get("RocketActions.PasteAct.Paste")); - this.putValue(MNEMONIC_KEY, KeyEvent.VK_P); - this.putValue(ACCELERATOR_KEY, PASTE_KEY_STROKE); - //// Paste the component or simulation on the clipboard to the design. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.PasteAct.ttip.Paste")); - this.putValue(SMALL_ICON, Icons.EDIT_PASTE); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent clipboard = OpenRocketClipboard.getClipboardComponent(); - Simulation[] sims = OpenRocketClipboard.getClipboardSimulations(); - - Pair position = getPastePosition(clipboard); - if (position != null) { - ComponentConfigDialog.hideDialog(); - - RocketComponent pasted = clipboard.copy(); - document.addUndoPosition("Paste " + pasted.getComponentName()); - position.getU().addChild(pasted, position.getV()); - selectionModel.setSelectedComponent(pasted); - - parentFrame.selectTab(BasicFrame.COMPONENT_TAB); - - } else if (sims != null) { - - ArrayList copySims = new ArrayList(); - - for (Simulation s: sims) { - Simulation copy = s.duplicateSimulation(rocket); - String name = copy.getName(); - if (name.matches(OpenRocketDocument.SIMULATION_NAME_PREFIX + "[0-9]+ *")) { - copy.setName(document.getNextSimulationName()); - } - document.addSimulation(copy); - copySims.add(copy); - } - selectionModel.setSelectedSimulations(copySims.toArray(new Simulation[0])); - - parentFrame.selectTab(BasicFrame.SIMULATION_TAB); - } - } - - @Override - public void clipboardChanged() { - this.setEnabled( - (getPastePosition(OpenRocketClipboard.getClipboardComponent()) != null) || - (OpenRocketClipboard.getClipboardSimulations() != null)); - } - } - - - - - - - /** - * Action to edit the currently selected component. - */ - private class EditAction extends RocketAction { - public EditAction() { - //// Edit - this.putValue(NAME, trans.get("RocketActions.EditAct.Edit")); - //// Edit the selected component. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.EditAct.ttip.Edit")); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent c = selectionModel.getSelectedComponent(); - if (c == null) - return; - - ComponentConfigDialog.showDialog(parentFrame, document, c); - } - - @Override - public void clipboardChanged() { - this.setEnabled(selectionModel.getSelectedComponent() != null); - } - } - - - - - - - - /** - * Action to add a new stage to the rocket. - */ - private class NewStageAction extends RocketAction { - public NewStageAction() { - //// New stage - this.putValue(NAME, trans.get("RocketActions.NewStageAct.Newstage")); - //// Add a new stage to the rocket design. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.NewStageAct.Newstage")); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - - ComponentConfigDialog.hideDialog(); - - RocketComponent stage = new Stage(); - //// Booster stage - stage.setName(trans.get("RocketActions.ActBoosterstage")); - //// Add stage - document.addUndoPosition("Add stage"); - rocket.addChild(stage); - rocket.getDefaultConfiguration().setAllStages(); - selectionModel.setSelectedComponent(stage); - ComponentConfigDialog.showDialog(parentFrame, document, stage); - - } - - @Override - public void clipboardChanged() { - this.setEnabled(true); - } - } - - - - - /** - * Action to move the selected component upwards in the parent's child list. - */ - private class MoveUpAction extends RocketAction { - public MoveUpAction() { - //// Move up - this.putValue(NAME, trans.get("RocketActions.MoveUpAct.Moveup")); - //// Move this component upwards. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.MoveUpAct.ttip.Moveup")); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent selected = selectionModel.getSelectedComponent(); - if (!canMove(selected)) - return; - - ComponentConfigDialog.hideDialog(); - - RocketComponent parent = selected.getParent(); - document.addUndoPosition("Move "+selected.getComponentName()); - parent.moveChild(selected, parent.getChildPosition(selected)-1); - selectionModel.setSelectedComponent(selected); - } - - @Override - public void clipboardChanged() { - this.setEnabled(canMove(selectionModel.getSelectedComponent())); - } - - private boolean canMove(RocketComponent c) { - if (c == null || c.getParent() == null) - return false; - RocketComponent parent = c.getParent(); - if (parent.getChildPosition(c) > 0) - return true; - return false; - } - } - - - - /** - * Action to move the selected component down in the parent's child list. - */ - private class MoveDownAction extends RocketAction { - public MoveDownAction() { - //// Move down - this.putValue(NAME, trans.get("RocketActions.MoveDownAct.Movedown")); - //// Move this component downwards. - this.putValue(SHORT_DESCRIPTION, trans.get("RocketActions.MoveDownAct.ttip.Movedown")); - clipboardChanged(); - } - - @Override - public void actionPerformed(ActionEvent e) { - RocketComponent selected = selectionModel.getSelectedComponent(); - if (!canMove(selected)) - return; - - ComponentConfigDialog.hideDialog(); - - RocketComponent parent = selected.getParent(); - document.addUndoPosition("Move "+selected.getComponentName()); - parent.moveChild(selected, parent.getChildPosition(selected)+1); - selectionModel.setSelectedComponent(selected); - } - - @Override - public void clipboardChanged() { - this.setEnabled(canMove(selectionModel.getSelectedComponent())); - } - - private boolean canMove(RocketComponent c) { - if (c == null || c.getParent() == null) - return false; - RocketComponent parent = c.getParent(); - if (parent.getChildPosition(c) < parent.getChildCount()-1) - return true; - return false; - } - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/main/SimulationEditDialog.java b/core/src/net/sf/openrocket/gui/main/SimulationEditDialog.java deleted file mode 100644 index 35c72db6..00000000 --- a/core/src/net/sf/openrocket/gui/main/SimulationEditDialog.java +++ /dev/null @@ -1,1056 +0,0 @@ -package net.sf.openrocket.gui.main; - - -import java.awt.Color; -import java.awt.Component; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Arrays; -import java.util.List; - -import javax.swing.AbstractListModel; -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.ListCellRenderer; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.BooleanModel; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.EnumModel; -import net.sf.openrocket.gui.adaptors.MotorConfigurationModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.SimulationExportPanel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.plot.Axis; -import net.sf.openrocket.gui.plot.PlotConfiguration; -import net.sf.openrocket.gui.plot.SimulationPlotPanel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.models.atmosphere.ExtendedISAModel; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.RK4SimulationStepper; -import net.sf.openrocket.simulation.SimulationOptions; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.example.CSVSaveListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.GeodeticComputationStrategy; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.axis.NumberAxis; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.ValueMarker; -import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.renderer.xy.StandardXYItemRenderer; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; - - -public class SimulationEditDialog extends JDialog { - - public static final int DEFAULT = -1; - public static final int EDIT = 1; - public static final int PLOT = 2; - - - private final Window parentWindow; - private final Simulation simulation; - private final OpenRocketDocument document; - private final SimulationOptions conditions; - private final Configuration configuration; - private static final Translator trans = Application.getTranslator(); - - - public SimulationEditDialog(Window parent, OpenRocketDocument document, Simulation s) { - this(parent, document, s, 0); - } - - public SimulationEditDialog(Window parent, OpenRocketDocument document, Simulation s, int tab) { - //// Edit simulation - super(parent, trans.get("simedtdlg.title.Editsim"), JDialog.ModalityType.DOCUMENT_MODAL); - this.document = document; - this.parentWindow = parent; - this.simulation = s; - this.conditions = simulation.getOptions(); - configuration = simulation.getConfiguration(); - - JPanel mainPanel = new JPanel(new MigLayout("fill", "[grow, fill]")); - - //// Simulation name: - mainPanel.add(new JLabel(trans.get("simedtdlg.lbl.Simname") + " "), "span, split 2, shrink"); - final JTextField field = new JTextField(simulation.getName()); - field.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void changedUpdate(DocumentEvent e) { - setText(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - setText(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - setText(); - } - - private void setText() { - String name = field.getText(); - if (name == null || name.equals("")) - return; - //System.out.println("Setting name:" + name); - simulation.setName(name); - - } - }); - mainPanel.add(field, "shrinky, growx, wrap"); - - JTabbedPane tabbedPane = new JTabbedPane(); - - //// Launch conditions - tabbedPane.addTab(trans.get("simedtdlg.tab.Launchcond"), flightConditionsTab()); - //// Simulation options - tabbedPane.addTab(trans.get("simedtdlg.tab.Simopt"), simulationOptionsTab()); - //// Plot data - tabbedPane.addTab(trans.get("simedtdlg.tab.Plotdata"), plotTab()); - //// Export data - tabbedPane.addTab(trans.get("simedtdlg.tab.Exportdata"), exportTab()); - - // Select the initial tab - if (tab == EDIT) { - tabbedPane.setSelectedIndex(0); - } else if (tab == PLOT) { - tabbedPane.setSelectedIndex(2); - } else { - FlightData data = s.getSimulatedData(); - if (data == null || data.getBranchCount() == 0) - tabbedPane.setSelectedIndex(0); - else - tabbedPane.setSelectedIndex(2); - } - - mainPanel.add(tabbedPane, "spanx, grow, wrap"); - - - // Buttons - mainPanel.add(new JPanel(), "spanx, split, growx"); - - JButton button; - //// Run simulation button - button = new JButton(trans.get("simedtdlg.but.runsimulation")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SimulationEditDialog.this.dispose(); - SimulationRunDialog.runSimulations(parentWindow, SimulationEditDialog.this.document, simulation); - } - }); - mainPanel.add(button, "gapright para"); - - //// Close button - JButton close = new JButton(trans.get("dlg.but.close")); - close.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SimulationEditDialog.this.dispose(); - } - }); - mainPanel.add(close, ""); - - - this.add(mainPanel); - this.validate(); - this.pack(); - this.setLocationByPlatform(true); - - GUIUtil.setDisposableDialogOptions(this, button); - } - - - - - - private JPanel flightConditionsTab() { - JPanel panel = new JPanel(new MigLayout("fill")); - JPanel sub; - String tip; - UnitSelector unit; - BasicSlider slider; - DoubleModel m; - JSpinner spin; - - //// Motor selector - //// Motor configuration: - JLabel label = new JLabel(trans.get("simedtdlg.lbl.Motorcfg")); - //// Select the motor configuration to use. - label.setToolTipText(trans.get("simedtdlg.lbl.ttip.Motorcfg")); - panel.add(label, "shrinkx, spanx, split 2"); - - JComboBox combo = new JComboBox(new MotorConfigurationModel(configuration)); - //// Select the motor configuration to use. - combo.setToolTipText(trans.get("simedtdlg.combo.ttip.motorconf")); - combo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - conditions.setMotorConfigurationID(configuration.getMotorConfigurationID()); - } - }); - panel.add(combo, "growx, wrap para"); - - - //// Wind settings: Average wind speed, turbulence intensity, std. deviation - sub = new JPanel(new MigLayout("fill, gap rel unrel", - "[grow][65lp!][30lp!][75lp!]", "")); - //// Wind - sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.lbl.Wind"))); - panel.add(sub, "growx, split 2, aligny 0, flowy, gapright para"); - - - // Wind average - //// Average windspeed: - label = new JLabel(trans.get("simedtdlg.lbl.Averwindspeed")); - //// The average windspeed relative to the ground. - tip = trans.get("simedtdlg.lbl.ttip.Averwindspeed"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "WindSpeedAverage", UnitGroup.UNITS_WINDSPEED, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(0, 10.0)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - - // Wind std. deviation - //// Standard deviation: - label = new JLabel(trans.get("simedtdlg.lbl.Stddeviation")); - //// The standard deviation of the windspeed.
- //// The windspeed is within twice the standard deviation from the average for 95% of the time. - tip = trans.get("simedtdlg.lbl.ttip.Stddeviation"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "WindSpeedDeviation", UnitGroup.UNITS_WINDSPEED, 0); - DoubleModel m2 = new DoubleModel(conditions, "WindSpeedAverage", 0.25, - UnitGroup.UNITS_COEFFICIENT, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(new DoubleModel(0), m2)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - // Wind turbulence intensity - //// Turbulence intensity: - label = new JLabel(trans.get("simedtdlg.lbl.Turbulenceintensity")); - //// The turbulence intensity is the standard deviation divided by the average windspeed.
- //// Typical values range from - //// to - tip = trans.get("simedtdlg.lbl.ttip.Turbulenceintensity1") + - trans.get("simedtdlg.lbl.ttip.Turbulenceintensity2") + " " + - UnitGroup.UNITS_RELATIVE.getDefaultUnit().toStringUnit(0.05) + - " " + trans.get("simedtdlg.lbl.ttip.Turbulenceintensity3") + " " + - UnitGroup.UNITS_RELATIVE.getDefaultUnit().toStringUnit(0.20) + "."; - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "WindTurbulenceIntensity", UnitGroup.UNITS_RELATIVE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - - final JLabel intensityLabel = new JLabel( - getIntensityDescription(conditions.getWindTurbulenceIntensity())); - intensityLabel.setToolTipText(tip); - sub.add(intensityLabel, "w 75lp, wrap"); - m.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - intensityLabel.setText( - getIntensityDescription(conditions.getWindTurbulenceIntensity())); - } - }); - - - - - - //// Temperature and pressure - sub = new JPanel(new MigLayout("fill, gap rel unrel", - "[grow][65lp!][30lp!][75lp!]", "")); - //// Atmospheric conditions - sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Atmoscond"))); - panel.add(sub, "growx, aligny 0, gapright para"); - - - BooleanModel isa = new BooleanModel(conditions, "ISAAtmosphere"); - JCheckBox check = new JCheckBox(isa); - //// Use International Standard Atmosphere - check.setText(trans.get("simedtdlg.checkbox.InterStdAtmosphere")); - //// Select to use the International Standard Atmosphere model. - ////
This model has a temperature of - //// and a pressure of - //// at sea level. - check.setToolTipText(trans.get("simedtdlg.checkbox.ttip.InterStdAtmosphere1") + " " + - UnitGroup.UNITS_TEMPERATURE.toStringUnit(ExtendedISAModel.STANDARD_TEMPERATURE) + - " " + trans.get("simedtdlg.checkbox.ttip.InterStdAtmosphere2") + " " + - UnitGroup.UNITS_PRESSURE.toStringUnit(ExtendedISAModel.STANDARD_PRESSURE) + - " " + trans.get("simedtdlg.checkbox.ttip.InterStdAtmosphere3")); - sub.add(check, "spanx, wrap unrel"); - - // Temperature: - label = new JLabel(trans.get("simedtdlg.lbl.Temperature")); - //// The temperature at the launch site. - tip = trans.get("simedtdlg.lbl.ttip.Temperature"); - label.setToolTipText(tip); - isa.addEnableComponent(label, false); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchTemperature", UnitGroup.UNITS_TEMPERATURE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - isa.addEnableComponent(spin, false); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - isa.addEnableComponent(unit, false); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(253.15, 308.15)); // -20 ... 35 - slider.setToolTipText(tip); - isa.addEnableComponent(slider, false); - sub.add(slider, "w 75lp, wrap"); - - - - // Pressure: - label = new JLabel(trans.get("simedtdlg.lbl.Pressure")); - //// The atmospheric pressure at the launch site. - tip = trans.get("simedtdlg.lbl.ttip.Pressure"); - label.setToolTipText(tip); - isa.addEnableComponent(label, false); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchPressure", UnitGroup.UNITS_PRESSURE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - isa.addEnableComponent(spin, false); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - isa.addEnableComponent(unit, false); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(0.950e5, 1.050e5)); - slider.setToolTipText(tip); - isa.addEnableComponent(slider, false); - sub.add(slider, "w 75lp, wrap"); - - - - - - //// Launch site conditions - sub = new JPanel(new MigLayout("fill, gap rel unrel", - "[grow][65lp!][30lp!][75lp!]", "")); - //// Launch site - sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.lbl.Launchsite"))); - panel.add(sub, "growx, split 2, aligny 0, flowy"); - - - // Latitude: - label = new JLabel(trans.get("simedtdlg.lbl.Latitude")); - //// The launch site latitude affects the gravitational pull of Earth.
- //// Positive values are on the Northern hemisphere, negative values on the Southern hemisphere. - tip = trans.get("simedtdlg.lbl.ttip.Latitude"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchLatitude", UnitGroup.UNITS_NONE, -90, 90); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - label = new JLabel(Chars.DEGREE + " N"); - label.setToolTipText(tip); - sub.add(label, "growx"); - slider = new BasicSlider(m.getSliderModel(-90, 90)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - // Longitude: - label = new JLabel(trans.get("simedtdlg.lbl.Longitude")); - tip = trans.get("simedtdlg.lbl.ttip.Longitude"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchLongitude", UnitGroup.UNITS_NONE, -180, 180); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - label = new JLabel(Chars.DEGREE + " E"); - label.setToolTipText(tip); - sub.add(label, "growx"); - slider = new BasicSlider(m.getSliderModel(-180, 180)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - // Altitude: - label = new JLabel(trans.get("simedtdlg.lbl.Altitude")); - //// The launch altitude above mean sea level.
- //// This affects the position of the rocket in the atmospheric model. - tip = trans.get("simedtdlg.lbl.ttip.Altitude"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchAltitude", UnitGroup.UNITS_DISTANCE, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(0, 250, 1000)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - - - - //// Launch rod - sub = new JPanel(new MigLayout("fill, gap rel unrel", - "[grow][65lp!][30lp!][75lp!]", "")); - //// Launch rod - sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Launchrod"))); - panel.add(sub, "growx, aligny 0, wrap"); - - - // Length: - label = new JLabel(trans.get("simedtdlg.lbl.Length")); - //// The length of the launch rod. - tip = trans.get("simedtdlg.lbl.ttip.Length"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchRodLength", UnitGroup.UNITS_LENGTH, 0); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(0, 1, 5)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - - // Angle: - label = new JLabel(trans.get("simedtdlg.lbl.Angle")); - //// The angle of the launch rod from vertical. - tip = trans.get("simedtdlg.lbl.ttip.Angle"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchRodAngle", UnitGroup.UNITS_ANGLE, - 0, SimulationOptions.MAX_LAUNCH_ROD_ANGLE); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(0, Math.PI / 9, - SimulationOptions.MAX_LAUNCH_ROD_ANGLE)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - - - // Direction: - label = new JLabel(trans.get("simedtdlg.lbl.Direction")); - //// Direction of the launch rod relative to the wind.
- //// = towards the wind, - //// = downwind. - tip = trans.get("simedtdlg.lbl.ttip.Direction1") + - UnitGroup.UNITS_ANGLE.toStringUnit(0) + - " " + trans.get("simedtdlg.lbl.ttip.Direction2") + " " + - UnitGroup.UNITS_ANGLE.toStringUnit(Math.PI) + - " " + trans.get("simedtdlg.lbl.ttip.Direction3"); - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "LaunchRodDirection", UnitGroup.UNITS_ANGLE, - -Math.PI, Math.PI); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "growx"); - slider = new BasicSlider(m.getSliderModel(-Math.PI, Math.PI)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - - return panel; - } - - - private String getIntensityDescription(double i) { - if (i < 0.001) - //// None - return trans.get("simedtdlg.IntensityDesc.None"); - if (i < 0.05) - //// Very low - return trans.get("simedtdlg.IntensityDesc.Verylow"); - if (i < 0.10) - //// Low - return trans.get("simedtdlg.IntensityDesc.Low"); - if (i < 0.15) - //// Medium - return trans.get("simedtdlg.IntensityDesc.Medium"); - if (i < 0.20) - //// High - return trans.get("simedtdlg.IntensityDesc.High"); - if (i < 0.25) - //// Very high - return trans.get("simedtdlg.IntensityDesc.Veryhigh"); - //// Extreme - return trans.get("simedtdlg.IntensityDesc.Extreme"); - } - - - - private JPanel simulationOptionsTab() { - JPanel panel = new JPanel(new MigLayout("fill")); - JPanel sub, subsub; - String tip; - JLabel label; - DoubleModel m; - JSpinner spin; - UnitSelector unit; - BasicSlider slider; - - - //// Simulation options - sub = new JPanel(new MigLayout("fill, gap rel unrel", - "[grow][65lp!][30lp!][75lp!]", "")); - //// Simulator options - sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Simopt"))); - panel.add(sub, "growx, growy, aligny 0"); - - - // Separate panel for computation methods, as they use a different layout - subsub = new JPanel(new MigLayout("insets 0, fill")); - - - //// Calculation method: - tip = trans.get("simedtdlg.lbl.ttip.Calcmethod"); - label = new JLabel(trans.get("simedtdlg.lbl.Calcmethod")); - label.setToolTipText(tip); - subsub.add(label, "gapright para"); - - //// Extended Barrowman - label = new JLabel(trans.get("simedtdlg.lbl.ExtBarrowman")); - label.setToolTipText(tip); - subsub.add(label, "growx, wrap para"); - - - // Simulation method - tip = trans.get("simedtdlg.lbl.ttip.Simmethod1") + - trans.get("simedtdlg.lbl.ttip.Simmethod2"); - label = new JLabel(trans.get("simedtdlg.lbl.Simmethod")); - label.setToolTipText(tip); - subsub.add(label, "gapright para"); - - label = new JLabel("6-DOF Runge-Kutta 4"); - label.setToolTipText(tip); - subsub.add(label, "growx, wrap para"); - - - //// Geodetic calculation method: - label = new JLabel(trans.get("simedtdlg.lbl.GeodeticMethod")); - label.setToolTipText(trans.get("simedtdlg.lbl.ttip.GeodeticMethodTip")); - subsub.add(label, "gapright para"); - - EnumModel gcsModel = new EnumModel(conditions, "GeodeticComputation"); - final JComboBox gcsCombo = new JComboBox(gcsModel); - ActionListener gcsTTipListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - GeodeticComputationStrategy gcs = (GeodeticComputationStrategy) gcsCombo.getSelectedItem(); - gcsCombo.setToolTipText(gcs.getDescription()); - } - }; - gcsCombo.addActionListener(gcsTTipListener); - gcsTTipListener.actionPerformed(null); - subsub.add(gcsCombo, "growx, wrap para"); - - sub.add(subsub, "spanx, wrap para"); - - - //// Time step: - label = new JLabel(trans.get("simedtdlg.lbl.Timestep")); - tip = trans.get("simedtdlg.lbl.ttip.Timestep1") + - trans.get("simedtdlg.lbl.ttip.Timestep2") + " " + - UnitGroup.UNITS_TIME_STEP.toStringUnit(RK4SimulationStepper.RECOMMENDED_TIME_STEP) + - "."; - label.setToolTipText(tip); - sub.add(label); - - m = new DoubleModel(conditions, "TimeStep", UnitGroup.UNITS_TIME_STEP, 0, 1); - - spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - spin.setToolTipText(tip); - sub.add(spin, "w 65lp!"); - //sub.add(spin, "nogrid"); - - unit = new UnitSelector(m); - unit.setToolTipText(tip); - sub.add(unit, "w 25"); - //sub.add(unit, "nogrid"); - slider = new BasicSlider(m.getSliderModel(0, 0.2)); - slider.setToolTipText(tip); - sub.add(slider, "w 75lp, wrap"); - //sub.add(slider,"wrap"); - - - - - //// Reset to default button - JButton button = new JButton(trans.get("simedtdlg.but.resettodefault")); - //// Reset the time step to its default value ( - button.setToolTipText(trans.get("simedtdlg.but.ttip.resettodefault") + - UnitGroup.UNITS_SHORT_TIME.toStringUnit(RK4SimulationStepper.RECOMMENDED_TIME_STEP) + - ")."); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - conditions.setTimeStep(RK4SimulationStepper.RECOMMENDED_TIME_STEP); - conditions.setGeodeticComputation(GeodeticComputationStrategy.SPHERICAL); - } - }); - - sub.add(button, "align left"); - - - - - //// Simulation listeners - sub = new JPanel(new MigLayout("fill, gap 0 0")); - //// Simulator listeners - sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Simlist"))); - panel.add(sub, "growx, growy"); - - - DescriptionArea desc = new DescriptionArea(5); - //// Simulation listeners is an advanced feature that allows user-written code to listen to and interact with the simulation. - //// For details on writing simulation listeners, see the OpenRocket technical documentation. - desc.setText(trans.get("simedtdlg.txt.longA1") + - trans.get("simedtdlg.txt.longA2")); - sub.add(desc, "aligny 0, growx, wrap para"); - - //// Current listeners: - label = new JLabel(trans.get("simedtdlg.lbl.Curlist")); - sub.add(label, "spanx, wrap rel"); - - final ListenerListModel listenerModel = new ListenerListModel(); - final JList list = new JList(listenerModel); - list.setCellRenderer(new ListenerCellRenderer()); - JScrollPane scroll = new JScrollPane(list); - // scroll.setPreferredSize(new Dimension(1,1)); - sub.add(scroll, "height 1px, grow, wrap rel"); - - //// Add button - button = new JButton(trans.get("simedtdlg.but.add")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String previous = Application.getPreferences().getString("previousListenerName", ""); - String input = (String) JOptionPane.showInputDialog(SimulationEditDialog.this, - new Object[] { - //// Type the full Java class name of the simulation listener, for example: - "Type the full Java class name of the simulation listener, for example:", - "" + CSVSaveListener.class.getName() + "" }, - //// Add simulation listener - trans.get("simedtdlg.lbl.Addsimlist"), - JOptionPane.QUESTION_MESSAGE, - null, null, - previous - ); - if (input == null || input.equals("")) - return; - - Application.getPreferences().putString("previousListenerName", input); - simulation.getSimulationListeners().add(input); - listenerModel.fireContentsChanged(); - } - }); - sub.add(button, "split 2, sizegroup buttons, alignx 50%, gapright para"); - - //// Remove button - button = new JButton(trans.get("simedtdlg.but.remove")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int[] selected = list.getSelectedIndices(); - Arrays.sort(selected); - for (int i = selected.length - 1; i >= 0; i--) { - simulation.getSimulationListeners().remove(selected[i]); - } - listenerModel.fireContentsChanged(); - } - }); - sub.add(button, "sizegroup buttons, alignx 50%"); - - - return panel; - } - - - private class ListenerListModel extends AbstractListModel { - @Override - public String getElementAt(int index) { - if (index < 0 || index >= getSize()) - return null; - return simulation.getSimulationListeners().get(index); - } - - @Override - public int getSize() { - return simulation.getSimulationListeners().size(); - } - - public void fireContentsChanged() { - super.fireContentsChanged(this, 0, getSize()); - } - } - - - - - /** - * A panel for plotting the previously calculated data. - */ - private JPanel plotTab() { - - // Check that data exists - if (simulation.getSimulatedData() == null || - simulation.getSimulatedData().getBranchCount() == 0) { - return noDataPanel(); - } - - return new SimulationPlotPanel(simulation); - } - - - - /** - * A panel for exporting the data. - */ - private JPanel exportTab() { - FlightData data = simulation.getSimulatedData(); - - // Check that data exists - if (data == null || data.getBranchCount() == 0 || - data.getBranch(0).getTypes().length == 0) { - return noDataPanel(); - } - - return new SimulationExportPanel(simulation); - } - - - /** - * Return a panel stating that there is no data available, and that the user - * should run the simulation first. - */ - public static JPanel noDataPanel() { - JPanel panel = new JPanel(new MigLayout("fill")); - - // No data available - //// No flight data available. - panel.add(new JLabel(trans.get("simedtdlg.lbl.Noflightdata")), - "alignx 50%, aligny 100%, wrap para"); - //// Please run the simulation first. - panel.add(new JLabel(trans.get("simedtdlg.lbl.runsimfirst")), - "alignx 50%, aligny 0%, wrap"); - return panel; - } - - - private void performPlot(PlotConfiguration config) { - - // Fill the auto-selections - FlightDataBranch branch = simulation.getSimulatedData().getBranch(0); - PlotConfiguration filled = config.fillAutoAxes(branch); - List axes = filled.getAllAxes(); - - - // Create the data series for both axes - XYSeriesCollection[] data = new XYSeriesCollection[2]; - data[0] = new XYSeriesCollection(); - data[1] = new XYSeriesCollection(); - - - // Get the domain axis type - final FlightDataType domainType = filled.getDomainAxisType(); - final Unit domainUnit = filled.getDomainAxisUnit(); - if (domainType == null) { - throw new IllegalArgumentException("Domain axis type not specified."); - } - List x = branch.get(domainType); - - - // Create the XYSeries objects from the flight data and store into the collections - int length = filled.getTypeCount(); - String[] axisLabel = new String[2]; - for (int i = 0; i < length; i++) { - // Get info - FlightDataType type = filled.getType(i); - Unit unit = filled.getUnit(i); - int axis = filled.getAxis(i); - String name = getLabel(type, unit); - - // Store data in provided units - List y = branch.get(type); - XYSeries series = new XYSeries(name, false, true); - for (int j = 0; j < x.size(); j++) { - series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j))); - } - data[axis].addSeries(series); - - // Update axis label - if (axisLabel[axis] == null) - axisLabel[axis] = type.getName(); - else - axisLabel[axis] += "; " + type.getName(); - } - - - // Create the chart using the factory to get all default settings - JFreeChart chart = ChartFactory.createXYLineChart( - //// Simulated flight - trans.get("simedtdlg.chart.Simflight"), - null, - null, - null, - PlotOrientation.VERTICAL, - true, - true, - false - ); - - - // Add the data and formatting to the plot - XYPlot plot = chart.getXYPlot(); - int axisno = 0; - for (int i = 0; i < 2; i++) { - // Check whether axis has any data - if (data[i].getSeriesCount() > 0) { - // Create and set axis - double min = axes.get(i).getMinValue(); - double max = axes.get(i).getMaxValue(); - NumberAxis axis = new PresetNumberAxis(min, max); - axis.setLabel(axisLabel[i]); - // axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue()); - plot.setRangeAxis(axisno, axis); - - // Add data and map to the axis - plot.setDataset(axisno, data[i]); - plot.setRenderer(axisno, new StandardXYItemRenderer()); - plot.mapDatasetToRangeAxis(axisno, axisno); - axisno++; - } - } - - plot.getDomainAxis().setLabel(getLabel(domainType, domainUnit)); - plot.addDomainMarker(new ValueMarker(0)); - plot.addRangeMarker(new ValueMarker(0)); - - - // Create the dialog - //// Simulation results - final JDialog dialog = new JDialog(this, trans.get("simedtdlg.dlg.Simres")); - dialog.setModalityType(ModalityType.DOCUMENT_MODAL); - - JPanel panel = new JPanel(new MigLayout("fill")); - dialog.add(panel); - - ChartPanel chartPanel = new ChartPanel(chart, - false, // properties - true, // save - false, // print - true, // zoom - true); // tooltips - chartPanel.setMouseWheelEnabled(true); - chartPanel.setEnforceFileExtensions(true); - chartPanel.setInitialDelay(500); - - chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1)); - - panel.add(chartPanel, "grow, wrap 20lp"); - - //// Close button - JButton button = new JButton(trans.get("dlg.but.close")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dialog.setVisible(false); - } - }); - panel.add(button, "right"); - - dialog.setLocationByPlatform(true); - dialog.pack(); - - GUIUtil.setDisposableDialogOptions(dialog, button); - - dialog.setVisible(true); - } - - - private class PresetNumberAxis extends NumberAxis { - private final double min; - private final double max; - - public PresetNumberAxis(double min, double max) { - this.min = min; - this.max = max; - autoAdjustRange(); - } - - @Override - protected void autoAdjustRange() { - this.setRange(min, max); - } - } - - - private String getLabel(FlightDataType type, Unit unit) { - String name = type.getName(); - if (unit != null && !UnitGroup.UNITS_NONE.contains(unit) && - !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0) - name += " (" + unit.getUnit() + ")"; - return name; - } - - - - private class ListenerCellRenderer extends JLabel implements ListCellRenderer { - - @Override - public Component getListCellRendererComponent(JList list, Object value, - int index, boolean isSelected, boolean cellHasFocus) { - String s = value.toString(); - setText(s); - - // Attempt instantiating, catch any exceptions - Exception ex = null; - try { - Class c = Class.forName(s); - @SuppressWarnings("unused") - SimulationListener l = (SimulationListener) c.newInstance(); - } catch (Exception e) { - ex = e; - } - - if (ex == null) { - setIcon(Icons.SIMULATION_LISTENER_OK); - //// Listener instantiated successfully. - setToolTipText("Listener instantiated successfully."); - } else { - setIcon(Icons.SIMULATION_LISTENER_ERROR); - //// Unable to instantiate listener due to exception:
- setToolTipText("Unable to instantiate listener due to exception:
" + - ex.toString()); - } - - if (isSelected) { - setBackground(list.getSelectionBackground()); - setForeground(list.getSelectionForeground()); - } else { - setBackground(list.getBackground()); - setForeground(list.getForeground()); - } - setOpaque(true); - return this; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/main/SimulationPanel.java b/core/src/net/sf/openrocket/gui/main/SimulationPanel.java deleted file mode 100644 index b12b8561..00000000 --- a/core/src/net/sf/openrocket/gui/main/SimulationPanel.java +++ /dev/null @@ -1,614 +0,0 @@ -package net.sf.openrocket.gui.main; - - -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Arrays; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.table.DefaultTableCellRenderer; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.document.events.DocumentChangeEvent; -import net.sf.openrocket.document.events.DocumentChangeListener; -import net.sf.openrocket.document.events.SimulationChangeEvent; -import net.sf.openrocket.gui.adaptors.Column; -import net.sf.openrocket.gui.adaptors.ColumnTableModel; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; -import net.sf.openrocket.unit.UnitGroup; - -public class SimulationPanel extends JPanel { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - private static final Color WARNING_COLOR = Color.RED; - private static final String WARNING_TEXT = "\uFF01"; // Fullwidth exclamation mark - - private static final Color OK_COLOR = new Color(60, 150, 0); - private static final String OK_TEXT = "\u2714"; // Heavy check mark - - - - private final OpenRocketDocument document; - - private final ColumnTableModel simulationTableModel; - private final JTable simulationTable; - - - public SimulationPanel(OpenRocketDocument doc) { - super(new MigLayout("fill", "[grow][][][][][][grow]")); - - JButton button; - - - this.document = doc; - - - - //////// The simulation action buttons - - //// New simulation button - button = new JButton(trans.get("simpanel.but.newsimulation")); - //// Add a new simulation - button.setToolTipText(trans.get("simpanel.but.ttip.newsimulation")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Simulation sim = new Simulation(document.getRocket()); - sim.setName(document.getNextSimulationName()); - - int n = document.getSimulationCount(); - document.addSimulation(sim); - simulationTableModel.fireTableDataChanged(); - simulationTable.clearSelection(); - simulationTable.addRowSelectionInterval(n, n); - - openDialog(sim, SimulationEditDialog.EDIT); - } - }); - this.add(button, "skip 1, gapright para"); - - //// Edit simulation button - button = new JButton(trans.get("simpanel.but.editsimulation")); - //// Edit the selected simulation - button.setToolTipText(trans.get("simpanel.but.ttip.editsim")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int selected = simulationTable.getSelectedRow(); - if (selected < 0) - return; // TODO: MEDIUM: "None selected" dialog - - selected = simulationTable.convertRowIndexToModel(selected); - simulationTable.clearSelection(); - simulationTable.addRowSelectionInterval(selected, selected); - - openDialog(document.getSimulations().get(selected), SimulationEditDialog.EDIT); - } - }); - this.add(button, "gapright para"); - - //// Run simulations - button = new JButton(trans.get("simpanel.but.runsimulations")); - //// Re-run the selected simulations - button.setToolTipText(trans.get("simpanel.but.ttip.runsimu")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int[] selection = simulationTable.getSelectedRows(); - if (selection.length == 0) - return; // TODO: LOW: "None selected" dialog - - Simulation[] sims = new Simulation[selection.length]; - for (int i = 0; i < selection.length; i++) { - selection[i] = simulationTable.convertRowIndexToModel(selection[i]); - sims[i] = document.getSimulation(selection[i]); - } - - long t = System.currentTimeMillis(); - new SimulationRunDialog(SwingUtilities.getWindowAncestor( - SimulationPanel.this), document, sims).setVisible(true); - log.info("Running simulations took " + (System.currentTimeMillis() - t) + " ms"); - fireMaintainSelection(); - } - }); - this.add(button, "gapright para"); - - //// Delete simulations button - button = new JButton(trans.get("simpanel.but.deletesimulations")); - //// Delete the selected simulations - button.setToolTipText(trans.get("simpanel.but.ttip.deletesim")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int[] selection = simulationTable.getSelectedRows(); - if (selection.length == 0) - return; // TODO: LOW: "None selected" dialog - - // Verify deletion - boolean verify = Application.getPreferences().getBoolean(Preferences.CONFIRM_DELETE_SIMULATION, true); - if (verify) { - - JPanel panel = new JPanel(new MigLayout()); - //// Do not ask me again - JCheckBox dontAsk = new JCheckBox(trans.get("simpanel.checkbox.donotask")); - panel.add(dontAsk, "wrap"); - //// You can change the default operation in the preferences. - panel.add(new StyledLabel(trans.get("simpanel.lbl.defpref"), -2)); - - int ret = JOptionPane.showConfirmDialog(SimulationPanel.this, - new Object[] { - //// Delete the selected simulations? - trans.get("simpanel.dlg.lbl.DeleteSim1"), - //// This operation cannot be undone. - trans.get("simpanel.dlg.lbl.DeleteSim2"), - "", - panel }, - //// Delete simulations - trans.get("simpanel.dlg.lbl.DeleteSim3"), - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE); - if (ret != JOptionPane.OK_OPTION) - return; - - if (dontAsk.isSelected()) { - Application.getPreferences().putBoolean(Preferences.CONFIRM_DELETE_SIMULATION, false); - } - } - - // Delete simulations - for (int i = 0; i < selection.length; i++) { - selection[i] = simulationTable.convertRowIndexToModel(selection[i]); - } - Arrays.sort(selection); - for (int i = selection.length - 1; i >= 0; i--) { - document.removeSimulation(selection[i]); - } - simulationTableModel.fireTableDataChanged(); - } - }); - this.add(button, "gapright para"); - - //// Plot / export button - button = new JButton(trans.get("simpanel.but.plotexport")); - // button = new JButton("Plot flight"); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - int selected = simulationTable.getSelectedRow(); - if (selected < 0) - return; // TODO: MEDIUM: "None selected" dialog - - selected = simulationTable.convertRowIndexToModel(selected); - simulationTable.clearSelection(); - simulationTable.addRowSelectionInterval(selected, selected); - - openDialog(document.getSimulations().get(selected), SimulationEditDialog.PLOT); - } - }); - this.add(button, "wrap para"); - - - - - //////// The simulation table - - simulationTableModel = new ColumnTableModel( - - //// Status and warning column - new Column("") { - private JLabel label = null; - - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - // Initialize the label - if (label == null) { - label = new StyledLabel(2f); - label.setIconTextGap(1); - // label.setFont(label.getFont().deriveFont(Font.BOLD)); - } - - // Set simulation status icon - Simulation.Status status = document.getSimulation(row).getStatus(); - label.setIcon(Icons.SIMULATION_STATUS_ICON_MAP.get(status)); - - - // Set warning marker - if (status == Simulation.Status.NOT_SIMULATED || - status == Simulation.Status.EXTERNAL) { - - label.setText(""); - - } else { - - WarningSet w = document.getSimulation(row).getSimulatedWarnings(); - if (w == null) { - label.setText(""); - } else if (w.isEmpty()) { - label.setForeground(OK_COLOR); - label.setText(OK_TEXT); - } else { - label.setForeground(WARNING_COLOR); - label.setText(WARNING_TEXT); - } - } - - return label; - } - - @Override - public int getExactWidth() { - return 36; - } - - @Override - public Class getColumnClass() { - return JLabel.class; - } - }, - - //// Simulation name - //// Name - new Column(trans.get("simpanel.col.Name")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - return document.getSimulation(row).getName(); - } - - @Override - public int getDefaultWidth() { - return 125; - } - }, - - //// Simulation motors - //// Motors - new Column(trans.get("simpanel.col.Motors")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - return document.getSimulation(row).getConfiguration() - .getMotorConfigurationDescription(); - } - - @Override - public int getDefaultWidth() { - return 125; - } - }, - - //// Launch rod velocity - new Column(trans.get("simpanel.col.Velocityoffrod")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_VELOCITY.getDefaultUnit().toStringUnit( - data.getLaunchRodVelocity()); - } - }, - - //// Apogee - new Column(trans.get("simpanel.col.Apogee")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_DISTANCE.getDefaultUnit().toStringUnit( - data.getMaxAltitude()); - } - }, - - //// Velocity at deployment - new Column(trans.get("simpanel.col.Velocityatdeploy")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_VELOCITY.getDefaultUnit().toStringUnit( - data.getDeploymentVelocity()); - } - }, - - //// Maximum velocity - new Column(trans.get("simpanel.col.Maxvelocity")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_VELOCITY.getDefaultUnit().toStringUnit( - data.getMaxVelocity()); - } - }, - - //// Maximum acceleration - new Column(trans.get("simpanel.col.Maxacceleration")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_ACCELERATION.getDefaultUnit().toStringUnit( - data.getMaxAcceleration()); - } - }, - - //// Time to apogee - new Column(trans.get("simpanel.col.Timetoapogee")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit().toStringUnit( - data.getTimeToApogee()); - } - }, - - //// Flight time - new Column(trans.get("simpanel.col.Flighttime")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit().toStringUnit( - data.getFlightTime()); - } - }, - - //// Ground hit velocity - new Column(trans.get("simpanel.col.Groundhitvelocity")) { - @Override - public Object getValueAt(int row) { - if (row < 0 || row >= document.getSimulationCount()) - return null; - - FlightData data = document.getSimulation(row).getSimulatedData(); - if (data == null) - return null; - - return UnitGroup.UNITS_VELOCITY.getDefaultUnit().toStringUnit( - data.getGroundHitVelocity()); - } - } - - ) { - @Override - public int getRowCount() { - return document.getSimulationCount(); - } - }; - - // Override processKeyBinding so that the JTable does not catch - // key bindings used in menu accelerators - simulationTable = new JTable(simulationTableModel) { - @Override - protected boolean processKeyBinding(KeyStroke ks, - KeyEvent e, - int condition, - boolean pressed) { - return false; - } - }; - simulationTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - simulationTable.setDefaultRenderer(Object.class, new JLabelRenderer()); - simulationTableModel.setColumnWidths(simulationTable.getColumnModel()); - - - // Mouse listener to act on double-clicks - simulationTable.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { - int selected = simulationTable.getSelectedRow(); - if (selected < 0) - return; - - selected = simulationTable.convertRowIndexToModel(selected); - simulationTable.clearSelection(); - simulationTable.addRowSelectionInterval(selected, selected); - - openDialog(document.getSimulations().get(selected), - SimulationEditDialog.DEFAULT); - } - } - }); - - document.addDocumentChangeListener(new DocumentChangeListener() { - @Override - public void documentChanged(DocumentChangeEvent event) { - if (!(event instanceof SimulationChangeEvent)) - return; - simulationTableModel.fireTableDataChanged(); - } - }); - - - - - // Fire table change event when the rocket changes - document.getRocket().addComponentChangeListener(new ComponentChangeListener() { - @Override - public void componentChanged(ComponentChangeEvent e) { - fireMaintainSelection(); - } - }); - - - JScrollPane scrollpane = new JScrollPane(simulationTable); - this.add(scrollpane, "spanx, grow, wrap rel"); - - - } - - - public ListSelectionModel getSimulationListSelectionModel() { - return simulationTable.getSelectionModel(); - } - - private void openDialog(final Simulation sim, int position) { - new SimulationEditDialog(SwingUtilities.getWindowAncestor(this), document, sim, position) - .setVisible(true); - fireMaintainSelection(); - } - - private void fireMaintainSelection() { - int[] selection = simulationTable.getSelectedRows(); - simulationTableModel.fireTableDataChanged(); - for (int row : selection) { - if (row >= simulationTableModel.getRowCount()) - break; - simulationTable.addRowSelectionInterval(row, row); - } - } - - - private class JLabelRenderer extends DefaultTableCellRenderer { - - @Override - public Component getTableCellRendererComponent(JTable table, - Object value, boolean isSelected, boolean hasFocus, int row, - int column) { - - if (row < 0 || row >= document.getSimulationCount()) - return super.getTableCellRendererComponent(table, value, - isSelected, hasFocus, row, column); - - // A JLabel is self-contained and has set its own tool tip - if (value instanceof JLabel) { - JLabel label = (JLabel) value; - if (isSelected) - label.setBackground(table.getSelectionBackground()); - else - label.setBackground(table.getBackground()); - label.setOpaque(true); - - label.setToolTipText(getSimulationToolTip(document.getSimulation(row))); - return label; - } - - Component component = super.getTableCellRendererComponent(table, value, - isSelected, hasFocus, row, column); - - if (component instanceof JComponent) { - ((JComponent) component).setToolTipText(getSimulationToolTip( - document.getSimulation(row))); - } - return component; - } - - private String getSimulationToolTip(Simulation sim) { - String tip; - FlightData data = sim.getSimulatedData(); - - tip = "" + sim.getName() + "
"; - switch (sim.getStatus()) { - case UPTODATE: - tip += trans.get ("simpanel.ttip.uptodate") + "
"; - break; - - case LOADED: - tip += trans.get ("simpanel.ttip.loaded") + "
"; - break; - - case OUTDATED: - tip += trans.get ("simpanel.ttip.outdated") + "
"; - break; - - case EXTERNAL: - tip += trans.get ("simpanel.ttip.external") + "
"; - return tip; - - case NOT_SIMULATED: - tip += trans.get ("simpanel.ttip.notSimulated"); - return tip; - } - - if (data == null) { - tip += trans.get ("simpanel.ttip.noData"); - return tip; - } - WarningSet warnings = data.getWarningSet(); - - if (warnings.isEmpty()) { - tip += trans.get ("simpanel.ttip.noWarnings"); - return tip; - } - - tip += trans.get ("simpanel.ttip.warnings"); - for (Warning w : warnings) { - tip += "
" + w.toString(); - } - - return tip; - } - - } -} diff --git a/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java b/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java deleted file mode 100644 index 65fabb8f..00000000 --- a/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java +++ /dev/null @@ -1,490 +0,0 @@ -package net.sf.openrocket.gui.main; - - -import java.awt.Dialog; -import java.awt.Dimension; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.dialogs.DetailDialog; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.simulation.customexpression.CustomExpressionSimulationListener; -import net.sf.openrocket.simulation.exception.SimulationCancelledException; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.exception.SimulationLaunchException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.MathUtil; - - -public class SimulationRunDialog extends JDialog { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - /** Update the dialog status every this many ms */ - private static final long UPDATE_MS = 200; - - /** Flight progress at motor burnout */ - private static final double BURNOUT_PROGRESS = 0.4; - - /** Flight progress at apogee */ - private static final double APOGEE_PROGRESS = 0.7; - - - /** - * A single ThreadPoolExecutor that will be used for all simulations. - * This executor must not be shut down. - */ - private static final ThreadPoolExecutor executor; - static { - int n = SwingPreferences.getMaxThreadCount(); - executor = new ThreadPoolExecutor(n, n, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(), - new ThreadFactory() { - private ThreadFactory factory = Executors.defaultThreadFactory(); - - @Override - public Thread newThread(Runnable r) { - Thread t = factory.newThread(r); - t.setDaemon(true); - return t; - } - }); - } - - - - private final JLabel simLabel, timeLabel, altLabel, velLabel; - private final JProgressBar progressBar; - - - /* - * NOTE: Care must be used when accessing the simulation parameters, since they - * are being run in another thread. Mutexes are used to avoid concurrent usage, which - * will result in an exception being thrown! - */ - private final Simulation[] simulations; - private final OpenRocketDocument document; - private final String[] simulationNames; - private final SimulationWorker[] simulationWorkers; - private final SimulationStatus[] simulationStatuses; - private final double[] simulationMaxAltitude; - private final double[] simulationMaxVelocity; - private final boolean[] simulationDone; - - public SimulationRunDialog(Window window, OpenRocketDocument document, Simulation... simulations) { - //// Running simulations... - super(window, trans.get("SimuRunDlg.title.RunSim"), Dialog.ModalityType.APPLICATION_MODAL); - this.document = document; - - if (simulations.length == 0) { - throw new IllegalArgumentException("Called with no simulations to run"); - } - - this.simulations = simulations; - - - // Randomize the simulation random seeds - for (Simulation sim : simulations) { - sim.getOptions().randomizeSeed(); - } - - // Initialize the simulations - int n = simulations.length; - simulationNames = new String[n]; - simulationWorkers = new SimulationWorker[n]; - simulationStatuses = new SimulationStatus[n]; - simulationMaxAltitude = new double[n]; - simulationMaxVelocity = new double[n]; - simulationDone = new boolean[n]; - - for (int i = 0; i < n; i++) { - simulationNames[i] = simulations[i].getName(); - simulationWorkers[i] = new InteractiveSimulationWorker(document, simulations[i], i); - executor.execute(simulationWorkers[i]); - } - - // Build the dialog - JPanel panel = new JPanel(new MigLayout("fill", "[][grow]")); - - //// Running ... - simLabel = new JLabel(trans.get("SimuRunDlg.lbl.Running")); - panel.add(simLabel, "spanx, wrap para"); - //// Simulation time: - panel.add(new JLabel(trans.get("SimuRunDlg.lbl.Simutime") + " "), "gapright para"); - timeLabel = new JLabel(""); - panel.add(timeLabel, "growx, wmin 200lp, wrap rel"); - - //// Altitude: - panel.add(new JLabel(trans.get("SimuRunDlg.lbl.Altitude") + " ")); - altLabel = new JLabel(""); - panel.add(altLabel, "growx, wrap rel"); - - //// Velocity: - panel.add(new JLabel(trans.get("SimuRunDlg.lbl.Velocity") + " ")); - velLabel = new JLabel(""); - panel.add(velLabel, "growx, wrap para"); - - progressBar = new JProgressBar(); - panel.add(progressBar, "spanx, growx, wrap para"); - - - // Add cancel button - JButton cancel = new JButton(trans.get("dlg.but.cancel")); - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - cancelSimulations(); - } - }); - panel.add(cancel, "spanx, tag cancel"); - - - // Cancel simulations when user closes the window - this.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - cancelSimulations(); - } - }); - - - this.add(panel); - this.setMinimumSize(new Dimension(300, 0)); - this.setLocationByPlatform(true); - this.validate(); - this.pack(); - - GUIUtil.setDisposableDialogOptions(this, null); - - updateProgress(); - } - - - /** - * Cancel the currently running simulations. This is equivalent to clicking - * the Cancel button on the dialog. - */ - public void cancelSimulations() { - for (SimulationWorker w : simulationWorkers) { - w.cancel(true); - } - executor.purge(); - } - - - /** - * Static helper method to run simulations. - * - * @param parent the parent Window of the dialog to use. - * @param simulations the simulations to run. - */ - public static void runSimulations(Window parent, OpenRocketDocument document, Simulation... simulations) { - new SimulationRunDialog(parent, document, simulations).setVisible(true); - } - - - - - private void updateProgress() { - int index; - for (index = 0; index < simulations.length; index++) { - if (!simulationDone[index]) - break; - } - - if (index >= simulations.length) { - // Everything is done, close the dialog - log.debug("Everything done."); - this.dispose(); - return; - } - - // Update the progress bar status - int progress = 0; - for (SimulationWorker s : simulationWorkers) { - progress += s.getProgress(); - } - progress /= simulationWorkers.length; - progressBar.setValue(progress); - log.debug("Progressbar value " + progress); - - // Update the simulation fields - simLabel.setText("Running " + simulationNames[index]); - if (simulationStatuses[index] == null) { - log.debug("No simulation status data available, setting empty labels"); - timeLabel.setText(""); - altLabel.setText(""); - velLabel.setText(""); - return; - } - - Unit u = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit(); - timeLabel.setText(u.toStringUnit(simulationStatuses[index].getSimulationTime())); - - u = UnitGroup.UNITS_DISTANCE.getDefaultUnit(); - altLabel.setText(u.toStringUnit(simulationStatuses[index].getRocketPosition().z) + " (max. " + - u.toStringUnit(simulationMaxAltitude[index]) + ")"); - - u = UnitGroup.UNITS_VELOCITY.getDefaultUnit(); - velLabel.setText(u.toStringUnit(simulationStatuses[index].getRocketVelocity().z) + " (max. " + - u.toStringUnit(simulationMaxVelocity[index]) + ")"); - } - - - - /** - * A SwingWorker that performs a flight simulation. It periodically updates the - * simulation statuses of the parent class and calls updateProgress(). - * The progress of the simulation is stored in the progress property of the - * SwingWorker. - * - * @author Sampo Niskanen - */ - private class InteractiveSimulationWorker extends SimulationWorker { - - private final int index; - private final double burnoutTimeEstimate; - private volatile double burnoutVelocity; - private volatile double apogeeAltitude; - - private final CustomExpressionSimulationListener exprListener; - - /* - * -2 = time from 0 ... burnoutTimeEstimate - * -1 = velocity from v(burnoutTimeEstimate) ... 0 - * 0 ... n = stages from alt(max) ... 0 - */ - private volatile int simulationStage = -2; - - private int progress = 0; - - - public InteractiveSimulationWorker(OpenRocketDocument doc, Simulation sim, int index) { - super(sim); - List exprs = doc.getCustomExpressions(); - exprListener = new CustomExpressionSimulationListener(exprs); - this.index = index; - - // Calculate estimate of motor burn time - double launchBurn = 0; - double otherBurn = 0; - Configuration config = simulation.getConfiguration(); - String id = simulation.getOptions().getMotorConfigurationID(); - Iterator iterator = config.motorIterator(); - while (iterator.hasNext()) { - MotorMount m = iterator.next(); - if (m.getIgnitionEvent() == IgnitionEvent.LAUNCH) - launchBurn = MathUtil.max(launchBurn, m.getMotor(id).getBurnTimeEstimate()); - else - otherBurn = otherBurn + m.getMotor(id).getBurnTimeEstimate(); - } - burnoutTimeEstimate = Math.max(launchBurn + otherBurn, 0.1); - - } - - - /** - * Return the extra listeners to use, a progress listener and cancel listener. - */ - @Override - protected SimulationListener[] getExtraListeners() { - return new SimulationListener[] { new SimulationProgressListener(), exprListener }; - } - - - /** - * Processes simulation statuses published by the simulation listener. - * The statuses of the parent class and the progress property are updated. - */ - @Override - protected void process(List chunks) { - - // Update max. altitude and velocity - for (SimulationStatus s : chunks) { - simulationMaxAltitude[index] = Math.max(simulationMaxAltitude[index], - s.getRocketPosition().z); - simulationMaxVelocity[index] = Math.max(simulationMaxVelocity[index], - s.getRocketVelocity().length()); - } - - // Calculate the progress - SimulationStatus status = chunks.get(chunks.size() - 1); - simulationStatuses[index] = status; - - // 1. time = 0 ... burnoutTimeEstimate - if (simulationStage == -2 && status.getSimulationTime() < burnoutTimeEstimate) { - log.debug("Method 1: t=" + status.getSimulationTime() + " est=" + burnoutTimeEstimate); - setSimulationProgress(MathUtil.map(status.getSimulationTime(), 0, burnoutTimeEstimate, - 0.0, BURNOUT_PROGRESS)); - updateProgress(); - return; - } - - if (simulationStage == -2) { - simulationStage++; - burnoutVelocity = MathUtil.max(status.getRocketVelocity().z, 0.1); - log.debug("CHANGING to Method 2, vel=" + burnoutVelocity); - } - - // 2. z-velocity from burnout velocity to zero - if (simulationStage == -1 && status.getRocketVelocity().z >= 0) { - log.debug("Method 2: vel=" + status.getRocketVelocity().z + " burnout=" + burnoutVelocity); - setSimulationProgress(MathUtil.map(status.getRocketVelocity().z, burnoutVelocity, 0, - BURNOUT_PROGRESS, APOGEE_PROGRESS)); - updateProgress(); - return; - } - - if (simulationStage == -1 && status.getRocketVelocity().z < 0) { - simulationStage++; - apogeeAltitude = MathUtil.max(status.getRocketPosition().z, 1); - log.debug("CHANGING to Method 3, apogee=" + apogeeAltitude); - } - - // 3. z-position from apogee to zero - // TODO: MEDIUM: several stages - log.debug("Method 3: alt=" + status.getRocketPosition().z + " apogee=" + apogeeAltitude); - setSimulationProgress(MathUtil.map(status.getRocketPosition().z, - apogeeAltitude, 0, APOGEE_PROGRESS, 1.0)); - updateProgress(); - } - - /** - * Marks this simulation as done and calls the progress update. - */ - @Override - protected void simulationDone() { - simulationDone[index] = true; - log.debug("Simulation done"); - setSimulationProgress(1.0); - updateProgress(); - } - - - /** - * Marks the simulation as done and shows a dialog presenting - * the error, unless the simulation was cancelled. - */ - @Override - protected void simulationInterrupted(Throwable t) { - - if (t instanceof SimulationCancelledException) { - simulationDone(); - return; // Ignore cancellations - } - - // Analyze the exception type - if (t instanceof SimulationLaunchException) { - - DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this, - new Object[] { - //// Unable to simulate: - trans.get("SimuRunDlg.msg.Unabletosim"), - t.getMessage() - }, - null, simulation.getName(), JOptionPane.ERROR_MESSAGE); - - } else if (t instanceof SimulationException) { - - DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this, - new Object[] { - //// A error occurred during the simulation: - trans.get("SimuRunDlg.msg.errorOccurred"), - t.getMessage() - }, - null, simulation.getName(), JOptionPane.ERROR_MESSAGE); - - } else { - - Application.getExceptionHandler().handleErrorCondition("An exception occurred during the simulation", t); - - } - simulationDone(); - } - - - private void setSimulationProgress(double p) { - int exact = Math.max(progress, (int) (100 * p + 0.5)); - progress = MathUtil.clamp(exact, 0, 100); - log.debug("Setting progress to " + progress + " (real " + exact + ")"); - super.setProgress(progress); - } - - - /** - * A simulation listener that regularly updates the progress property of the - * SimulationWorker and publishes the simulation status for the run dialog to process. - * - * @author Sampo Niskanen - */ - private class SimulationProgressListener extends AbstractSimulationListener { - private long time = 0; - - @Override - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) { - switch (event.getType()) { - case APOGEE: - simulationStage = 0; - apogeeAltitude = status.getRocketPosition().z; - log.debug("APOGEE, setting progress"); - setSimulationProgress(APOGEE_PROGRESS); - publish(status); - break; - - case LAUNCH: - publish(status); - break; - - case SIMULATION_END: - log.debug("END, setting progress"); - setSimulationProgress(1.0); - break; - } - return true; - } - - @Override - public void postStep(SimulationStatus status) { - if (System.currentTimeMillis() >= time + UPDATE_MS) { - time = System.currentTimeMillis(); - publish(status); - } - } - } - } -} diff --git a/core/src/net/sf/openrocket/gui/main/SimulationWorker.java b/core/src/net/sf/openrocket/gui/main/SimulationWorker.java deleted file mode 100644 index f348fbcd..00000000 --- a/core/src/net/sf/openrocket/gui/main/SimulationWorker.java +++ /dev/null @@ -1,121 +0,0 @@ -package net.sf.openrocket.gui.main; - -import java.util.Arrays; - -import javax.swing.SwingWorker; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationCancelledException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.simulation.listeners.SimulationListener; - - - -/** - * A SwingWorker that runs a simulation in a background thread. The simulation - * always includes a listener that checks whether this SwingWorked has been cancelled, - * and throws a {@link SimulationCancelledException} if it has. This allows the - * {@link #cancel(boolean)} method to be used to cancel the simulation. - * - * @author Sampo Niskanen - */ -public abstract class SimulationWorker extends SwingWorker { - - protected final Simulation simulation; - private Throwable throwable = null; - - public SimulationWorker(Simulation sim) { - this.simulation = sim; - } - - - /** - * Runs the simulation. - */ - @Override - protected FlightData doInBackground() { - if (isCancelled()) { - throwable = new SimulationCancelledException("The simulation was interrupted."); - return null; - } - - SimulationListener[] listeners = getExtraListeners(); - - if (listeners != null) { - listeners = Arrays.copyOf(listeners, listeners.length + 1); - } else { - listeners = new SimulationListener[1]; - } - - listeners[listeners.length - 1] = new CancelListener(); - - try { - simulation.simulate(listeners); - } catch (Throwable e) { - throwable = e; - return null; - } - return simulation.getSimulatedData(); - } - - - /** - * Return additional listeners to use during the simulation. The default - * implementation returns an empty array. - * - * @return additional listeners to use, or null. - */ - protected SimulationListener[] getExtraListeners() { - return new SimulationListener[0]; - } - - - /** - * Called after a simulation is successfully simulated. This method is not - * called if the simulation ends in an exception. - */ - protected abstract void simulationDone(); - - /** - * Called if the simulation is interrupted due to an exception. - * - * @param t the Throwable that caused the interruption - */ - protected abstract void simulationInterrupted(Throwable t); - - - - /** - * Marks this simulation as done and calls the progress update. - */ - @Override - protected final void done() { - if (throwable == null) - simulationDone(); - else - simulationInterrupted(throwable); - } - - - - /** - * A simulation listener that throws a {@link SimulationCancelledException} if - * this SwingWorker has been cancelled. The conditions is checked every time a step - * is taken. - * - * @author Sampo Niskanen - */ - private class CancelListener extends AbstractSimulationListener { - - @Override - public void postStep(SimulationStatus status) throws SimulationCancelledException { - - if (isCancelled()) { - throw new SimulationCancelledException("The simulation was interrupted."); - } - - } - } -} diff --git a/core/src/net/sf/openrocket/gui/main/Splash.java b/core/src/net/sf/openrocket/gui/main/Splash.java deleted file mode 100644 index 4d9b68a5..00000000 --- a/core/src/net/sf/openrocket/gui/main/Splash.java +++ /dev/null @@ -1,93 +0,0 @@ -package net.sf.openrocket.gui.main; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.SplashScreen; -import java.awt.font.GlyphVector; -import java.awt.geom.Rectangle2D; - -import net.sf.openrocket.util.BuildProperties; - -/** - * Helper methods for manipulating the Java runtime splash screen. - *

- * Notes: - * SplashScreen.update() takes randomly between 4 and 500 ms to complete, - * even after it has been called ~100 times (and therefore pre-compiled). - * Therefore it cannot be relied upon to perform for example color fades. - * Care should be taken to call update() only once or twice per second. - * - * @author Sampo Niskanen - */ -public class Splash { - - // The right edge of the text base line for the version string - private static final int VERSION_POSITION_X = 617; - private static final int VERSION_POSITION_Y = 138; - private static final Font VERSION_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 9); - private static final Color VERSION_COLOR = Color.WHITE; - - - /** - * Initialize the splash screen with additional information. This method should - * be called as soon as reasonably possible during program startup. - * - * @return true if the splash screen could be successfully initialized - */ - public static boolean init() { - // Get the splash screen - SplashScreen s = getSplash(); - if (s == null) - return false; - - // Create graphics context and set antialiasing on - Graphics2D g2 = s.createGraphics(); - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - g2.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - // Draw the version number - drawVersionNumber(g2); - - // Update the splash screen - s.update(); - return true; - } - - - - private static void drawVersionNumber(Graphics2D g2) { - String text = "Version " + BuildProperties.getVersion(); - GlyphVector gv = VERSION_FONT.createGlyphVector(g2.getFontRenderContext(), text); - - Rectangle2D rect = gv.getVisualBounds(); - double width = rect.getWidth(); - - g2.setColor(VERSION_COLOR); - g2.drawGlyphVector(gv, (float) (VERSION_POSITION_X - width), VERSION_POSITION_Y); - - } - - - /** - * Return the current splash screen or null if not available. - * This method catches the possible exceptions and returns null if they occur. - * - * @return the current splash screen, or null. - */ - private static SplashScreen getSplash() { - try { - return SplashScreen.getSplashScreen(); - } catch (RuntimeException e) { - return null; - } - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/main/SwingExceptionHandler.java b/core/src/net/sf/openrocket/gui/main/SwingExceptionHandler.java deleted file mode 100644 index dbaf437c..00000000 --- a/core/src/net/sf/openrocket/gui/main/SwingExceptionHandler.java +++ /dev/null @@ -1,425 +0,0 @@ -package net.sf.openrocket.gui.main; - -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; - -import net.sf.openrocket.gui.dialogs.BugReportDialog; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.ExceptionHandler; - - -public class SwingExceptionHandler implements Thread.UncaughtExceptionHandler, ExceptionHandler { - - private static final LogHelper log = Application.getLogger(); - - private static final int MEMORY_RESERVE = 512 * 1024; - - /** - * A memory reserve of 0.5 MB of memory, that can be freed when showing the dialog. - *

- * This field is package-private so that the JRE cannot optimize its use away. - */ - volatile byte[] memoryReserve = null; - - private volatile boolean handling = false; - - - - - @Override - public void uncaughtException(final Thread thread, final Throwable throwable) { - - // Free memory reserve if out of memory - if (isOutOfMemoryError(throwable)) { - memoryReserve = null; - handling = false; - log.error("Out of memory error detected", throwable); - } - - if (isNonFatalJREBug(throwable)) { - log.warn("Ignoring non-fatal JRE bug", throwable); - return; - } - - log.error("Handling uncaught exception on thread=" + thread, throwable); - throwable.printStackTrace(); - - if (handling) { - log.warn("Exception is currently being handled, ignoring"); - return; - } - - try { - handling = true; - - // Show on the EDT - if (SwingUtilities.isEventDispatchThread()) { - log.info("Exception handler running on EDT, showing dialog"); - showDialog(thread, throwable); - } else { - log.info("Exception handler not on EDT, invoking dialog on EDT"); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - showDialog(thread, throwable); - } - }); - } - - } catch (Throwable ex) { - - // Make sure the handler does not throw any exceptions - try { - log.error("Caught exception while handling exception", ex); - System.err.println("Exception in exception handler, dumping exception:"); - ex.printStackTrace(); - } catch (Exception ignore) { - } - - } finally { - // Mark handling as completed - handling = false; - } - - } - - - /** - * Handle an error condition programmatically without throwing an exception. - * This can be used in cases where recovery of the error is desirable. - *

- * This method is guaranteed never to throw an exception, and can thus be safely - * used in finally blocks. - * - * @param message the error message. - */ - @Override - public void handleErrorCondition(String message) { - log.error(1, message, new TraceException()); - handleErrorCondition(new InternalException(message)); - } - - - /** - * Handle an error condition programmatically without throwing an exception. - * This can be used in cases where recovery of the error is desirable. - *

- * This method is guaranteed never to throw an exception, and can thus be safely - * used in finally blocks. - * - * @param message the error message. - * @param exception the exception that occurred. - */ - @Override - public void handleErrorCondition(String message, Throwable exception) { - log.error(1, message, exception); - handleErrorCondition(new InternalException(message, exception)); - } - - - /** - * Handle an error condition programmatically without throwing an exception. - * This can be used in cases where recovery of the error is desirable. - *

- * This method is guaranteed never to throw an exception, and can thus be safely - * used in finally blocks. - * - * @param exception the exception that occurred. - */ - @Override - public void handleErrorCondition(final Throwable exception) { - try { - if (!(exception instanceof InternalException)) { - log.error(1, "Error occurred", exception); - } - final Thread thread = Thread.currentThread(); - - if (SwingUtilities.isEventDispatchThread()) { - log.info("Running in EDT, showing dialog"); - this.showDialog(thread, exception); - } else { - log.info("Not in EDT, invoking dialog later"); - final SwingExceptionHandler instance = this; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - instance.showDialog(thread, exception); - } - }); - } - } catch (Exception e) { - log.error("Exception occurred in error handler", e); - } - } - - - /** - * The actual handling routine. - * - * @param t the thread that caused the exception, or null. - * @param e the exception. - */ - private void showDialog(Thread t, Throwable e) { - - // Out of memory - if (isOutOfMemoryError(e)) { - log.info("Showing out-of-memory dialog"); - JOptionPane.showMessageDialog(null, - new Object[] { - "OpenRocket is out of available memory!", - "You should immediately close unnecessary design windows,", - "save any unsaved designs and restart OpenRocket!" - }, "Out of memory", JOptionPane.ERROR_MESSAGE); - return; - } - - // Create the message - String msg = e.getClass().getSimpleName() + ": " + e.getMessage(); - if (msg.length() > 90) { - msg = msg.substring(0, 80) + "..."; - } - - // Unknown Error - if (!(e instanceof Exception) && !(e instanceof LinkageError)) { - log.info("Showing Error dialog"); - JOptionPane.showMessageDialog(null, - new Object[] { - "An unknown Java error occurred:", - msg, - "You should immediately close unnecessary design windows,
" + - "save any unsaved designs and restart OpenRocket!" - }, "Unknown Java error", JOptionPane.ERROR_MESSAGE); - return; - } - - - // Normal exception, show question dialog - log.info("Showing Exception dialog"); - int selection = JOptionPane.showOptionDialog(null, new Object[] { - "OpenRocket encountered an uncaught exception. This typically signifies " + - "a bug in the software.", - "        " + msg + "", - " ", - "Please take a moment to report this bug to the developers.", - "This can be done automatically if you have an Internet connection." - }, "Uncaught exception", JOptionPane.DEFAULT_OPTION, - JOptionPane.ERROR_MESSAGE, null, - new Object[] { "View bug report", "Close" }, "View bug report"); - - if (selection != 0) { - // User cancelled - log.user("User chose not to fill bug report"); - return; - } - - // Show bug report dialog - log.user("User requested sending bug report"); - BugReportDialog.showExceptionDialog(null, t, e); - } - - - - /** - * Registers the uncaught exception handler. This should be used to ensure that - * all necessary registrations are performed. - */ - public void registerExceptionHandler() { - - Thread.setDefaultUncaughtExceptionHandler(this); - - // Handler for modal dialogs of Sun's Java implementation - // See bug ID 4499199. - System.setProperty("sun.awt.exception.handler", AwtHandler.class.getName()); - - reserveMemory(); - - } - - - /** - * Reserve the buffer memory that is freed in case an OutOfMemoryError occurs. - */ - private void reserveMemory() { - memoryReserve = new byte[MEMORY_RESERVE]; - for (int i = 0; i < MEMORY_RESERVE; i++) { - memoryReserve[i] = (byte) i; - } - } - - - - /** - * Return whether this throwable was caused by an OutOfMemoryError - * condition. An exception is deemed to be caused by OutOfMemoryError - * if the throwable or any of its causes is of the type OutOfMemoryError. - *

- * This method is required because Apple's JRE implementation sometimes - * masks OutOfMemoryErrors within RuntimeExceptions. Idiots. - * - * @param t the throwable to examine. - * @return whether this is an out-of-memory condition. - */ - private boolean isOutOfMemoryError(Throwable t) { - while (t != null) { - if (t instanceof OutOfMemoryError) - return true; - t = t.getCause(); - } - return false; - } - - - - /** - * Handler used in modal dialogs by Sun Java implementation. - */ - public static class AwtHandler { - public void handle(Throwable t) { - Application.getExceptionHandler().uncaughtException(Thread.currentThread(), t); - } - } - - - /** - * Detect various non-fatal Sun JRE bugs. - * - * @param t the throwable - * @return whether this exception should be ignored - */ - private boolean isNonFatalJREBug(Throwable t) { - - // NOTE: Calling method logs the entire throwable, so log only message here - - - /* - * Detect and ignore bug 6826104 in Sun JRE. - */ - if (t instanceof NullPointerException) { - StackTraceElement[] trace = t.getStackTrace(); - - if (trace.length > 3 && - trace[0].getClassName().equals("sun.awt.X11.XWindowPeer") && - trace[0].getMethodName().equals("restoreTransientFor") && - - trace[1].getClassName().equals("sun.awt.X11.XWindowPeer") && - trace[1].getMethodName().equals("removeFromTransientFors") && - - trace[2].getClassName().equals("sun.awt.X11.XWindowPeer") && - trace[2].getMethodName().equals("setModalBlocked")) { - log.warn("Ignoring Sun JRE bug (6826104): http://bugs.sun.com/view_bug.do?bug_id=6826104" + t); - return true; - } - - } - - - /* - * Detect and ignore bug 6828938 in Sun JRE 1.6.0_14 - 1.6.0_16. - */ - if (t instanceof ArrayIndexOutOfBoundsException) { - final String buggyClass = "sun.font.FontDesignMetrics"; - StackTraceElement[] elements = t.getStackTrace(); - if (elements.length >= 3 && - (buggyClass.equals(elements[0].getClassName()) || - buggyClass.equals(elements[1].getClassName()) || - buggyClass.equals(elements[2].getClassName()))) { - log.warn("Ignoring Sun JRE bug 6828938: " + - "(see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6828938): " + t); - return true; - } - } - - /* - * Detect and ignore bug 6561072 in Sun JRE 1.6.0_? - */ - if (t instanceof NullPointerException) { - StackTraceElement[] trace = t.getStackTrace(); - - if (trace.length > 3 && - trace[0].getClassName().equals("javax.swing.JComponent") && - trace[0].getMethodName().equals("repaint") && - - trace[1].getClassName().equals("sun.swing.FilePane$2") && - trace[1].getMethodName().equals("repaintListSelection") && - - trace[2].getClassName().equals("sun.swing.FilePane$2") && - trace[2].getMethodName().equals("repaintSelection")) { - log.warn("Ignoring Sun JRE bug 6561072 " + - "(see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6561072): " + t); - return true; - } - } - - - /* - * Detect and ignore bug 6933331 in Sun JRE 1.6.0_18 and others - */ - if (t instanceof IllegalStateException) { - StackTraceElement[] trace = t.getStackTrace(); - - if (trace.length > 1 && - trace[0].getClassName().equals("sun.awt.windows.WComponentPeer") && - trace[0].getMethodName().equals("getBackBuffer")) { - log.warn("Ignoring Sun JRE bug 6933331 " + - "(see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6933331): " + t); - return true; - } - } - - /* - * Detect and ignore bug in Sun JRE 1.6.0_19 - */ - if (t instanceof NullPointerException) { - StackTraceElement[] trace = t.getStackTrace(); - - if (trace.length > 3 && - trace[0].getClassName().equals("sun.awt.shell.Win32ShellFolder2") && - trace[0].getMethodName().equals("pidlsEqual") && - - trace[1].getClassName().equals("sun.awt.shell.Win32ShellFolder2") && - trace[1].getMethodName().equals("equals") && - - trace[2].getClassName().equals("sun.awt.shell.Win32ShellFolderManager2") && - trace[2].getMethodName().equals("isFileSystemRoot")) { - log.warn("Ignoring Sun JRE bug " + - "(see http://forums.sun.com/thread.jspa?threadID=5435324): " + t); - return true; - } - } - - /* - * Detect Sun JRE bug in D3D - */ - if (t instanceof ClassCastException) { - if (t.getMessage().equals("sun.awt.Win32GraphicsConfig cannot be cast to sun.java2d.d3d.D3DGraphicsConfig")) { - log.warn("Ignoring Sun JRE bug " + - "(see http://forums.sun.com/thread.jspa?threadID=5440525): " + t); - return true; - } - } - - return false; - } - - - @SuppressWarnings("unused") - private static class InternalException extends Exception { - public InternalException() { - super(); - } - - public InternalException(String message, Throwable cause) { - super(message, cause); - } - - public InternalException(String message) { - super(message); - } - - public InternalException(Throwable cause) { - super(cause); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/main/UndoRedoAction.java b/core/src/net/sf/openrocket/gui/main/UndoRedoAction.java deleted file mode 100644 index 08c31c7e..00000000 --- a/core/src/net/sf/openrocket/gui/main/UndoRedoAction.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.sf.openrocket.gui.main; - -import java.awt.event.ActionEvent; - -import javax.swing.AbstractAction; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.UndoRedoListener; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; - -/** - * Inner class to implement undo/redo actions. - */ -public class UndoRedoAction extends AbstractAction implements UndoRedoListener { - - // Use Factory mechanism because we want to register the new instance as an - // UndoRedoListener. - public static UndoRedoAction newUndoAction( OpenRocketDocument document ) { - UndoRedoAction undo = new UndoRedoAction( UNDO, document ); - document.addUndoRedoListener(undo); - return undo; - } - - public static UndoRedoAction newRedoAction( OpenRocketDocument document ) { - UndoRedoAction redo = new UndoRedoAction( REDO, document ); - document.addUndoRedoListener(redo); - return redo; - } - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private static final int UNDO = 1; - private static final int REDO = 2; - - private final int type; - - private final OpenRocketDocument document; - - // Sole constructor - private UndoRedoAction(int type, OpenRocketDocument document) { - this.document = document; - if (type != UNDO && type != REDO) { - throw new IllegalArgumentException("Unknown type = " + type); - } - this.type = type; - setAllValues(); - } - - - // Actual action to make - @Override - public void actionPerformed(ActionEvent e) { - switch (type) { - case UNDO: - log.user("Performing undo, event=" + e); - document.undo(); - break; - - case REDO: - log.user("Performing redo, event=" + e); - document.redo(); - break; - } - } - - - // Set all the values correctly (name and enabled/disabled status) - public void setAllValues() { - String name, desc; - boolean actionEnabled; - - switch (type) { - case UNDO: - //// Undo - name = trans.get("OpenRocketDocument.Undo"); - desc = document.getUndoDescription(); - actionEnabled = document.isUndoAvailable(); - this.putValue(SMALL_ICON, Icons.EDIT_UNDO); - break; - - case REDO: - ////Redo - name = trans.get("OpenRocketDocument.Redo"); - desc = document.getRedoDescription(); - actionEnabled = document.isRedoAvailable(); - this.putValue(SMALL_ICON, Icons.EDIT_REDO); - break; - - default: - throw new BugException("illegal type=" + type); - } - - if (desc != null) - name = name + " (" + desc + ")"; - - putValue(NAME, name); - setEnabled(actionEnabled); - } -} diff --git a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTree.java b/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTree.java deleted file mode 100644 index f78bfd00..00000000 --- a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTree.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.sf.openrocket.gui.main.componenttree; - -import javax.swing.DropMode; -import javax.swing.ToolTipManager; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.components.BasicTree; - - -public class ComponentTree extends BasicTree { - - public ComponentTree(OpenRocketDocument document) { - super(); - this.setModel(new ComponentTreeModel(document.getRocket(), this)); - - this.setCellRenderer(new ComponentTreeRenderer()); - - this.setDragEnabled(true); - this.setDropMode(DropMode.INSERT); - this.setTransferHandler(new ComponentTreeTransferHandler(document)); - - // Expand whole tree by default - expandTree(); - - // Enable tooltips for this component - ToolTipManager.sharedInstance().registerComponent(this); - - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeModel.java b/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeModel.java deleted file mode 100644 index fe141f61..00000000 --- a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeModel.java +++ /dev/null @@ -1,226 +0,0 @@ -package net.sf.openrocket.gui.main.componenttree; - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.JTree; -import javax.swing.event.TreeModelEvent; -import javax.swing.event.TreeModelListener; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; - -import net.sf.openrocket.rocketcomponent.ComponentChangeEvent; -import net.sf.openrocket.rocketcomponent.ComponentChangeListener; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.BugException; - - -/** - * A TreeModel that implements viewing of the rocket tree structure. - * - * @author Sampo Niskanen - */ - -public class ComponentTreeModel implements TreeModel, ComponentChangeListener { - ArrayList listeners = new ArrayList(); - - private final RocketComponent root; - private final JTree tree; - - public ComponentTreeModel(RocketComponent root, JTree tree) { - this.root = root; - this.tree = tree; - root.addComponentChangeListener(this); - } - - - @Override - public Object getChild(Object parent, int index) { - RocketComponent component = (RocketComponent) parent; - - try { - return component.getChild(index); - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - - @Override - public int getChildCount(Object parent) { - RocketComponent c = (RocketComponent) parent; - - return c.getChildCount(); - } - - - @Override - public int getIndexOfChild(Object parent, Object child) { - if (parent == null || child == null) - return -1; - - RocketComponent p = (RocketComponent) parent; - RocketComponent c = (RocketComponent) child; - - return p.getChildPosition(c); - } - - @Override - public Object getRoot() { - return root; - } - - @Override - public boolean isLeaf(Object node) { - return !((RocketComponent) node).allowsChildren(); - } - - @Override - public void addTreeModelListener(TreeModelListener l) { - listeners.add(l); - } - - @Override - public void removeTreeModelListener(TreeModelListener l) { - listeners.remove(l); - } - - private void fireTreeNodeChanged(RocketComponent node) { - TreeModelEvent e = new TreeModelEvent(this, makeTreePath(node), null, null); - Object[] l = listeners.toArray(); - for (int i = 0; i < l.length; i++) - ((TreeModelListener) l[i]).treeNodesChanged(e); - } - - - private void fireTreeStructureChanged(RocketComponent source) { - Object[] path = { root }; - - - // Get currently expanded path IDs - Enumeration enumer = tree.getExpandedDescendants(new TreePath(path)); - ArrayList expanded = new ArrayList(); - if (enumer != null) { - while (enumer.hasMoreElements()) { - TreePath p = enumer.nextElement(); - expanded.add(((RocketComponent) p.getLastPathComponent()).getID()); - } - } - - // Send structure change event - TreeModelEvent e = new TreeModelEvent(this, path); - Object[] l = listeners.toArray(); - for (int i = 0; i < l.length; i++) - ((TreeModelListener) l[i]).treeStructureChanged(e); - - // Re-expand the paths - for (String id : expanded) { - RocketComponent c = root.findComponent(id); - if (c == null) - continue; - tree.expandPath(makeTreePath(c)); - } - if (source != null) { - TreePath p = makeTreePath(source); - tree.makeVisible(p); - tree.expandPath(p); - } - } - - @Override - public void valueForPathChanged(TreePath path, Object newValue) { - System.err.println("ERROR: valueForPathChanged called?!"); - } - - - @Override - public void componentChanged(ComponentChangeEvent e) { - if (e.isTreeChange() || e.isUndoChange()) { - // Tree must be fully updated also in case of an undo change - fireTreeStructureChanged(e.getSource()); - if (e.isTreeChange() && e.isUndoChange()) { - // If the undo has changed the tree structure, some elements may be hidden - // unnecessarily - // TODO: LOW: Could this be performed better? - expandAll(); - } - } else if (e.isOtherChange()) { - fireTreeNodeChanged(e.getSource()); - } - } - - public void expandAll() { - Iterator iterator = root.iterator(false); - while (iterator.hasNext()) { - tree.makeVisible(makeTreePath(iterator.next())); - } - } - - - /** - * Return the rocket component that a TreePath object is referring to. - * - * @param path the TreePath - * @return the RocketComponent the path is referring to. - * @throws NullPointerException if path is null - * @throws BugException if the path does not refer to a RocketComponent - */ - public static RocketComponent componentFromPath(TreePath path) { - Object last = path.getLastPathComponent(); - if (!(last instanceof RocketComponent)) { - throw new BugException("Tree path does not refer to a RocketComponent: " + path.toString()); - } - return (RocketComponent) last; - } - - - /** - * Return a TreePath corresponding to the specified rocket component. - * - * @param component the rocket component - * @return a TreePath corresponding to this RocketComponent - */ - public static TreePath makeTreePath(RocketComponent component) { - if (component == null) { - throw new NullPointerException(); - } - - RocketComponent c = component; - - List list = new LinkedList(); - - while (c != null) { - list.add(0, c); - c = c.getParent(); - } - - return new TreePath(list.toArray()); - } - - - /** - * Return a string describing the path, using component normal names. - * - * @param treePath the tree path - * @return a string representation - */ - public static String pathToString(TreePath treePath) { - StringBuffer sb = new StringBuffer(); - sb.append("["); - for (Object o : treePath.getPath()) { - if (sb.length() > 1) { - sb.append("; "); - } - if (o instanceof RocketComponent) { - sb.append(((RocketComponent) o).getComponentName()); - } else { - sb.append(o.toString()); - } - } - sb.append("]"); - return sb.toString(); - } -} diff --git a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java b/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java deleted file mode 100644 index 6fe9fe1d..00000000 --- a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.sf.openrocket.gui.main.componenttree; - - - -import java.awt.Component; - -import javax.swing.JTree; -import javax.swing.tree.DefaultTreeCellRenderer; - -import net.sf.openrocket.gui.main.ComponentIcons; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.TextUtil; - -public class ComponentTreeRenderer extends DefaultTreeCellRenderer { - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus1) { - - super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus1); - - // Set icon - setIcon(ComponentIcons.getSmallIcon(value.getClass())); - - // Set tooltip - RocketComponent c = (RocketComponent) value; - this.setToolTipText(getToolTip(c)); - - return this; - } - - - private String getToolTip(RocketComponent c) { - StringBuilder sb = new StringBuilder(); - sb.append(""); - - sb.append("").append(c.getName()).append(""); - if (c.isMassive()) { - sb.append(" (").append(UnitGroup.UNITS_MASS.toStringUnit(c.getMass())).append(")"); - } - - String comment = c.getComment().trim(); - if (comment.length() > 0) { - comment = TextUtil.htmlEncode(comment); - comment = comment.replace("\n", "
"); - sb.append("
").append(comment); - } - - return sb.toString(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeTransferHandler.java b/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeTransferHandler.java deleted file mode 100644 index ff4ae578..00000000 --- a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeTransferHandler.java +++ /dev/null @@ -1,373 +0,0 @@ -package net.sf.openrocket.gui.main.componenttree; - -import java.awt.Point; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.io.IOException; -import java.util.Arrays; - -import javax.swing.JComponent; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.TransferHandler; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; - -/** - * A TransferHandler that handles dragging components from and to a ComponentTree. - * Supports both moving and copying (only copying when dragging to a different rocket). - * - * @author Sampo Niskanen - */ -public class ComponentTreeTransferHandler extends TransferHandler { - - private static final LogHelper log = Application.getLogger(); - - private final OpenRocketDocument document; - - - /** - * Sole constructor. - * - * @param document the document this handler will drop to, used for undo actions. - */ - public ComponentTreeTransferHandler(OpenRocketDocument document) { - this.document = document; - } - - @Override - public int getSourceActions(JComponent comp) { - return COPY_OR_MOVE; - } - - @Override - public Transferable createTransferable(JComponent component) { - if (!(component instanceof JTree)) { - throw new BugException("TransferHandler called with component " + component); - } - - JTree tree = (JTree) component; - TreePath path = tree.getSelectionPath(); - if (path == null) { - return null; - } - - RocketComponent c = ComponentTreeModel.componentFromPath(path); - if (c instanceof Rocket) { - log.info("Attempting to create transferable from Rocket"); - return null; - } - - log.info("Creating transferable from component " + c.getComponentName()); - return new RocketComponentTransferable(c); - } - - - - - @Override - public void exportDone(JComponent comp, Transferable trans, int action) { - // Removal from the old place is implemented already in import, so do nothing - } - - - - @Override - public boolean canImport(TransferHandler.TransferSupport support) { - SourceTarget data = getSourceAndTarget(support); - - if (data == null) { - return false; - } - - boolean allowed = data.destParent.isCompatible(data.child); - log.verbose("Checking validity of drag-drop " + data.toString() + " allowed:" + allowed); - - // Ensure we're not dropping a component onto a child component - RocketComponent path = data.destParent; - while (path != null) { - if (path.equals(data.child)) { - log.verbose("Drop would cause cycle in tree, disallowing."); - allowed = false; - break; - } - path = path.getParent(); - } - - // If drag-dropping to another rocket always copy - if (support.getDropAction() == MOVE && data.srcParent.getRoot() != data.destParent.getRoot()) { - support.setDropAction(COPY); - } - - return allowed; - } - - - @Override - public boolean importData(TransferHandler.TransferSupport support) { - - // We currently only support drop, not paste - if (!support.isDrop()) { - log.warn("Import action is not a drop action"); - return false; - } - - // Sun JRE silently ignores any RuntimeExceptions in importData, yeech! - try { - - SourceTarget data = getSourceAndTarget(support); - - // Check what action to perform - int action = support.getDropAction(); - if (data.srcParent.getRoot() != data.destParent.getRoot()) { - // If drag-dropping to another rocket always copy - log.info("Performing DnD between different rockets, forcing copy action"); - action = TransferHandler.COPY; - } - - - // Check whether move action would be a no-op - if ((action == MOVE) && (data.srcParent == data.destParent) && - (data.destIndex == data.srcIndex || data.destIndex == data.srcIndex + 1)) { - log.user("Dropped component at the same place as previously: " + data); - return false; - } - - - switch (action) { - case MOVE: - log.user("Performing DnD move operation: " + data); - - // If parents are the same, check whether removing the child changes the insert position - int index = data.destIndex; - if (data.srcParent == data.destParent && data.srcIndex < data.destIndex) { - index--; - } - - // Mark undo and freeze rocket. src and dest are in same rocket, need to freeze only one - try { - document.startUndo("Move component"); - try { - data.srcParent.getRocket().freeze(); - data.srcParent.removeChild(data.srcIndex); - data.destParent.addChild(data.child, index); - } finally { - data.srcParent.getRocket().thaw(); - } - } finally { - document.stopUndo(); - } - return true; - - case COPY: - log.user("Performing DnD copy operation: " + data); - RocketComponent copy = data.child.copy(); - try { - document.startUndo("Copy component"); - data.destParent.addChild(copy, data.destIndex); - } finally { - document.stopUndo(); - } - return true; - - default: - log.warn("Unknown transfer action " + action); - return false; - } - - } catch (final RuntimeException e) { - // Open error dialog later if an exception has occurred - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - Application.getExceptionHandler().handleErrorCondition(e); - } - }); - return false; - } - } - - - - /** - * Fetch the source and target for the DnD action. This method does not perform - * checks on whether this action is allowed based on component positioning rules. - * - * @param support the transfer support - * @return the source and targer, or null if invalid. - */ - private SourceTarget getSourceAndTarget(TransferHandler.TransferSupport support) { - // We currently only support drop, not paste - if (!support.isDrop()) { - log.warn("Import action is not a drop action"); - return null; - } - - // we only import RocketComponentTransferable - if (!support.isDataFlavorSupported(RocketComponentTransferable.ROCKET_COMPONENT_DATA_FLAVOR)) { - log.debug("Attempting to import data with data flavors " + - Arrays.toString(support.getTransferable().getTransferDataFlavors())); - return null; - } - - // Fetch the drop location and convert it to work around bug 6560955 - JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation(); - if (dl.getPath() == null) { - log.debug("No drop path location available"); - return null; - } - MyDropLocation location = convertDropLocation((JTree) support.getComponent(), dl); - - - // Fetch the transferred component (child component) - Transferable transferable = support.getTransferable(); - RocketComponent child; - - try { - child = (RocketComponent) transferable.getTransferData( - RocketComponentTransferable.ROCKET_COMPONENT_DATA_FLAVOR); - } catch (IOException e) { - throw new BugException(e); - } catch (UnsupportedFlavorException e) { - throw new BugException(e); - } - - - // Get the source component & index - RocketComponent srcParent = child.getParent(); - if (srcParent == null) { - log.debug("Attempting to drag root component"); - return null; - } - int srcIndex = srcParent.getChildPosition(child); - - - // Get destination component & index - RocketComponent destParent = ComponentTreeModel.componentFromPath(location.path); - int destIndex = location.index; - if (destIndex < 0) { - destIndex = 0; - } - - return new SourceTarget(srcParent, srcIndex, destParent, destIndex, child); - } - - private class SourceTarget { - private final RocketComponent srcParent; - private final int srcIndex; - private final RocketComponent destParent; - private final int destIndex; - private final RocketComponent child; - - public SourceTarget(RocketComponent srcParent, int srcIndex, RocketComponent destParent, int destIndex, - RocketComponent child) { - this.srcParent = srcParent; - this.srcIndex = srcIndex; - this.destParent = destParent; - this.destIndex = destIndex; - this.child = child; - } - - @Override - public String toString() { - return "[" + - "srcParent=" + srcParent.getComponentName() + - ", srcIndex=" + srcIndex + - ", destParent=" + destParent.getComponentName() + - ", destIndex=" + destIndex + - ", child=" + child.getComponentName() + - "]"; - } - - } - - - - /** - * Convert the JTree drop location in order to work around bug 6560955 - * (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6560955). - *

- * This method analyzes whether the user is dropping on top of the last component - * of a subtree or the next item in the tree. The case to fix must fulfill the following - * requirements: - *

    - *
  • The node before the current insertion node is not a leaf node - *
  • The drop point is on top of the last node of that node - *
- *

- * This does not fix the visual clue provided to the user, but fixes the actual drop location. - * - * @param tree the JTree in question - * @param location the original drop location - * @return the updated drop location - */ - private MyDropLocation convertDropLocation(JTree tree, JTree.DropLocation location) { - - final TreePath originalPath = location.getPath(); - final int originalIndex = location.getChildIndex(); - - if (originalPath == null || originalIndex <= 0) { - return new MyDropLocation(location); - } - - // Check whether previous node is a leaf node - TreeModel model = tree.getModel(); - Object previousNode = model.getChild(originalPath.getLastPathComponent(), originalIndex - 1); - if (model.isLeaf(previousNode)) { - return new MyDropLocation(location); - } - - // Find node on top of which the drop occurred - Point point = location.getDropPoint(); - TreePath dropPath = tree.getPathForLocation(point.x, point.y); - if (dropPath == null) { - return new MyDropLocation(location); - } - - // Check whether previousNode is in the ancestry of the actual drop location - boolean inAncestry = false; - for (Object o : dropPath.getPath()) { - if (o == previousNode) { - inAncestry = true; - break; - } - } - if (!inAncestry) { - return new MyDropLocation(location); - } - - // The bug has occurred - insert after the actual drop location - TreePath correctInsertPath = dropPath.getParentPath(); - int correctInsertIndex = model.getIndexOfChild(correctInsertPath.getLastPathComponent(), - dropPath.getLastPathComponent()) + 1; - - log.verbose("Working around Sun JRE bug 6560955: " + - "converted path=" + ComponentTreeModel.pathToString(originalPath) + " index=" + originalIndex + - " into path=" + ComponentTreeModel.pathToString(correctInsertPath) + - " index=" + correctInsertIndex); - - return new MyDropLocation(correctInsertPath, correctInsertIndex); - } - - private class MyDropLocation { - private final TreePath path; - private final int index; - - public MyDropLocation(JTree.DropLocation location) { - this(location.getPath(), location.getChildIndex()); - } - - public MyDropLocation(TreePath path, int index) { - this.path = path; - this.index = index; - } - - } -} diff --git a/core/src/net/sf/openrocket/gui/main/componenttree/RocketComponentTransferable.java b/core/src/net/sf/openrocket/gui/main/componenttree/RocketComponentTransferable.java deleted file mode 100644 index e9379dae..00000000 --- a/core/src/net/sf/openrocket/gui/main/componenttree/RocketComponentTransferable.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.sf.openrocket.gui.main.componenttree; - -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.io.IOException; - -import net.sf.openrocket.rocketcomponent.RocketComponent; - -/** - * A transferable that provides a reference to a (JVM-local) RocketComponent object. - * - * @author Sampo Niskanen - */ -public class RocketComponentTransferable implements Transferable { - - public static final DataFlavor ROCKET_COMPONENT_DATA_FLAVOR = new DataFlavor( - DataFlavor.javaJVMLocalObjectMimeType + "; class=" + RocketComponent.class.getCanonicalName(), - "OpenRocket component"); - - - private final RocketComponent component; - - public RocketComponentTransferable(RocketComponent component) { - this.component = component; - } - - - @Override - public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { - if (!isDataFlavorSupported(flavor)) { - throw new UnsupportedFlavorException(flavor); - } - return component; - } - - @Override - public DataFlavor[] getTransferDataFlavors() { - return new DataFlavor[] { ROCKET_COMPONENT_DATA_FLAVOR }; - } - - @Override - public boolean isDataFlavorSupported(DataFlavor flavor) { - return flavor.equals(ROCKET_COMPONENT_DATA_FLAVOR); - } - -} diff --git a/core/src/net/sf/openrocket/gui/plot/Axis.java b/core/src/net/sf/openrocket/gui/plot/Axis.java deleted file mode 100644 index 3f97ad36..00000000 --- a/core/src/net/sf/openrocket/gui/plot/Axis.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.sf.openrocket.gui.plot; - -import net.sf.openrocket.util.BugException; - -public class Axis implements Cloneable { - - private double minValue = Double.NaN; - private double maxValue = Double.NaN; - - - - public void addBound(double value) { - - if (value < minValue || Double.isNaN(minValue)) { - minValue = value; - } - if (value > maxValue || Double.isNaN(maxValue)) { - maxValue = value; - } - - } - - - public double getMinValue() { - return minValue; - } - - public double getMaxValue() { - return maxValue; - } - - public double getRangeLength() { - return maxValue - minValue; - } - - public void reset() { - minValue = Double.NaN; - maxValue = Double.NaN; - } - - - - @Override - public Axis clone() { - try { - - return (Axis) super.clone(); - - } catch (CloneNotSupportedException e) { - throw new BugException("BUG! Could not clone()."); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java b/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java deleted file mode 100644 index 4438b207..00000000 --- a/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java +++ /dev/null @@ -1,754 +0,0 @@ -package net.sf.openrocket.gui.plot; - -import java.util.EnumSet; -import java.util.List; -import java.util.Set; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Pair; - - -public class PlotConfiguration implements Cloneable { - - private static final Translator trans = Application.getTranslator(); - - public static final PlotConfiguration[] DEFAULT_CONFIGURATIONS; - static { - ArrayList configs = new ArrayList(); - PlotConfiguration config; - - //// Vertical motion vs. time - config = new PlotConfiguration(trans.get("PlotConfiguration.Verticalmotion")); - config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0); - config.addPlotDataType(FlightDataType.TYPE_VELOCITY_Z); - config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_Z); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - //// Total motion vs. time - config = new PlotConfiguration(trans.get("PlotConfiguration.Totalmotion")); - config.addPlotDataType(FlightDataType.TYPE_ALTITUDE, 0); - config.addPlotDataType(FlightDataType.TYPE_VELOCITY_TOTAL); - config.addPlotDataType(FlightDataType.TYPE_ACCELERATION_TOTAL); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - //// Flight side profile - config = new PlotConfiguration(trans.get("PlotConfiguration.Flightside"), FlightDataType.TYPE_POSITION_X); - config.addPlotDataType(FlightDataType.TYPE_ALTITUDE); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - //// Stability vs. time - config = new PlotConfiguration(trans.get("PlotConfiguration.Stability")); - config.addPlotDataType(FlightDataType.TYPE_STABILITY, 0); - config.addPlotDataType(FlightDataType.TYPE_CP_LOCATION, 1); - config.addPlotDataType(FlightDataType.TYPE_CG_LOCATION, 1); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - //// Drag coefficients vs. Mach number - config = new PlotConfiguration(trans.get("PlotConfiguration.Dragcoef"), - FlightDataType.TYPE_MACH_NUMBER); - config.addPlotDataType(FlightDataType.TYPE_DRAG_COEFF, 0); - config.addPlotDataType(FlightDataType.TYPE_FRICTION_DRAG_COEFF, 0); - config.addPlotDataType(FlightDataType.TYPE_BASE_DRAG_COEFF, 0); - config.addPlotDataType(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, 0); - configs.add(config); - - //// Roll characteristics - config = new PlotConfiguration(trans.get("PlotConfiguration.Rollcharacteristics")); - config.addPlotDataType(FlightDataType.TYPE_ROLL_RATE, 0); - config.addPlotDataType(FlightDataType.TYPE_ROLL_MOMENT_COEFF, 1); - config.addPlotDataType(FlightDataType.TYPE_ROLL_FORCING_COEFF, 1); - config.addPlotDataType(FlightDataType.TYPE_ROLL_DAMPING_COEFF, 1); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.LAUNCHROD, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - //// Angle of attack and orientation vs. time - config = new PlotConfiguration(trans.get("PlotConfiguration.Angleofattack")); - config.addPlotDataType(FlightDataType.TYPE_AOA, 0); - config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_PHI); - config.addPlotDataType(FlightDataType.TYPE_ORIENTATION_THETA); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - //// Simulation time step and computation time - config = new PlotConfiguration(trans.get("PlotConfiguration.Simulationtime")); - config.addPlotDataType(FlightDataType.TYPE_TIME_STEP); - config.addPlotDataType(FlightDataType.TYPE_COMPUTATION_TIME); - config.setEvent(FlightEvent.Type.IGNITION, true); - config.setEvent(FlightEvent.Type.BURNOUT, true); - config.setEvent(FlightEvent.Type.APOGEE, true); - config.setEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, true); - config.setEvent(FlightEvent.Type.STAGE_SEPARATION, true); - config.setEvent(FlightEvent.Type.GROUND_HIT, true); - configs.add(config); - - DEFAULT_CONFIGURATIONS = configs.toArray(new PlotConfiguration[0]); - } - - - - /** Bonus given for the first type being on the first axis */ - private static final double BONUS_FIRST_TYPE_ON_FIRST_AXIS = 1.0; - - /** - * Bonus given if the first axis includes zero (to prefer first axis having zero over - * the others) - */ - private static final double BONUS_FIRST_AXIS_HAS_ZERO = 2.0; - - /** Bonus given for a common zero point on left and right axes. */ - private static final double BONUS_COMMON_ZERO = 40.0; - - /** Bonus given for only using a single axis. */ - private static final double BONUS_ONLY_ONE_AXIS = 50.0; - - - private static final double INCLUDE_ZERO_DISTANCE = 0.3; // 30% of total range - - - - /** The data types to be plotted. */ - private ArrayList plotDataTypes = new ArrayList(); - - private ArrayList plotDataUnits = new ArrayList(); - - /** The corresponding Axis on which they will be plotted, or null to auto-select. */ - private ArrayList plotDataAxes = new ArrayList(); - - private EnumSet events = EnumSet.noneOf(FlightEvent.Type.class); - - /** The domain (x) axis. */ - private FlightDataType domainAxisType = null; - private Unit domainAxisUnit = null; - - - /** All available axes. */ - private final int axesCount; - private ArrayList allAxes = new ArrayList(); - - - - private String name = null; - - - - public PlotConfiguration() { - this(null, FlightDataType.TYPE_TIME); - } - - public PlotConfiguration(String name) { - this(name, FlightDataType.TYPE_TIME); - } - - public PlotConfiguration(String name, FlightDataType domainType) { - this.name = name; - // Two axes - allAxes.add(new Axis()); - allAxes.add(new Axis()); - axesCount = 2; - - setDomainAxisType(domainType); - } - - - - - - public FlightDataType getDomainAxisType() { - return domainAxisType; - } - - public void setDomainAxisType(FlightDataType type) { - boolean setUnit; - - if (domainAxisType != null && domainAxisType.getUnitGroup() == type.getUnitGroup()) - setUnit = false; - else - setUnit = true; - - domainAxisType = type; - if (setUnit) - domainAxisUnit = domainAxisType.getUnitGroup().getDefaultUnit(); - } - - public Unit getDomainAxisUnit() { - return domainAxisUnit; - } - - public void setDomainAxisUnit(Unit u) { - if (!domainAxisType.getUnitGroup().contains(u)) { - throw new IllegalArgumentException("Setting unit " + u + " to type " + domainAxisType); - } - domainAxisUnit = u; - } - - - - public void addPlotDataType(FlightDataType type) { - plotDataTypes.add(type); - plotDataUnits.add(type.getUnitGroup().getDefaultUnit()); - plotDataAxes.add(-1); - } - - public void addPlotDataType(FlightDataType type, int axis) { - if (axis >= axesCount) { - throw new IllegalArgumentException("Axis index too large"); - } - plotDataTypes.add(type); - plotDataUnits.add(type.getUnitGroup().getDefaultUnit()); - plotDataAxes.add(axis); - } - - - - - public void setPlotDataType(int index, FlightDataType type) { - FlightDataType origType = plotDataTypes.get(index); - plotDataTypes.set(index, type); - - if (origType.getUnitGroup() != type.getUnitGroup()) { - plotDataUnits.set(index, type.getUnitGroup().getDefaultUnit()); - } - } - - public void setPlotDataUnit(int index, Unit unit) { - if (!plotDataTypes.get(index).getUnitGroup().contains(unit)) { - throw new IllegalArgumentException("Attempting to set unit " + unit + " to group " - + plotDataTypes.get(index).getUnitGroup()); - } - plotDataUnits.set(index, unit); - } - - public void setPlotDataAxis(int index, int axis) { - if (axis >= axesCount) { - throw new IllegalArgumentException("Axis index too large"); - } - plotDataAxes.set(index, axis); - } - - - public void setPlotDataType(int index, FlightDataType type, Unit unit, int axis) { - if (axis >= axesCount) { - throw new IllegalArgumentException("Axis index too large"); - } - plotDataTypes.set(index, type); - plotDataUnits.set(index, unit); - plotDataAxes.set(index, axis); - } - - public void removePlotDataType(int index) { - plotDataTypes.remove(index); - plotDataUnits.remove(index); - plotDataAxes.remove(index); - } - - - - public FlightDataType getType(int index) { - return plotDataTypes.get(index); - } - - public Unit getUnit(int index) { - return plotDataUnits.get(index); - } - - public int getAxis(int index) { - return plotDataAxes.get(index); - } - - public int getTypeCount() { - return plotDataTypes.size(); - } - - - /// Events - - public Set getActiveEvents() { - return events.clone(); - } - - public void setEvent(FlightEvent.Type type, boolean active) { - if (active) { - events.add(type); - } else { - events.remove(type); - } - } - - public boolean isEventActive(FlightEvent.Type type) { - return events.contains(type); - } - - - - - - public List getAllAxes() { - List list = new ArrayList(); - list.addAll(allAxes); - return list; - } - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * Returns the name of this PlotConfiguration. - */ - @Override - public String toString() { - return name; - } - - - - /** - * Find the best combination of the auto-selectable axes. - * - * @return a new PlotConfiguration with the best fitting auto-selected axes and - * axes ranges selected. - */ - public PlotConfiguration fillAutoAxes(FlightDataBranch data) { - PlotConfiguration config = recursiveFillAutoAxes(data).getU(); - //System.out.println("BEST FOUND, fitting"); - config.fitAxes(data); - return config; - } - - - - - /** - * Recursively search for the best combination of the auto-selectable axes. - * This is a brute-force search method. - * - * @return a new PlotConfiguration with the best fitting auto-selected axes and - * axes ranges selected, and the goodness value - */ - private Pair recursiveFillAutoAxes(FlightDataBranch data) { - - // Create copy to fill in - PlotConfiguration copy = this.clone(); - - int autoindex; - for (autoindex = 0; autoindex < plotDataAxes.size(); autoindex++) { - if (plotDataAxes.get(autoindex) < 0) - break; - } - - - if (autoindex >= plotDataAxes.size()) { - // All axes have been assigned, just return since we are already the best - return new Pair(copy, copy.getGoodnessValue(data)); - } - - - // Set the auto-selected index one at a time and choose the best one - PlotConfiguration best = null; - double bestValue = Double.NEGATIVE_INFINITY; - for (int i = 0; i < axesCount; i++) { - copy.plotDataAxes.set(autoindex, i); - Pair result = copy.recursiveFillAutoAxes(data); - if (result.getV() > bestValue) { - best = result.getU(); - bestValue = result.getV(); - } - } - - return new Pair(best, bestValue); - } - - - - - - /** - * Fit the axes to hold the provided data. All of the plotDataAxis elements must - * be non-negative. - *

- * NOTE: This method assumes that only two axes are used. - */ - protected void fitAxes(FlightDataBranch data) { - - // Reset axes - for (Axis a : allAxes) { - a.reset(); - } - - // Add full range to the axes - int length = plotDataTypes.size(); - for (int i = 0; i < length; i++) { - FlightDataType type = plotDataTypes.get(i); - Unit unit = plotDataUnits.get(i); - int index = plotDataAxes.get(i); - if (index < 0) { - throw new IllegalStateException("fitAxes called with auto-selected axis"); - } - Axis axis = allAxes.get(index); - - double min = unit.toUnit(data.getMinimum(type)); - double max = unit.toUnit(data.getMaximum(type)); - - axis.addBound(min); - axis.addBound(max); - } - - // Ensure non-zero (or NaN) range, add a few percent range, include zero if it is close - for (Axis a : allAxes) { - if (MathUtil.equals(a.getMinValue(), a.getMaxValue())) { - a.addBound(a.getMinValue() - 1); - a.addBound(a.getMaxValue() + 1); - } - - double addition = a.getRangeLength() * 0.03; - a.addBound(a.getMinValue() - addition); - a.addBound(a.getMaxValue() + addition); - - double dist; - dist = Math.min(Math.abs(a.getMinValue()), Math.abs(a.getMaxValue())); - if (dist <= a.getRangeLength() * INCLUDE_ZERO_DISTANCE) { - a.addBound(0); - } - } - - - // Check whether to use a common zero - Axis left = allAxes.get(0); - Axis right = allAxes.get(1); - - if (left.getMinValue() > 0 || left.getMaxValue() < 0 || - right.getMinValue() > 0 || right.getMaxValue() < 0 || - Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue())) - return; - - - - //// Compute common zero - // TODO: MEDIUM: This algorithm may require tweaking - - double min1 = left.getMinValue(); - double max1 = left.getMaxValue(); - double min2 = right.getMinValue(); - double max2 = right.getMaxValue(); - - // Calculate and round scaling factor - double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / - Math.min(left.getRangeLength(), right.getRangeLength()); - - //System.out.println("Scale: " + scale); - - scale = roundScale(scale); - if (right.getRangeLength() > left.getRangeLength()) { - scale = 1 / scale; - } - //System.out.println("Rounded scale: " + scale); - - // Scale right axis, enlarge axes if necessary and scale back - min2 *= scale; - max2 *= scale; - min1 = Math.min(min1, min2); - min2 = min1; - max1 = Math.max(max1, max2); - max2 = max1; - min2 /= scale; - max2 /= scale; - - - - // Scale to unit length - // double scale1 = left.getRangeLength(); - // double scale2 = right.getRangeLength(); - // - // double min1 = left.getMinValue() / scale1; - // double max1 = left.getMaxValue() / scale1; - // double min2 = right.getMinValue() / scale2; - // double max2 = right.getMaxValue() / scale2; - // - // // Combine unit ranges - // min1 = MathUtil.min(min1, min2); - // min2 = min1; - // max1 = MathUtil.max(max1, max2); - // max2 = max1; - // - // // Scale up - // min1 *= scale1; - // max1 *= scale1; - // min2 *= scale2; - // max2 *= scale2; - // - // // Compute common scale - // double range1 = max1-min1; - // double range2 = max2-min2; - // - // double scale = MathUtil.max(range1, range2) / MathUtil.min(range1, range2); - // double roundScale = roundScale(scale); - // - // if (range2 < range1) { - // if (roundScale < scale) { - // min2 = min1 / roundScale; - // max2 = max1 / roundScale; - // } else { - // min1 = min2 * roundScale; - // max1 = max2 * roundScale; - // } - // } else { - // if (roundScale > scale) { - // min2 = min1 * roundScale; - // max2 = max1 * roundScale; - // } else { - // min1 = min2 / roundScale; - // max1 = max2 / roundScale; - // } - // } - - // Apply scale - left.addBound(min1); - left.addBound(max1); - right.addBound(min2); - right.addBound(max2); - - } - - - - private double roundScale(double scale) { - double mul = 1; - while (scale >= 10) { - scale /= 10; - mul *= 10; - } - while (scale < 1) { - scale *= 10; - mul /= 10; - } - - // 1 2 4 5 10 - - if (scale > 7.5) { - scale = 10; - } else if (scale > 4.5) { - scale = 5; - } else if (scale > 3) { - scale = 4; - } else if (scale > 1.5) { - scale = 2; - } else { - scale = 1; - } - return scale * mul; - } - - - - private double roundScaleUp(double scale) { - double mul = 1; - while (scale >= 10) { - scale /= 10; - mul *= 10; - } - while (scale < 1) { - scale *= 10; - mul /= 10; - } - - if (scale > 5) { - scale = 10; - } else if (scale > 4) { - scale = 5; - } else if (scale > 2) { - scale = 4; - } else if (scale > 1) { - scale = 2; - } else { - scale = 1; - } - return scale * mul; - } - - - private double roundScaleDown(double scale) { - double mul = 1; - while (scale >= 10) { - scale /= 10; - mul *= 10; - } - while (scale < 1) { - scale *= 10; - mul /= 10; - } - - if (scale > 5) { - scale = 5; - } else if (scale > 4) { - scale = 4; - } else if (scale > 2) { - scale = 2; - } else { - scale = 1; - } - return scale * mul; - } - - - - /** - * Fits the axis ranges to the data and returns the "goodness value" of this - * selection of axes. All plotDataAxis elements must be non-null. - *

- * NOTE: This method assumes that all data can fit into the axes ranges and - * that only two axes are used. - * - * @return a "goodness value", the larger the better. - */ - protected double getGoodnessValue(FlightDataBranch data) { - double goodness = 0; - int length = plotDataTypes.size(); - - // Fit the axes ranges to the data - fitAxes(data); - - /* - * Calculate goodness of ranges. 100 points is given if the values fill the - * entire range, 0 if they fill none of it. - */ - for (int i = 0; i < length; i++) { - FlightDataType type = plotDataTypes.get(i); - Unit unit = plotDataUnits.get(i); - int index = plotDataAxes.get(i); - if (index < 0) { - throw new IllegalStateException("getGoodnessValue called with auto-selected axis"); - } - Axis axis = allAxes.get(index); - - double min = unit.toUnit(data.getMinimum(type)); - double max = unit.toUnit(data.getMaximum(type)); - if (Double.isNaN(min) || Double.isNaN(max)) - continue; - if (MathUtil.equals(min, max)) - continue; - - double d = (max - min) / axis.getRangeLength(); - d = MathUtil.safeSqrt(d); // Prioritize small ranges - goodness += d * 100.0; - } - - - /* - * Add extra points for specific things. - */ - - // A little for the first type being on the first axis - if (plotDataAxes.get(0) == 0) - goodness += BONUS_FIRST_TYPE_ON_FIRST_AXIS; - - // A little bonus if the first axis contains zero - Axis left = allAxes.get(0); - if (left.getMinValue() <= 0 && left.getMaxValue() >= 0) - goodness += BONUS_FIRST_AXIS_HAS_ZERO; - - // A boost if a common zero was used in the ranging - Axis right = allAxes.get(1); - if (left.getMinValue() <= 0 && left.getMaxValue() >= 0 && - right.getMinValue() <= 0 && right.getMaxValue() >= 0) - goodness += BONUS_COMMON_ZERO; - - // A boost if only one axis is used - if (Double.isNaN(left.getMinValue()) || Double.isNaN(right.getMinValue())) - goodness += BONUS_ONLY_ONE_AXIS; - - return goodness; - } - - - - /** - * Reset the units of this configuration to the default units. Returns this - * PlotConfiguration. - * - * @return this PlotConfiguration. - */ - public PlotConfiguration resetUnits() { - for (int i = 0; i < plotDataTypes.size(); i++) { - plotDataUnits.set(i, plotDataTypes.get(i).getUnitGroup().getDefaultUnit()); - } - return this; - } - - - - - @Override - public PlotConfiguration clone() { - try { - - PlotConfiguration copy = (PlotConfiguration) super.clone(); - - // Shallow-clone all immutable lists - copy.plotDataTypes = this.plotDataTypes.clone(); - copy.plotDataAxes = this.plotDataAxes.clone(); - copy.plotDataUnits = this.plotDataUnits.clone(); - copy.events = this.events.clone(); - - // Deep-clone all Axis since they are mutable - copy.allAxes = new ArrayList(); - for (Axis a : this.allAxes) { - copy.allAxes.add(a.clone()); - } - - return copy; - - - } catch (CloneNotSupportedException e) { - throw new BugException("BUG! Could not clone()."); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java b/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java deleted file mode 100644 index ada19bfc..00000000 --- a/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java +++ /dev/null @@ -1,583 +0,0 @@ -package net.sf.openrocket.gui.plot; - -import java.awt.AlphaComposite; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import javax.imageio.ImageIO; -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.components.StyledLabel; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Preferences; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.annotations.XYImageAnnotation; -import org.jfree.chart.axis.NumberAxis; -import org.jfree.chart.axis.ValueAxis; -import org.jfree.chart.plot.Marker; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.plot.ValueMarker; -import org.jfree.chart.plot.XYPlot; -import org.jfree.chart.renderer.xy.StandardXYItemRenderer; -import org.jfree.chart.title.TextTitle; -import org.jfree.data.Range; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; -import org.jfree.text.TextUtilities; -import org.jfree.ui.LengthAdjustmentType; -import org.jfree.ui.RectangleAnchor; -import org.jfree.ui.TextAnchor; - -/** - * Dialog that shows a plot of a simulation results based on user options. - * - * @author Sampo Niskanen - */ -public class SimulationPlotDialog extends JDialog { - - private static final float PLOT_STROKE_WIDTH = 1.5f; - private static final Translator trans = Application.getTranslator(); - - private static final Color DEFAULT_EVENT_COLOR = new Color(0, 0, 0); - private static final Map EVENT_COLORS = - new HashMap(); - static { - EVENT_COLORS.put(FlightEvent.Type.LAUNCH, new Color(255, 0, 0)); - EVENT_COLORS.put(FlightEvent.Type.LIFTOFF, new Color(0, 80, 196)); - EVENT_COLORS.put(FlightEvent.Type.LAUNCHROD, new Color(0, 100, 80)); - EVENT_COLORS.put(FlightEvent.Type.IGNITION, new Color(230, 130, 15)); - EVENT_COLORS.put(FlightEvent.Type.BURNOUT, new Color(80, 55, 40)); - EVENT_COLORS.put(FlightEvent.Type.EJECTION_CHARGE, new Color(80, 55, 40)); - EVENT_COLORS.put(FlightEvent.Type.STAGE_SEPARATION, new Color(80, 55, 40)); - EVENT_COLORS.put(FlightEvent.Type.APOGEE, new Color(15, 120, 15)); - EVENT_COLORS.put(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, new Color(0, 0, 128)); - EVENT_COLORS.put(FlightEvent.Type.GROUND_HIT, new Color(0, 0, 0)); - EVENT_COLORS.put(FlightEvent.Type.SIMULATION_END, new Color(128, 0, 0)); - } - - private static final Map EVENT_IMAGES = - new HashMap(); - static { - loadImage(FlightEvent.Type.LAUNCH, "pix/eventicons/event-launch.png"); - loadImage(FlightEvent.Type.LIFTOFF, "pix/eventicons/event-liftoff.png"); - loadImage(FlightEvent.Type.LAUNCHROD, "pix/eventicons/event-launchrod.png"); - loadImage(FlightEvent.Type.IGNITION, "pix/eventicons/event-ignition.png"); - loadImage(FlightEvent.Type.BURNOUT, "pix/eventicons/event-burnout.png"); - loadImage(FlightEvent.Type.EJECTION_CHARGE, "pix/eventicons/event-ejection-charge.png"); - loadImage(FlightEvent.Type.STAGE_SEPARATION, - "pix/eventicons/event-stage-separation.png"); - loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png"); - loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, - "pix/eventicons/event-recovery-device-deployment.png"); - loadImage(FlightEvent.Type.GROUND_HIT, "pix/eventicons/event-ground-hit.png"); - loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png"); - } - - private static void loadImage(FlightEvent.Type type, String file) { - InputStream is; - - is = ClassLoader.getSystemResourceAsStream(file); - if (is == null) { - //System.out.println("ERROR: File " + file + " not found!"); - return; - } - - try { - Image image = ImageIO.read(is); - EVENT_IMAGES.put(type, image); - } catch (IOException ignore) { - ignore.printStackTrace(); - } - } - - - - - private final List renderers = - new ArrayList(); - - private SimulationPlotDialog(Window parent, Simulation simulation, PlotConfiguration config) { - //// Flight data plot - super(parent, trans.get("PlotDialog.title.Flightdataplot")); - this.setModalityType(ModalityType.DOCUMENT_MODAL); - - final boolean initialShowPoints = Application.getPreferences().getBoolean(Preferences.PLOT_SHOW_POINTS, false); - - - // Fill the auto-selections - FlightDataBranch branch = simulation.getSimulatedData().getBranch(0); - PlotConfiguration filled = config.fillAutoAxes(branch); - List axes = filled.getAllAxes(); - - - // Create the data series for both axes - XYSeriesCollection[] data = new XYSeriesCollection[2]; - data[0] = new XYSeriesCollection(); - data[1] = new XYSeriesCollection(); - - - // Get the domain axis type - final FlightDataType domainType = filled.getDomainAxisType(); - final Unit domainUnit = filled.getDomainAxisUnit(); - if (domainType == null) { - throw new IllegalArgumentException("Domain axis type not specified."); - } - List x = branch.get(domainType); - - - // Get plot length (ignore trailing NaN's) - int typeCount = filled.getTypeCount(); - int dataLength = 0; - for (int i = 0; i < typeCount; i++) { - FlightDataType type = filled.getType(i); - List y = branch.get(type); - - for (int j = dataLength; j < y.size(); j++) { - if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j))) - dataLength = j; - } - } - dataLength = Math.min(dataLength, x.size()); - - - // Create the XYSeries objects from the flight data and store into the collections - String[] axisLabel = new String[2]; - for (int i = 0; i < typeCount; i++) { - // Get info - FlightDataType type = filled.getType(i); - Unit unit = filled.getUnit(i); - int axis = filled.getAxis(i); - String name = getLabel(type, unit); - - // Store data in provided units - List y = branch.get(type); - XYSeries series = new XYSeries(name, false, true); - for (int j = 0; j < dataLength; j++) { - series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j))); - } - data[axis].addSeries(series); - - // Update axis label - if (axisLabel[axis] == null) - axisLabel[axis] = type.getName(); - else - axisLabel[axis] += "; " + type.getName(); - } - - - // Create the chart using the factory to get all default settings - JFreeChart chart = ChartFactory.createXYLineChart( - //// Simulated flight - trans.get("PlotDialog.Chart.Simulatedflight"), - null, - null, - null, - PlotOrientation.VERTICAL, - true, - true, - false - ); - - chart.addSubtitle(new TextTitle(config.getName())); - - // Add the data and formatting to the plot - XYPlot plot = chart.getXYPlot(); - int axisno = 0; - for (int i = 0; i < 2; i++) { - // Check whether axis has any data - if (data[i].getSeriesCount() > 0) { - // Create and set axis - double min = axes.get(i).getMinValue(); - double max = axes.get(i).getMaxValue(); - NumberAxis axis = new PresetNumberAxis(min, max); - axis.setLabel(axisLabel[i]); - // axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue()); - plot.setRangeAxis(axisno, axis); - - // Add data and map to the axis - plot.setDataset(axisno, data[i]); - ModifiedXYItemRenderer r = new ModifiedXYItemRenderer(); - r.setBaseShapesVisible(initialShowPoints); - r.setBaseShapesFilled(true); - for (int j = 0; j < data[i].getSeriesCount(); j++) { - r.setSeriesStroke(j, new BasicStroke(PLOT_STROKE_WIDTH)); - } - renderers.add(r); - plot.setRenderer(axisno, r); - plot.mapDatasetToRangeAxis(axisno, axisno); - axisno++; - } - } - - plot.getDomainAxis().setLabel(getLabel(domainType, domainUnit)); - plot.addDomainMarker(new ValueMarker(0)); - plot.addRangeMarker(new ValueMarker(0)); - - - - // Create list of events to show (combine event too close to each other) - ArrayList timeList = new ArrayList(); - ArrayList eventList = new ArrayList(); - ArrayList colorList = new ArrayList(); - ArrayList imageList = new ArrayList(); - - HashSet typeSet = new HashSet(); - - double prevTime = -100; - String text = null; - Color color = null; - Image image = null; - - List events = branch.getEvents(); - for (int i = 0; i < events.size(); i++) { - FlightEvent event = events.get(i); - double t = event.getTime(); - FlightEvent.Type type = event.getType(); - - if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) { - if (Math.abs(t - prevTime) <= 0.01) { - - if (!typeSet.contains(type)) { - text = text + ", " + type.toString(); - color = getEventColor(type); - image = EVENT_IMAGES.get(type); - typeSet.add(type); - } - - } else { - - if (text != null) { - timeList.add(prevTime); - eventList.add(text); - colorList.add(color); - imageList.add(image); - } - prevTime = t; - text = type.toString(); - color = getEventColor(type); - image = EVENT_IMAGES.get(type); - typeSet.clear(); - typeSet.add(type); - - } - } - } - if (text != null) { - timeList.add(prevTime); - eventList.add(text); - colorList.add(color); - imageList.add(image); - } - - - // Create the event markers - - if (config.getDomainAxisType() == FlightDataType.TYPE_TIME) { - - // Domain time is plotted as vertical markers - for (int i = 0; i < eventList.size(); i++) { - double t = timeList.get(i); - String event = eventList.get(i); - color = colorList.get(i); - - ValueMarker m = new ValueMarker(t); - m.setLabel(event); - m.setPaint(color); - m.setLabelPaint(color); - m.setAlpha(0.7f); - plot.addDomainMarker(m); - } - - } else { - - // Other domains are plotted as image annotations - List time = branch.get(FlightDataType.TYPE_TIME); - List domain = branch.get(config.getDomainAxisType()); - - for (int i = 0; i < eventList.size(); i++) { - final double t = timeList.get(i); - String event = eventList.get(i); - image = imageList.get(i); - - if (image == null) - continue; - - // Calculate index and interpolation position a - final double a; - int tindex = Collections.binarySearch(time, t); - if (tindex < 0) { - tindex = -tindex - 1; - } - if (tindex >= time.size()) { - // index greater than largest value in time list - tindex = time.size() - 1; - a = 0; - } else if (tindex <= 0) { - // index smaller than smallest value in time list - tindex = 0; - a = 0; - } else { - tindex--; - double t1 = time.get(tindex); - double t2 = time.get(tindex + 1); - - if ((t1 > t) || (t2 < t)) { - throw new BugException("t1=" + t1 + " t2=" + t2 + " t=" + t); - } - - if (MathUtil.equals(t1, t2)) { - a = 0; - } else { - a = 1 - (t - t1) / (t2 - t1); - } - } - - double xcoord; - if (a == 0) { - xcoord = domain.get(tindex); - } else { - xcoord = a * domain.get(tindex) + (1 - a) * domain.get(tindex + 1); - } - - for (int index = 0; index < config.getTypeCount(); index++) { - FlightDataType type = config.getType(index); - List range = branch.get(type); - - // Image annotations are not supported on the right-side axis - // TODO: LOW: Can this be achieved by JFreeChart? - if (filled.getAxis(index) != SimulationPlotPanel.LEFT) { - continue; - } - - double ycoord; - if (a == 0) { - ycoord = range.get(tindex); - } else { - ycoord = a * range.get(tindex) + (1 - a) * range.get(tindex + 1); - } - - // Convert units - xcoord = config.getDomainAxisUnit().toUnit(xcoord); - ycoord = config.getUnit(index).toUnit(ycoord); - - XYImageAnnotation annotation = - new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER); - annotation.setToolTipText(event); - plot.addAnnotation(annotation); - } - } - } - - - // Create the dialog - - JPanel panel = new JPanel(new MigLayout("fill")); - this.add(panel); - - ChartPanel chartPanel = new ChartPanel(chart, - false, // properties - true, // save - false, // print - true, // zoom - true); // tooltips - chartPanel.setMouseWheelEnabled(true); - chartPanel.setEnforceFileExtensions(true); - chartPanel.setInitialDelay(500); - - chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1)); - - panel.add(chartPanel, "grow, wrap 20lp"); - - //// Show data points - final JCheckBox check = new JCheckBox(trans.get("PlotDialog.CheckBox.Showdatapoints")); - check.setSelected(initialShowPoints); - check.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean show = check.isSelected(); - Application.getPreferences().putBoolean(Preferences.PLOT_SHOW_POINTS, show); - for (ModifiedXYItemRenderer r : renderers) { - r.setBaseShapesVisible(show); - } - } - }); - panel.add(check, "split, left"); - - - JLabel label = new StyledLabel(trans.get("PlotDialog.lbl.Chart"), -2); - panel.add(label, "gapleft para"); - - - panel.add(new JPanel(), "growx"); - - //// Close button - JButton button = new JButton(trans.get("dlg.but.close")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SimulationPlotDialog.this.dispose(); - } - }); - panel.add(button, "right"); - - this.setLocationByPlatform(true); - this.pack(); - - GUIUtil.setDisposableDialogOptions(this, button); - GUIUtil.rememberWindowSize(this); - } - - private String getLabel(FlightDataType type, Unit unit) { - String name = type.getName(); - if (unit != null && !UnitGroup.UNITS_NONE.contains(unit) && - !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0) - name += " (" + unit.getUnit() + ")"; - return name; - } - - - - private class PresetNumberAxis extends NumberAxis { - private final double min; - private final double max; - - public PresetNumberAxis(double min, double max) { - this.min = min; - this.max = max; - autoAdjustRange(); - } - - @Override - protected void autoAdjustRange() { - this.setRange(min, max); - } - } - - - /** - * Static method that shows a plot with the specified parameters. - * - * @param parent the parent window, which will be blocked. - * @param simulation the simulation to plot. - * @param config the configuration of the plot. - */ - public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) { - new SimulationPlotDialog(parent, simulation, config).setVisible(true); - } - - - - private static Color getEventColor(FlightEvent.Type type) { - Color c = EVENT_COLORS.get(type); - if (c != null) - return c; - return DEFAULT_EVENT_COLOR; - } - - - - - - /** - * A modification to the standard renderer that renders the domain marker - * labels vertically instead of horizontally. - */ - private static class ModifiedXYItemRenderer extends StandardXYItemRenderer { - - @Override - public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis, - Marker marker, Rectangle2D dataArea) { - - if (!(marker instanceof ValueMarker)) { - // Use parent for all others - super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea); - return; - } - - /* - * Draw the normal marker, but with rotated text. - * Copied from the overridden method. - */ - ValueMarker vm = (ValueMarker) marker; - double value = vm.getValue(); - Range range = domainAxis.getRange(); - if (!range.contains(value)) { - return; - } - - double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge()); - - PlotOrientation orientation = plot.getOrientation(); - Line2D line = null; - if (orientation == PlotOrientation.HORIZONTAL) { - line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v); - } else { - line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY()); - } - - final Composite originalComposite = g2.getComposite(); - g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker - .getAlpha())); - g2.setPaint(marker.getPaint()); - g2.setStroke(marker.getStroke()); - g2.draw(line); - - String label = marker.getLabel(); - RectangleAnchor anchor = marker.getLabelAnchor(); - if (label != null) { - Font labelFont = marker.getLabelFont(); - g2.setFont(labelFont); - g2.setPaint(marker.getLabelPaint()); - Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2, - orientation, dataArea, line.getBounds2D(), marker - .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor); - - // Changed: - TextAnchor textAnchor = TextAnchor.TOP_RIGHT; - TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX() + 2, - (float) coordinates.getY(), textAnchor, - -Math.PI / 2, textAnchor); - } - g2.setComposite(originalComposite); - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java b/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java deleted file mode 100644 index 515ad0c8..00000000 --- a/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java +++ /dev/null @@ -1,542 +0,0 @@ -package net.sf.openrocket.gui.plot; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.util.Arrays; -import java.util.EnumSet; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.components.DescriptionArea; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.util.Utils; - -/** - * Panel that displays the simulation plot options to the user. - * - * @author Sampo Niskanen - */ -public class SimulationPlotPanel extends JPanel { - private static final Translator trans = Application.getTranslator(); - - // TODO: LOW: Should these be somewhere else? - public static final int AUTO = -1; - public static final int LEFT = 0; - public static final int RIGHT = 1; - - //// Auto - public static final String AUTO_NAME = trans.get("simplotpanel.AUTO_NAME"); - //// Left - public static final String LEFT_NAME = trans.get("simplotpanel.LEFT_NAME"); - //// Right - public static final String RIGHT_NAME = trans.get("simplotpanel.RIGHT_NAME"); - - //// Custom - private static final String CUSTOM = trans.get("simplotpanel.CUSTOM"); - - /** The "Custom" configuration - not to be used for anything other than the title. */ - private static final PlotConfiguration CUSTOM_CONFIGURATION; - static { - CUSTOM_CONFIGURATION = new PlotConfiguration(CUSTOM); - } - - /** The array of presets for the combo box. */ - private static final PlotConfiguration[] PRESET_ARRAY; - static { - PRESET_ARRAY = Arrays.copyOf(PlotConfiguration.DEFAULT_CONFIGURATIONS, - PlotConfiguration.DEFAULT_CONFIGURATIONS.length + 1); - PRESET_ARRAY[PRESET_ARRAY.length - 1] = CUSTOM_CONFIGURATION; - } - - - - /** The current default configuration, set each time a plot is made. */ - private static PlotConfiguration defaultConfiguration = - PlotConfiguration.DEFAULT_CONFIGURATIONS[0].resetUnits(); - - - private final Simulation simulation; - private final FlightDataType[] types; - private PlotConfiguration configuration; - - - private JComboBox configurationSelector; - - private JComboBox domainTypeSelector; - private UnitSelector domainUnitSelector; - - private JPanel typeSelectorPanel; - private FlightEventTableModel eventTableModel; - - - private int modifying = 0; - - - public SimulationPlotPanel(final Simulation simulation) { - super(new MigLayout("fill")); - - this.simulation = simulation; - if (simulation.getSimulatedData() == null || - simulation.getSimulatedData().getBranchCount() == 0) { - throw new IllegalArgumentException("Simulation contains no data."); - } - FlightDataBranch branch = simulation.getSimulatedData().getBranch(0); - types = branch.getTypes(); - - setConfiguration(defaultConfiguration); - - //// Configuration selector - - // Setup the combo box - configurationSelector = new JComboBox(PRESET_ARRAY); - for (PlotConfiguration config : PRESET_ARRAY) { - if (config.getName().equals(configuration.getName())) { - configurationSelector.setSelectedItem(config); - } - } - - configurationSelector.addItemListener(new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - // We are only concerned with ItemEvent.SELECTED to update - // the UI when the selected item changes. - // TODO - this should probably be implemented as an ActionListener instead - // of ItemStateListener. - if ( e.getStateChange() == ItemEvent.DESELECTED) { - return; - } - if (modifying > 0) - return; - PlotConfiguration conf = (PlotConfiguration) configurationSelector.getSelectedItem(); - if (conf == CUSTOM_CONFIGURATION) - return; - modifying++; - setConfiguration(conf.clone().resetUnits()); - updatePlots(); - modifying--; - } - }); - //// Preset plot configurations: - this.add(new JLabel(trans.get("simplotpanel.lbl.Presetplotconf")), "spanx, split"); - this.add(configurationSelector, "growx, wrap 20lp"); - - - - //// X axis - - //// X axis type: - this.add(new JLabel(trans.get("simplotpanel.lbl.Xaxistype")), "spanx, split"); - domainTypeSelector = new JComboBox(types); - domainTypeSelector.setSelectedItem(configuration.getDomainAxisType()); - domainTypeSelector.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (modifying > 0) - return; - FlightDataType type = (FlightDataType) domainTypeSelector.getSelectedItem(); - configuration.setDomainAxisType(type); - domainUnitSelector.setUnitGroup(type.getUnitGroup()); - domainUnitSelector.setSelectedUnit(configuration.getDomainAxisUnit()); - setToCustom(); - } - }); - this.add(domainTypeSelector, "gapright para"); - - //// Unit: - this.add(new JLabel(trans.get("simplotpanel.lbl.Unit"))); - domainUnitSelector = new UnitSelector(configuration.getDomainAxisType().getUnitGroup()); - domainUnitSelector.setSelectedUnit(configuration.getDomainAxisUnit()); - domainUnitSelector.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (modifying > 0) - return; - configuration.setDomainAxisUnit(domainUnitSelector.getSelectedUnit()); - } - }); - this.add(domainUnitSelector, "width 40lp, gapright para"); - - //// The data will be plotted in time order even if the X axis type is not time. - DescriptionArea desc = new DescriptionArea(trans.get("simplotpanel.Desc"), 2, -2f); - desc.setViewportBorder(BorderFactory.createEmptyBorder()); - this.add(desc, "width 1px, growx 1, wrap unrel"); - - - - //// Y axis selector panel - //// Y axis types: - this.add(new JLabel(trans.get("simplotpanel.lbl.Yaxistypes"))); - //// Flight events: - this.add(new JLabel(trans.get("simplotpanel.lbl.Flightevents")), "wrap rel"); - - typeSelectorPanel = new JPanel(new MigLayout("gapy rel")); - JScrollPane scroll = new JScrollPane(typeSelectorPanel); - this.add(scroll, "spany 2, height 10px, wmin 400lp, grow 100, gapright para"); - - - //// Flight events - eventTableModel = new FlightEventTableModel(); - JTable table = new JTable(eventTableModel); - table.setTableHeader(null); - table.setShowVerticalLines(false); - table.setRowSelectionAllowed(false); - table.setColumnSelectionAllowed(false); - - TableColumnModel columnModel = table.getColumnModel(); - TableColumn col0 = columnModel.getColumn(0); - int w = table.getRowHeight() + 2; - col0.setMinWidth(w); - col0.setPreferredWidth(w); - col0.setMaxWidth(w); - table.addMouseListener(new GUIUtil.BooleanTableClickListener(table)); - this.add(new JScrollPane(table), "height 10px, width 200lp, grow 1, wrap rel"); - - - //// All + None buttons - JButton button = new JButton(trans.get("simplotpanel.but.All")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for (FlightEvent.Type t : FlightEvent.Type.values()) - configuration.setEvent(t, true); - eventTableModel.fireTableDataChanged(); - } - }); - this.add(button, "split 2, gapleft para, gapright para, growx, sizegroup buttons"); - - //// None - button = new JButton(trans.get("simplotpanel.but.None")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - for (FlightEvent.Type t : FlightEvent.Type.values()) - configuration.setEvent(t, false); - eventTableModel.fireTableDataChanged(); - } - }); - this.add(button, "gapleft para, gapright para, growx, sizegroup buttons, wrap para"); - - - - //// New Y axis plot type - button = new JButton(trans.get("simplotpanel.but.NewYaxisplottype")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (configuration.getTypeCount() >= 15) { - JOptionPane.showMessageDialog(SimulationPlotPanel.this, - //// A maximum of 15 plots is allowed. - //// Cannot add plot - trans.get("simplotpanel.OptionPane.lbl1"), - trans.get("simplotpanel.OptionPane.lbl2"), - JOptionPane.ERROR_MESSAGE); - return; - } - - // Select new type smartly - FlightDataType type = null; - for (FlightDataType t : - simulation.getSimulatedData().getBranch(0).getTypes()) { - - boolean used = false; - if (configuration.getDomainAxisType().equals(t)) { - used = true; - } else { - for (int i = 0; i < configuration.getTypeCount(); i++) { - if (configuration.getType(i).equals(t)) { - used = true; - break; - } - } - } - - if (!used) { - type = t; - break; - } - } - if (type == null) { - type = simulation.getSimulatedData().getBranch(0).getTypes()[0]; - } - - // Add new type - configuration.addPlotDataType(type); - setToCustom(); - updatePlots(); - } - }); - this.add(button, "spanx, split"); - - - this.add(new JPanel(), "growx"); - - //// Plot flight - button = new JButton(trans.get("simplotpanel.but.Plotflight")); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (configuration.getTypeCount() == 0) { - JOptionPane.showMessageDialog(SimulationPlotPanel.this, - trans.get("error.noPlotSelected"), - trans.get("error.noPlotSelected.title"), - JOptionPane.ERROR_MESSAGE); - return; - } - defaultConfiguration = configuration.clone(); - SimulationPlotDialog.showPlot(SwingUtilities.getWindowAncestor(SimulationPlotPanel.this), - simulation, configuration); - } - }); - this.add(button, "right"); - - - updatePlots(); - } - - - private void setConfiguration(PlotConfiguration conf) { - - boolean modified = false; - - configuration = conf.clone(); - if (!Utils.contains(types, configuration.getDomainAxisType())) { - configuration.setDomainAxisType(types[0]); - modified = true; - } - - for (int i = 0; i < configuration.getTypeCount(); i++) { - if (!Utils.contains(types, configuration.getType(i))) { - configuration.removePlotDataType(i); - i--; - modified = true; - } - } - - if (modified) { - configuration.setName(CUSTOM); - } - - } - - - private void setToCustom() { - modifying++; - configuration.setName(CUSTOM); - configurationSelector.setSelectedItem(CUSTOM_CONFIGURATION); - modifying--; - } - - - private void updatePlots() { - domainTypeSelector.setSelectedItem(configuration.getDomainAxisType()); - domainUnitSelector.setUnitGroup(configuration.getDomainAxisType().getUnitGroup()); - domainUnitSelector.setSelectedUnit(configuration.getDomainAxisUnit()); - - typeSelectorPanel.removeAll(); - for (int i = 0; i < configuration.getTypeCount(); i++) { - FlightDataType type = configuration.getType(i); - Unit unit = configuration.getUnit(i); - int axis = configuration.getAxis(i); - - typeSelectorPanel.add(new PlotTypeSelector(i, type, unit, axis), "wrap"); - } - - // In order to consistantly update the ui, we need to validate before repaint. - typeSelectorPanel.validate(); - typeSelectorPanel.repaint(); - - eventTableModel.fireTableDataChanged(); - } - - - - - /** - * A JPanel which configures a single plot of a PlotConfiguration. - */ - private class PlotTypeSelector extends JPanel { - private final String[] POSITIONS = { AUTO_NAME, LEFT_NAME, RIGHT_NAME }; - - private final int index; - private JComboBox typeSelector; - private UnitSelector unitSelector; - private JComboBox axisSelector; - - - public PlotTypeSelector(int plotIndex, FlightDataType type, Unit unit, int position) { - super(new MigLayout("ins 0")); - - this.index = plotIndex; - - typeSelector = new JComboBox(types); - typeSelector.setSelectedItem(type); - typeSelector.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (modifying > 0) - return; - FlightDataType type = (FlightDataType) typeSelector.getSelectedItem(); - configuration.setPlotDataType(index, type); - unitSelector.setUnitGroup(type.getUnitGroup()); - unitSelector.setSelectedUnit(configuration.getUnit(index)); - setToCustom(); - } - }); - this.add(typeSelector, "gapright para"); - - //// Unit: - this.add(new JLabel(trans.get("simplotpanel.lbl.Unit"))); - unitSelector = new UnitSelector(type.getUnitGroup()); - if (unit != null) - unitSelector.setSelectedUnit(unit); - unitSelector.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (modifying > 0) - return; - Unit unit = unitSelector.getSelectedUnit(); - configuration.setPlotDataUnit(index, unit); - } - }); - this.add(unitSelector, "width 40lp, gapright para"); - - //// Axis: - this.add(new JLabel(trans.get("simplotpanel.lbl.Axis"))); - axisSelector = new JComboBox(POSITIONS); - if (position == LEFT) - axisSelector.setSelectedIndex(1); - else if (position == RIGHT) - axisSelector.setSelectedIndex(2); - else - axisSelector.setSelectedIndex(0); - axisSelector.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (modifying > 0) - return; - int axis = axisSelector.getSelectedIndex() - 1; - configuration.setPlotDataAxis(index, axis); - } - }); - this.add(axisSelector); - - - JButton button = new JButton(Icons.DELETE); - //// Remove this plot - button.setToolTipText(trans.get("simplotpanel.but.ttip.Removethisplot")); - button.setBorderPainted(false); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - configuration.removePlotDataType(index); - setToCustom(); - updatePlots(); - } - }); - this.add(button, "gapright 0"); - } - } - - - - private class FlightEventTableModel extends AbstractTableModel { - private final FlightEvent.Type[] eventTypes; - - public FlightEventTableModel() { - EnumSet set = EnumSet.noneOf(FlightEvent.Type.class); - for (int i = 0; i < simulation.getSimulatedData().getBranchCount(); i++) { - for (FlightEvent e : simulation.getSimulatedData().getBranch(i).getEvents()) { - set.add(e.getType()); - } - } - set.remove(FlightEvent.Type.ALTITUDE); - int count = set.size(); - - eventTypes = new FlightEvent.Type[count]; - int pos = 0; - for (FlightEvent.Type t : FlightEvent.Type.values()) { - if (set.contains(t)) { - eventTypes[pos] = t; - pos++; - } - } - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public int getRowCount() { - return eventTypes.length; - } - - @Override - public Class getColumnClass(int column) { - switch (column) { - case 0: - return Boolean.class; - - case 1: - return String.class; - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - @Override - public Object getValueAt(int row, int column) { - switch (column) { - case 0: - return new Boolean(configuration.isEventActive(eventTypes[row])); - - case 1: - return eventTypes[row].toString(); - - default: - throw new IndexOutOfBoundsException("column=" + column); - } - } - - @Override - public boolean isCellEditable(int row, int column) { - return column == 0; - } - - @Override - public void setValueAt(Object value, int row, int column) { - if (column != 0 || !(value instanceof Boolean)) { - throw new IllegalArgumentException("column=" + column + ", value=" + value); - } - - configuration.setEvent(eventTypes[row], (Boolean) value); - this.fireTableCellUpdated(row, column); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/plugin/DoSomethingPlugin.java b/core/src/net/sf/openrocket/gui/plugin/DoSomethingPlugin.java deleted file mode 100644 index d238c4eb..00000000 --- a/core/src/net/sf/openrocket/gui/plugin/DoSomethingPlugin.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.sf.openrocket.gui.plugin; - -import javax.swing.Action; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.main.BasicFrame; - -public class DoSomethingPlugin extends OpenRocketSwingMenuPlugin { - - @Override - public Action getAction(BasicFrame frame, OpenRocketDocument document) { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/core/src/net/sf/openrocket/gui/plugin/OpenRocketSwingMenuPlugin.java b/core/src/net/sf/openrocket/gui/plugin/OpenRocketSwingMenuPlugin.java deleted file mode 100644 index e76e64a2..00000000 --- a/core/src/net/sf/openrocket/gui/plugin/OpenRocketSwingMenuPlugin.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.gui.plugin; - -import java.util.List; - -import net.sf.openrocket.plugin.framework.Service; - -public abstract class OpenRocketSwingMenuPlugin implements Service, SwingMenuPlugin { - - @Override - public String[] getMenuPosition() { - // TODO Auto-generated method stub - return null; - } - - - @Override - public List getPlugins(Class type, Object... args) { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/core/src/net/sf/openrocket/gui/plugin/SwingMenuPlugin.java b/core/src/net/sf/openrocket/gui/plugin/SwingMenuPlugin.java deleted file mode 100644 index e27b78ac..00000000 --- a/core/src/net/sf/openrocket/gui/plugin/SwingMenuPlugin.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.gui.plugin; - -import javax.swing.Action; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.main.BasicFrame; - -/** - * A plugin that provides a menu item to the Swing GUI menus. - * This may open a dialog window or perform some other action on - * the current document. - *

- * During plugin discovery, the BasicFrame and OpenRocketDocument - * objects are passed to the plugin. - * - * @author Sampo Niskanen - */ -public interface SwingMenuPlugin { - - /** - * Return the menu position where the action is placed. - * The first string in the array indicates the menu to place - * the item in, the second is the sub-menu, the third is the - * sub-sub-menu etc. - *

- * The strings are translated menu names. - * - * @return the menu position for the action - */ - public String[] getMenuPosition(); - - /** - * Return the Action that the menu item performs. This contains - * the menu item text and may contain an icon. - * - * @return the action to perform on the menu item. - */ - public Action getAction(BasicFrame frame, OpenRocketDocument document); - -} diff --git a/core/src/net/sf/openrocket/gui/preset/ButtonColumn.java b/core/src/net/sf/openrocket/gui/preset/ButtonColumn.java deleted file mode 100644 index 13b86535..00000000 --- a/core/src/net/sf/openrocket/gui/preset/ButtonColumn.java +++ /dev/null @@ -1,238 +0,0 @@ -package net.sf.openrocket.gui.preset; - -import javax.swing.AbstractCellEditor; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JTable; -import javax.swing.UIManager; -import javax.swing.border.Border; -import javax.swing.border.LineBorder; -import javax.swing.table.TableCellEditor; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumnModel; -import java.awt.Color; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; - -/** - * The ButtonColumn class provides a renderer and an editor that looks like a - * JButton. The renderer and editor will then be used for a specified column - * in the table. The TableModel will contain the String to be displayed on - * the button. - * - * The button can be invoked by a mouse click or by pressing the space bar - * when the cell has focus. Optionaly a mnemonic can be set to invoke the - * button. When the button is invoked the provided Action is invoked. The - * source of the Action will be the table. The action command will contain - * the model row number of the button that was clicked. - * - * Credits: A post by Rob Camick http://tips4java.wordpress.com/2009/07/12/table-button-column/ - */ -public class ButtonColumn extends AbstractCellEditor - implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener -{ - private JTable table; - private Action action; - private int mnemonic; - private Border originalBorder; - private Border focusBorder; - - private JButton renderButton; - private JButton editButton; - private Object editorValue; - private boolean isButtonColumnEditor; - - /** - * Create the ButtonColumn to be used as a renderer and editor. The - * renderer and editor will automatically be installed on the TableColumn - * of the specified column. - * - * @param table the table containing the button renderer/editor - * @param action the Action to be invoked when the button is invoked - * @param column the column to which the button renderer/editor is added - */ - public ButtonColumn(JTable table, Action action, int column) - { - this.table = table; - this.action = action; - - renderButton = new JButton(); - editButton = new JButton(); - editButton.setFocusPainted( false ); - editButton.addActionListener( this ); - originalBorder = editButton.getBorder(); - setFocusBorder( new LineBorder(Color.BLUE) ); - - TableColumnModel columnModel = table.getColumnModel(); - columnModel.getColumn(column).setCellRenderer( this ); - columnModel.getColumn(column).setCellEditor( this ); - table.addMouseListener( this ); - } - - - /** - * Get foreground color of the button when the cell has focus - * - * @return the foreground color - */ - public Border getFocusBorder() - { - return focusBorder; - } - - /** - * The foreground color of the button when the cell has focus - * - * @param focusBorder the foreground color - */ - public void setFocusBorder(Border focusBorder) - { - this.focusBorder = focusBorder; - editButton.setBorder( focusBorder ); - } - - public int getMnemonic() - { - return mnemonic; - } - - /** - * The mnemonic to activate the button when the cell has focus - * - * @param mnemonic the mnemonic - */ - public void setMnemonic(int mnemonic) - { - this.mnemonic = mnemonic; - renderButton.setMnemonic(mnemonic); - editButton.setMnemonic(mnemonic); - } - - @Override - public Component getTableCellEditorComponent( - JTable table, Object value, boolean isSelected, int row, int column) - { - if (value == null) - { - editButton.setText( "" ); - editButton.setIcon( null ); - } - else if (value instanceof Icon) - { - editButton.setText( "" ); - editButton.setIcon( (Icon)value ); - } - else - { - editButton.setText( value.toString() ); - editButton.setIcon( null ); - } - - this.editorValue = value; - return editButton; - } - - @Override - public Object getCellEditorValue() - { - return editorValue; - } - -// -// Implement TableCellRenderer interface -// - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) - { - if (isSelected) - { - renderButton.setForeground(table.getSelectionForeground()); - renderButton.setBackground(table.getSelectionBackground()); - } - else - { - renderButton.setForeground(table.getForeground()); - renderButton.setBackground(UIManager.getColor("Button.background")); - } - - if (hasFocus) - { - renderButton.setBorder( focusBorder ); - } - else - { - renderButton.setBorder( originalBorder ); - } - -// renderButton.setText( (value == null) ? "" : value.toString() ); - if (value == null) - { - renderButton.setText( "" ); - renderButton.setIcon( null ); - } - else if (value instanceof Icon) - { - renderButton.setText( "" ); - renderButton.setIcon( (Icon)value ); - } - else - { - renderButton.setText( value.toString() ); - renderButton.setIcon( null ); - } - - return renderButton; - } - -// -// Implement ActionListener interface -// - /* - * The button has been pressed. Stop editing and invoke the custom Action - */ - public void actionPerformed(ActionEvent e) - { - int row = table.convertRowIndexToModel( table.getEditingRow() ); - fireEditingStopped(); - - // Invoke the Action - - ActionEvent event = new ActionEvent( - table, - ActionEvent.ACTION_PERFORMED, - "" + row); - action.actionPerformed(event); - } - -// -// Implement MouseListener interface -// - /* - * When the mouse is pressed the editor is invoked. If you then drag - * the mouse to another cell before releasing it, the editor is still - * active. Make sure editing is stopped when the mouse is released. - */ - public void mousePressed(MouseEvent e) - { - if (table.isEditing() - && table.getCellEditor() == this) - isButtonColumnEditor = true; - } - - public void mouseReleased(MouseEvent e) - { - if (isButtonColumnEditor - && table.isEditing()) - table.getCellEditor().stopCellEditing(); - - isButtonColumnEditor = false; - } - - public void mouseClicked(MouseEvent e) {} - public void mouseEntered(MouseEvent e) {} - public void mouseExited(MouseEvent e) {} -} diff --git a/core/src/net/sf/openrocket/gui/preset/ComponentPresetEditor.java b/core/src/net/sf/openrocket/gui/preset/ComponentPresetEditor.java deleted file mode 100644 index 9f11cdd6..00000000 --- a/core/src/net/sf/openrocket/gui/preset/ComponentPresetEditor.java +++ /dev/null @@ -1,505 +0,0 @@ -package net.sf.openrocket.gui.preset; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JTable; -import javax.swing.table.DefaultTableModel; -import javax.xml.bind.JAXBException; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.FileHelper; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.loader.MaterialHolder; -import net.sf.openrocket.preset.loader.RocksimComponentFileTranslator; -import net.sf.openrocket.preset.xml.OpenRocketComponentDTO; -import net.sf.openrocket.preset.xml.OpenRocketComponentSaver; -import net.sf.openrocket.startup.Application; - -/** - * A UI for editing component presets. Currently this is a standalone application - run the main within this class. - * TODO: Full I18n TODO: Save As .csv - */ -public class ComponentPresetEditor extends JPanel implements PresetResultListener { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The I18N translator. - */ - private static ResourceBundleTranslator trans = null; - - /** - * The table of presets. - */ - private JTable table; - - /** - * The table's data model. - */ - private DataTableModel model; - - /** - * Flag that indicates if an existing Preset is currently being edited. - */ - // private boolean editingSelected = false; - - private final OpenedFileContext editContext = new OpenedFileContext(); - - static { - trans = new ResourceBundleTranslator("l10n.messages"); - net.sf.openrocket.startup.Application.setBaseTranslator(trans); - } - - /** - * Create the panel. - * - * @param frame the parent window - */ - public ComponentPresetEditor(final JFrame frame) { - setLayout(new MigLayout("", "[82.00px, grow][168.00px, grow][84px, grow][117.00px, grow][][222px]", - "[346.00px, grow][29px]")); - - model = new DataTableModel(new String[]{"Manufacturer", "Type", "Part No", "Description", ""}); - - table = new JTable(model); - table.getTableHeader().setFont(new JLabel().getFont()); - //The action never gets called because the table MouseAdapter intercepts it first. Still need an empty - // instance though. - Action action = new AbstractAction() { - @Override - public void actionPerformed(final ActionEvent e) { - } - }; - //Create a editor/renderer for the delete operation. Instantiation self-registers into the table. - new ButtonColumn(table, action, 4); - table.getColumnModel().getColumn(4).setMaxWidth(Icons.EDIT_DELETE.getIconWidth()); - table.getColumnModel().getColumn(4).setMinWidth(Icons.EDIT_DELETE.getIconWidth()); - - JScrollPane scrollPane = new JScrollPane(table); - table.setFillsViewportHeight(true); - table.setAutoCreateRowSorter(true); - add(scrollPane, "cell 0 0 6 1,grow"); - - table.addMouseListener(new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - JTable target = (JTable) e.getSource(); - int selectedColumn = table.getColumnModel().getColumnIndexAtX( target.getSelectedColumn() ); - int selectedRow = table.getRowSorter().convertRowIndexToModel( target.getSelectedRow() ); - if (selectedColumn == 4) { - if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(ComponentPresetEditor.this, - "Do you want to delete this preset?", - "Confirm Delete", JOptionPane.YES_OPTION, - JOptionPane.QUESTION_MESSAGE)) { - model.removeRow(selectedRow); - } - } - else { - if (e.getClickCount() == 2) { - editContext.setEditingSelected(true); - new PresetEditorDialog(ComponentPresetEditor.this, - (ComponentPreset) model.getAssociatedObject(selectedRow), editContext.getMaterialsLoaded()).setVisible(true); - } - } - } - }); - - - JMenuBar menuBar = new JMenuBar(); - frame.setJMenuBar(menuBar); - - JMenu mnFile = new JMenu("File"); - menuBar.add(mnFile); - - JMenuItem mntmOpen = new JMenuItem("Open..."); - mnFile.add(mntmOpen); - mntmOpen.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - if (model.getRowCount() > 0) { - /* - * If the table model already contains presets, ask the user if they a) want to discard those - * presets, b) save them before reading in another component file, or c) merge the read component file - * with the current contents of the table model. - */ - Object[] options = {"Save", - "Merge", - "Discard", - "Cancel"}; - int n = JOptionPane.showOptionDialog(frame, - "The editor contains existing component presets. What would you like to do with them?", - "Existing Component Presets", - JOptionPane.YES_NO_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, - options, - options[0]); - if (n == 0) { //Save. Then remove existing rows and open. - if (saveAndHandleError()) { - model.removeAllRows(); - } - else { //Save failed; bail out. - return; - } - } - else if (n == 2) { //Discard and open - model.removeAllRows(); - } - else if (n == 3) { //Cancel. Bail out. - return; - } - } - //Open file dialog - openComponentFile(); - } - }); - - JSeparator separator = new JSeparator(); - mnFile.add(separator); - - JMenuItem mntmSave = new JMenuItem("Save As..."); - mnFile.add(mntmSave); - mntmSave.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - saveAndHandleError(); - } - }); - - JSeparator separator_1 = new JSeparator(); - mnFile.add(separator_1); - - JMenuItem mntmExit = new JMenuItem("Exit"); - mnFile.add(mntmExit); - mntmExit.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent arg0) { - System.exit(0); - } - }); - - - JButton addBtn = new JButton("Add"); - addBtn.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent arg0) { - editContext.setEditingSelected(false); - new PresetEditorDialog(ComponentPresetEditor.this).setVisible(true); - } - }); - add(addBtn, "cell 0 1,alignx left,aligny top"); - } - - /** - * Callback method from the PresetEditorDialog to notify this class when a preset has been saved. The 'save' is - * really just a call back here so the preset can be added to the master table. It's not to be confused with the - * save to disk. - * - * @param preset the new or modified preset - */ - @Override - public void notifyResult(final ComponentPreset preset) { - if (preset != null) { - DataTableModel model = (DataTableModel) table.getModel(); - //Is this a new preset? - String description = preset.has(ComponentPreset.DESCRIPTION) ? preset.get(ComponentPreset.DESCRIPTION) : - preset.getPartNo(); - if (!editContext.isEditingSelected()|| table.getSelectedRow() == -1) { - model.addRow(new Object[]{preset.getManufacturer().getDisplayName(), preset.getType().name(), - preset.getPartNo(), description, Icons.EDIT_DELETE}, preset); - } - else { - //This is a modified preset; update all of the columns and the stored associated instance. - int row = table.getSelectedRow(); - model.setValueAt(preset.getManufacturer().getDisplayName(), row, 0); - model.setValueAt(preset.getType().name(), row, 1); - model.setValueAt(preset.getPartNo(), row, 2); - model.setValueAt(description, row, 3); - model.associated.set(row, preset); - } - } - editContext.setEditingSelected(false); - } - - /** - * Launch the test main. - */ - public static void main(String[] args) { - try { - Application.setPreferences(new SwingPreferences()); - JFrame dialog = new JFrame(); - dialog.getContentPane().add(new ComponentPresetEditor(dialog)); - dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - dialog.pack(); - dialog.setVisible(true); - } - catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * A table model that adds associated objects to each row, allowing for easy retrieval. - */ - class DataTableModel extends DefaultTableModel { - - private List associated = new ArrayList(); - - /** - * Constructs a DefaultTableModel with as many columns as there are elements in - * columnNames and rowCount of null object values. Each column's name - * will be taken from the columnNames array. - * - * @param columnNames array containing the names of the new columns; if this is null - * then the model has no columns - * - * @see #setDataVector - * @see #setValueAt - */ - DataTableModel(final Object[] columnNames) { - super(columnNames, 0); - } - - public void addRow(Object[] data, Object associatedData) { - super.addRow(data); - associated.add(getRowCount() - 1, associatedData); - } - - public void removeAllRows() { - for (int x = getRowCount(); x > 0; x--) { - super.removeRow(x - 1); - } - associated.clear(); - } - - public void removeRow(int row) { - super.removeRow(row); - associated.remove(row); - } - - public Object getAssociatedObject(int row) { - return associated.get(row); - } - - public boolean isCellEditable(int rowIndex, int mColIndex) { - return false; - } - } - - /** - * Open the component file. Present a chooser for the user to navigate to the file. - * - * @return true if the file was successfully opened; Note: side effect, is that the ComponentPresets read from the - * file are written to the table model. - */ - private boolean openComponentFile() { - final JFileChooser chooser = new JFileChooser(); - chooser.addChoosableFileFilter(FileHelper.OPEN_ROCKET_COMPONENT_FILTER); - chooser.addChoosableFileFilter(FileHelper.CSV_FILE_FILTER); - chooser.setFileFilter(FileHelper.OPEN_ROCKET_COMPONENT_FILTER); - chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); - if (editContext.getLastDirectory() != null) { - chooser.setCurrentDirectory(editContext.getLastDirectory()); - } - else { - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - } - - int option = chooser.showOpenDialog(ComponentPresetEditor.this); - if (option != JFileChooser.APPROVE_OPTION) { - editContext.setOpenedFile(null); - log.user("User decided not to open, option=" + option); - return false; - } - - File file = chooser.getSelectedFile(); - try { - if (file == null) { - log.user("User did not select a file"); - return false; - } - - editContext.setLastDirectory(file.getParentFile()); - editContext.setMaterialsLoaded(null); - List presets = null; - - if (file.getName().toLowerCase().endsWith(".orc")) { - OpenRocketComponentDTO fileContents = new OpenRocketComponentSaver().unmarshalFromOpenRocketComponent(new FileReader(file)); - editContext.setMaterialsLoaded( new MaterialHolder(fileContents.asMaterialList()) ); - presets = fileContents.asComponentPresets(); - } - else { - if (file.getName().toLowerCase().endsWith(".csv")) { - file = file.getParentFile(); - } - presets = new ArrayList(); - MaterialHolder materialHolder = RocksimComponentFileTranslator.loadAll(presets, file); - editContext.setMaterialsLoaded(materialHolder); - } - if (presets != null) { - for (ComponentPreset next : presets) { - notifyResult(next); - } - editContext.setOpenedFile(file); - } - } - catch (Exception e) { - JOptionPane.showMessageDialog(ComponentPresetEditor.this, "Unable to open OpenRocket component file: " + - file.getName() + " Invalid format. " + e.getMessage()); - editContext.setOpenedFile(null); - editContext.setEditingSelected(false); - return false; - } - return true; - } - - private boolean saveAndHandleError() { - try { - return saveAsORC(); - } - catch (Exception e1) { - JOptionPane.showMessageDialog(ComponentPresetEditor.this, e1.getLocalizedMessage(), - "Error saving ORC file.", JOptionPane.ERROR_MESSAGE); - return false; - } - } - - /** - * Save the contents of the table model as XML in .orc format. - * - * @return true if the file was written - * - * @throws JAXBException thrown if the data could not be marshaled - * @throws IOException thrown if there was a problem with writing the file - */ - private boolean saveAsORC() throws JAXBException, IOException { - File file = null; - - final JFileChooser chooser = new JFileChooser(); - chooser.addChoosableFileFilter(FileHelper.OPEN_ROCKET_COMPONENT_FILTER); - - chooser.setFileFilter(FileHelper.OPEN_ROCKET_COMPONENT_FILTER); - if (editContext.getOpenedFile() != null) { - chooser.setSelectedFile(editContext.getOpenedFile()); - } - else { - chooser.setCurrentDirectory(((SwingPreferences) Application.getPreferences()).getDefaultDirectory()); - } - - int option = chooser.showSaveDialog(ComponentPresetEditor.this); - if (option != JFileChooser.APPROVE_OPTION) { - log.user("User decided not to save, option=" + option); - return false; - } - - file = chooser.getSelectedFile(); - if (file == null) { - log.user("User did not select a file"); - return false; - } - - ((SwingPreferences) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory()); - - file = FileHelper.forceExtension(file, "orc"); - - MaterialHolder materials = new MaterialHolder(); - List presets = new ArrayList(); - - for (int x = 0; x < model.getRowCount(); x++) { - ComponentPreset preset = (ComponentPreset) model.getAssociatedObject(x); - // If we don't have a material already defined for saving... - if ( materials.getMaterial(preset.get(ComponentPreset.MATERIAL)) == null ) { - // Check if we loaded a material with this name. - Material m = editContext.getMaterialsLoaded().getMaterial(preset.get(ComponentPreset.MATERIAL)); - // If there was no material loaded with that name, use the component's material. - if ( m == null ) { - m = preset.get(ComponentPreset.MATERIAL); - } - materials.put(m); - } - presets.add(preset); - } - - return FileHelper.confirmWrite(file, this) && new OpenRocketComponentSaver().save(file, new ArrayList(materials.values()), presets); - } - - class OpenedFileContext { - - /** - * State variable to keep track of which file was opened, in case it needs to be saved back to that file. - */ - private File openedFile = null; - - /** - * Last directory; file chooser is set here so user doesn't have to keep navigating to a common area. - */ - private File lastDirectory = null; - - private boolean editingSelected = false; - - private MaterialHolder materialsLoaded = null; - - OpenedFileContext() { - } - - public File getOpenedFile() { - return openedFile; - } - - public void setOpenedFile(final File theOpenedFile) { - openedFile = theOpenedFile; - } - - public File getLastDirectory() { - return lastDirectory; - } - - public void setLastDirectory(final File theLastDirectory) { - lastDirectory = theLastDirectory; - } - - public boolean isEditingSelected() { - return editingSelected; - } - - public void setEditingSelected(final boolean theEditingSelected) { - editingSelected = theEditingSelected; - } - - public MaterialHolder getMaterialsLoaded() { - return materialsLoaded; - } - - public void setMaterialsLoaded(final MaterialHolder theMaterialsLoaded) { - materialsLoaded = theMaterialsLoaded; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/preset/DeselectableComboBox.java b/core/src/net/sf/openrocket/gui/preset/DeselectableComboBox.java deleted file mode 100644 index 758a8507..00000000 --- a/core/src/net/sf/openrocket/gui/preset/DeselectableComboBox.java +++ /dev/null @@ -1,83 +0,0 @@ -package net.sf.openrocket.gui.preset; - -import javax.swing.*; -import javax.swing.plaf.basic.BasicComboBoxRenderer; -import java.awt.*; -import java.util.HashSet; -import java.util.Set; - -/** - * A combo box that allows for items to be deselected. - */ -public class DeselectableComboBox extends JComboBox { - - public DeselectableComboBox() { - super(); - super.setRenderer(new DeselectedtemsRenderer()); - } - - private Set disabled_items = new HashSet(); - - public void addItem(Object anObject, boolean disabled) { - super.addItem(anObject); - if (disabled) { - disabled_items.add(getItemCount() - 1); - } - } - - @Override - public void removeAllItems() { - super.removeAllItems(); - disabled_items = new HashSet(); - } - - @Override - public void removeItemAt(final int anIndex) { - super.removeItemAt(anIndex); - disabled_items.remove(anIndex); - } - - @Override - public void removeItem(final Object anObject) { - for (int i = 0; i < getItemCount(); i++) { - if (getItemAt(i) == anObject) { - disabled_items.remove(i); - } - } - super.removeItem(anObject); - } - - @Override - public void setSelectedIndex(int index) { - if (!disabled_items.contains(index)) { - super.setSelectedIndex(index); - } - } - - private class DeselectedtemsRenderer extends BasicComboBoxRenderer { - - @Override - public Component getListCellRendererComponent(JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus) { - - if (isSelected) { - setBackground(list.getSelectionBackground()); - setForeground(list.getSelectionForeground()); - } - else { - setBackground(list.getBackground()); - setForeground(list.getForeground()); - } - if (disabled_items.contains(index)) { - setBackground(list.getBackground()); - setForeground(UIManager.getColor("Label.disabledForeground")); - } - setFont(list.getFont()); - setText((value == null) ? "" : value.toString()); - return this; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/preset/ImagePreviewPanel.java b/core/src/net/sf/openrocket/gui/preset/ImagePreviewPanel.java deleted file mode 100644 index bab36ec5..00000000 --- a/core/src/net/sf/openrocket/gui/preset/ImagePreviewPanel.java +++ /dev/null @@ -1,105 +0,0 @@ - -package net.sf.openrocket.gui.preset; - - -import javax.swing.*; -import java.awt.*; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; - -/** - * From a JavaLobby article by Michael Urban: http://www.javalobby.org/java/forums/t49462.html - */ -public class ImagePreviewPanel extends JPanel - implements PropertyChangeListener { - - private int width, height; - private ImageIcon icon; - private Image image; - private static final int ACCSIZE = 155; - private Color bg; - - public ImagePreviewPanel() { - setPreferredSize(new Dimension(ACCSIZE, -1)); - bg = getBackground(); - } - - public void propertyChange(PropertyChangeEvent e) { - String propertyName = e.getPropertyName(); - - // Make sure we are responding to the right event. - if (propertyName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) { - File selection = (File)e.getNewValue(); - String name; - - if (selection == null) - return; - else - name = selection.getAbsolutePath(); - - /* - * Make reasonably sure we have an image format that AWT can - * handle so we don't try to draw something silly. - */ - if ((name != null) && - name.toLowerCase().endsWith(".jpg") || - name.toLowerCase().endsWith(".jpeg") || - name.toLowerCase().endsWith(".gif") || - name.toLowerCase().endsWith(".png")) { - icon = new ImageIcon(name); - image = icon.getImage(); - scaleImage(); - repaint(); - } - } - } - - private void scaleImage() { - width = image.getWidth(this); - height = image.getHeight(this); - double ratio = 1.0; - - /* - * Determine how to scale the image. Since the accessory can expand - * vertically make sure we don't go larger than 150 when scaling - * vertically. - */ - if (width >= height) { - ratio = (double)(ACCSIZE-5) / width; - width = ACCSIZE-5; - height = (int)(height * ratio); - } - else { - if (getHeight() > 150) { - ratio = (double)(ACCSIZE-5) / height; - height = ACCSIZE-5; - width = (int)(width * ratio); - } - else { - ratio = (double)getHeight() / height; - height = getHeight(); - width = (int)(width * ratio); - } - } - - image = image.getScaledInstance(width, height, Image.SCALE_DEFAULT); - } - - public void paintComponent(Graphics g) { - g.setColor(bg); - - /* - * If we don't do this, we will end up with garbage from previous - * images if they have larger sizes than the one we are currently - * drawing. Also, it seems that the file list can paint outside - * of its rectangle, and will cause odd behavior if we don't clear - * or fill the rectangle for the accessory before drawing. This might - * be a bug in JFileChooser. - */ - g.fillRect(0, 0, ACCSIZE, getHeight()); - g.drawImage(image, getWidth() / 2 - width / 2 + 5, - getHeight() / 2 - height / 2, this); - } - -} diff --git a/core/src/net/sf/openrocket/gui/preset/MaterialModel.java b/core/src/net/sf/openrocket/gui/preset/MaterialModel.java deleted file mode 100644 index f51f2146..00000000 --- a/core/src/net/sf/openrocket/gui/preset/MaterialModel.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.sf.openrocket.gui.preset; - -import net.sf.openrocket.database.Database; -import net.sf.openrocket.database.DatabaseListener; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.gui.dialogs.CustomMaterialDialog; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.loader.MaterialHolder; -import net.sf.openrocket.startup.Application; - -import javax.swing.DefaultComboBoxModel; -import javax.swing.SwingUtilities; -import java.awt.Component; - -/** - * A material model specifically for presets. - */ -public class MaterialModel extends DefaultComboBoxModel implements DatabaseListener { - - private static final String CUSTOM = "Custom"; - - private final Database database; - - private static final Translator trans = Application.getTranslator(); - - private Material.Type type; - - private Component parent; - - public MaterialModel(Component theParent, Material.Type theType, Database materials) { - parent = theParent; - type = theType; - database = materials; - database.addDatabaseListener(this); - } - - public MaterialModel(Component theParent, Material.Type theType) { - parent = theParent; - type = theType; - - switch (type) { - case LINE: - this.database = Databases.LINE_MATERIAL; - break; - - case BULK: - this.database = Databases.BULK_MATERIAL; - break; - - case SURFACE: - this.database = Databases.SURFACE_MATERIAL; - break; - - default: - throw new IllegalArgumentException("Unknown material type:" + type); - } - - database.addDatabaseListener(this); - } - - @Override - public void setSelectedItem(Object item) { - if (item == null) { - // Clear selection - huh? - return; - } - - if (item == CUSTOM) { - - // Open custom material dialog in the future, after combo box has closed - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - CustomMaterialDialog dialog = new CustomMaterialDialog(SwingUtilities.getWindowAncestor(parent), (Material) getSelectedItem(), true, - //// Define custom material - trans.get("MaterialModel.title.Defcustmat")); - - dialog.setVisible(true); - - if (!dialog.getOkClicked()) { - return; - } - - Material material = dialog.getMaterial(); - MaterialModel.super.setSelectedItem(material); - if (dialog.isAddSelected()) { - database.add(material); - } - } - }); - - } - else if (item instanceof Material) { - super.setSelectedItem(item); - } - else { - throw new IllegalArgumentException("Illegal item class " + item.getClass() + - " item=" + item); - } - } - - @Override - public Object getElementAt(int index) { - if (index == database.size()) { - return CUSTOM; - } - else if (index >= database.size() + 1) { - return null; - } - return database.get(index); - } - - @Override - public int getSize() { - return database.size() + 1; - } - - //////// Change listeners - - @Override - public void elementAdded(Material element, Database source) { - this.fireContentsChanged(this, 0, database.size()); - } - - @Override - public void elementRemoved(Material element, Database source) { - this.fireContentsChanged(this, 0, database.size()); - } - - public Material.Type getType() { - return type; - } - - public void removeListener() { - database.removeChangeListener(this); - } -} diff --git a/core/src/net/sf/openrocket/gui/preset/PresetEditorDialog.java b/core/src/net/sf/openrocket/gui/preset/PresetEditorDialog.java deleted file mode 100644 index 9d1b220c..00000000 --- a/core/src/net/sf/openrocket/gui/preset/PresetEditorDialog.java +++ /dev/null @@ -1,2217 +0,0 @@ -package net.sf.openrocket.gui.preset; - -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.imageio.ImageIO; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultComboBoxModel; -import javax.swing.ImageIcon; -import javax.swing.InputVerifier; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.border.EmptyBorder; -import javax.swing.filechooser.FileNameExtensionFilter; -import javax.swing.text.JTextComponent; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.SpinnerEditor; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.preset.loader.MaterialHolder; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * Preset editor for creating new preset components. - */ -public class PresetEditorDialog extends JDialog implements ItemListener { - - private static Translator trans = Application.getTranslator(); - - private static LogHelper log = Application.getLogger(); - - private static final String NON_NEGATIVE_INTEGER_FIELD = "(\\d){0,10}"; - - /** - * Input of non-negative decimals. - */ - final PresetInputVerifier NON_NEGATIVE_INTEGER = new PresetInputVerifier(Pattern.compile(NON_NEGATIVE_INTEGER_FIELD)); - - private final JPanel contentPanel = new JPanel(); - private DeselectableComboBox typeCombo; - private JTextField mfgTextField; - private MaterialChooser materialChooser; - private MaterialHolder holder = null; - - private JTextField ncPartNoTextField; - private JTextField ncDescTextField; - private DoubleModel ncLength; - private JCheckBox ncFilledCB; - private JComboBox ncShapeCB; - private DoubleModel ncAftDia; - private DoubleModel ncAftShoulderDia; - private DoubleModel ncAftShoulderLen; - private DoubleModel ncMass; - private ImageIcon ncImage; - private JButton ncImageBtn; - - private JTextField trPartNoTextField; - private JTextField trDescTextField; - private DoubleModel trLength; - private DoubleModel trAftDia; - private DoubleModel trAftShoulderDia; - private DoubleModel trAftShoulderLen; - private DoubleModel trForeDia; - private DoubleModel trForeShoulderDia; - private DoubleModel trForeShoulderLen; - private DoubleModel trMass; - private ImageIcon trImage; - private JCheckBox trFilledCB; - private JComboBox trShapeCB; - private JButton trImageBtn; - - private JTextField btPartNoTextField; - private JTextField btDescTextField; - private DoubleModel btMass; - private DoubleModel btInnerDia; - private DoubleModel btOuterDia; - private DoubleModel btLength; - private ImageIcon btImage; - private JButton btImageBtn; - - private JTextField tcPartNoTextField; - private JTextField tcDescTextField; - private DoubleModel tcMass; - private DoubleModel tcInnerDia; - private DoubleModel tcOuterDia; - private DoubleModel tcLength; - private ImageIcon tcImage; - private JButton tcImageBtn; - - private JTextField bhPartNoTextField; - private JTextField bhDescTextField; - private DoubleModel bhOuterDia; - private DoubleModel bhLength; - private DoubleModel bhMass; - private ImageIcon bhImage; - private JButton bhImageBtn; - - private JTextField crPartNoTextField; - private JTextField crDescTextField; - private DoubleModel crOuterDia; - private DoubleModel crInnerDia; - private DoubleModel crThickness; - private DoubleModel crMass; - private ImageIcon crImage; - private JButton crImageBtn; - - private JTextField ebPartNoTextField; - private JTextField ebDescTextField; - private DoubleModel ebOuterDia; - private DoubleModel ebInnerDia; - private DoubleModel ebThickness; - private DoubleModel ebMass; - private ImageIcon ebImage; - private JButton ebImageBtn; - - private JTextField llPartNoTextField; - private JTextField llDescTextField; - private DoubleModel llOuterDia; - private DoubleModel llInnerDia; - private DoubleModel llLength; - private DoubleModel llMass; - private ImageIcon llImage; - private JButton llImageBtn; - - private JTextField stPartNoTextField; - private JTextField stDescTextField; - private DoubleModel stThickness; - private DoubleModel stWidth; - private DoubleModel stLength; - private DoubleModel stMass; - private ImageIcon stImage; - private JButton stImageBtn; - - private JTextField pcPartNoTextField; - private JTextField pcDescTextField; - private JTextField pcSides; - private JTextField pcLineCount; - private DoubleModel pcDiameter; - private DoubleModel pcLineLength; - private MaterialChooser pcLineMaterialChooser; - private DoubleModel pcMass; - private ImageIcon pcImage; - private JButton pcImageBtn; - - private final JFileChooser imageChooser = createImageChooser(); - - private JPanel componentOverlayPanel; - - private PresetResultListener resultListener; - - private static Map componentMap = new HashMap(); - - private static final String NOSE_CONE_KEY = "NoseCone.NoseCone"; - private static final String BODY_TUBE_KEY = "BodyTube.BodyTube"; - private static final String TUBE_COUPLER_KEY = "TubeCoupler.TubeCoupler"; - private static final String TRANSITION_KEY = "Transition.Transition"; - private static final String CR_KEY = "ComponentIcons.Centeringring"; - private static final String BULKHEAD_KEY = "Bulkhead.Bulkhead"; - private static final String EB_KEY = "ComponentIcons.Engineblock"; - private static final String LAUNCH_LUG_KEY = "ComponentIcons.Launchlug"; - private static final String STREAMER_KEY = "ComponentIcons.Streamer"; - private static final String PARACHUTE_KEY = "ComponentIcons.Parachute"; - - - static { - componentMap.put(trans.get(NOSE_CONE_KEY), "NOSECONE"); - componentMap.put(trans.get(BODY_TUBE_KEY), "BODYTUBE"); - componentMap.put(trans.get(TUBE_COUPLER_KEY), "TUBECOUPLER"); - componentMap.put(trans.get(TRANSITION_KEY), "TRANSITION"); - componentMap.put(trans.get(CR_KEY), "CENTERINGRING"); - componentMap.put(trans.get(BULKHEAD_KEY), "BULKHEAD"); - componentMap.put(trans.get(EB_KEY), "ENGINEBLOCK"); - componentMap.put(trans.get(LAUNCH_LUG_KEY), "LAUNCHLUG"); - componentMap.put(trans.get(PARACHUTE_KEY), "PARACHUTE"); - componentMap.put(trans.get(STREAMER_KEY), "STREAMER"); - } - - /** - * Create the dialog. - * - * @param theCallback the listener that gets the results of editing the presets - */ - public PresetEditorDialog(PresetResultListener theCallback) { - this(theCallback, null, null); - } - - /** - * Create the dialog. - * - * @param theCallback the listener that gets the results of editing the presets - * @param toEdit the ComponentPreset to be edited; or null if a new one is being added - * @param matHolder the set of materials; if null then use system materials - */ - public PresetEditorDialog(PresetResultListener theCallback, ComponentPreset toEdit, MaterialHolder matHolder) { - resultListener = theCallback; - getContentPane().setMinimumSize(new Dimension(200, 200)); - setBounds(100, 100, 825, 610); - getContentPane().setLayout(new BorderLayout()); - contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); - getContentPane().add(contentPanel, BorderLayout.CENTER); - contentPanel.setLayout(new MigLayout("", "[][grow][94.00,grow][232.0,grow][130.00][grow]", "[][][20.00,grow][grow]")); - JLabel lblManufacturer = new JLabel("Manufacturer:"); - contentPanel.add(lblManufacturer, "cell 2 0,alignx left,aligny center"); - - mfgTextField = new JTextField(); - contentPanel.add(mfgTextField, "cell 3 0,growx"); - mfgTextField.setColumns(10); - - JLabel typeLabel = new JLabel("Type:"); - contentPanel.add(typeLabel, "cell 2 1,alignx left,aligny center"); - - componentOverlayPanel = new JPanel(); - contentPanel.add(componentOverlayPanel, "cell 1 3 5 2,grow"); - componentOverlayPanel.setLayout(new CardLayout(0, 0)); - - typeCombo = new DeselectableComboBox(); - typeCombo.addItemListener(this); - typeCombo.setModel(new DefaultComboBoxModel()); - setItems(typeCombo, toEdit); - contentPanel.add(typeCombo, "cell 3 1,growx"); - - JLabel bhMaterialLabel = new JLabel("Material:"); - contentPanel.add(bhMaterialLabel, "cell 2 2, alignx left"); - - materialChooser = new MaterialChooser(new MaterialModel(this, Material.Type.BULK)); - - contentPanel.add(materialChooser, "cell 3 2,growx"); - - { - JPanel ncPanel = new JPanel(); - componentOverlayPanel.add(ncPanel, "NOSECONE"); - ncPanel.setLayout(new MigLayout("", "[61px][159.00,grow][45.00][109.00,grow][189.00,grow][grow]", "[16px][][][][][]")); - JLabel ncPartNoLabel = new JLabel("Part No:"); - ncPanel.add(ncPartNoLabel, "cell 0 0,alignx left,aligny center"); - - ncPartNoTextField = new JTextField(); - ncPanel.add(ncPartNoTextField, "cell 1 0,growx"); - ncPartNoTextField.setColumns(10); - - JLabel ncDescLabel = new JLabel("Description:"); - ncPanel.add(ncDescLabel, "cell 3 0,alignx left,aligny center"); - - ncDescTextField = new JTextField(); - ncPanel.add(ncDescTextField, "cell 4 0,growx"); - ncDescTextField.setColumns(10); - - ncFilledCB = new JCheckBox("Filled"); - ncPanel.add(ncFilledCB, "cell 1 1"); - - JLabel ncMaterialLabel = new JLabel(trans.get("RocketCompCfg.lbl.Componentmaterial")); - ncPanel.add(ncMaterialLabel, "cell 0 1,alignx left"); - - JLabel ncMassLabel = new JLabel(trans.get("RocketCompCfg.lbl.Componentmass")); - ncPanel.add(ncMassLabel, "cell 3 1,alignx left"); - - ncMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - JSpinner spin = new JSpinner(ncMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ncPanel.add(spin, "cell 4 1, growx"); - ncPanel.add(new UnitSelector(ncMass), "growx"); - - JLabel ncShapeLabel = new JLabel(trans.get("NoseConeCfg.lbl.Noseconeshape")); - ncPanel.add(ncShapeLabel, "cell 0 2,alignx left"); - - ncShapeCB = new JComboBox(); - ncShapeCB.setModel(new DefaultComboBoxModel(new String[] { Transition.Shape.OGIVE.getName(), Transition.Shape.CONICAL.getName(), Transition.Shape.PARABOLIC.getName(), - Transition.Shape.ELLIPSOID.getName(), Transition.Shape.HAACK.getName() })); - ncPanel.add(ncShapeCB, "cell 1 2,growx"); - - JLabel ncLengthLabel = new JLabel(trans.get("NoseConeCfg.lbl.Noseconelength")); - ncPanel.add(ncLengthLabel, "cell 3 2,alignx left"); - - ncLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(ncLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ncPanel.add(spin, "cell 4 2, growx"); - ncPanel.add(new UnitSelector(ncLength), "growx"); - - JLabel ncAftDiaLabel = new JLabel("Aft Dia.:"); - ncPanel.add(ncAftDiaLabel, "cell 0 3,alignx left"); - - ncAftDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(ncAftDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ncPanel.add(spin, "cell 1 3, growx"); - ncPanel.add(new UnitSelector(ncAftDia), "growx"); - - JLabel ncAftShoulderLenLabel = new JLabel("Aft Shoulder Len:"); - ncPanel.add(ncAftShoulderLenLabel, "cell 0 4,alignx left"); - - ncAftShoulderLen = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(ncAftShoulderLen.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ncPanel.add(spin, "cell 1 4, growx"); - ncPanel.add(new UnitSelector(ncAftShoulderLen), "growx"); - - JLabel ncAftShoulderDiaLabel = new JLabel("Aft Shoulder Dia.:"); - ncPanel.add(ncAftShoulderDiaLabel, "cell 0 5,alignx left, aligny top, pad 7 0 0 0"); - - ncAftShoulderDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(ncAftShoulderDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ncPanel.add(spin, "cell 1 5, growx, aligny top"); - ncPanel.add(new UnitSelector(ncAftShoulderDia), "growx, aligny top, pad 7 0 0 0"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - ncPanel.add(panel, "cell 4 3, span 1 3"); - panel.setLayout(null); - ncImageBtn = new JButton("No Image"); - ncImageBtn.setMaximumSize(new Dimension(75, 75)); - ncImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(ncImageBtn); - ncImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - ncImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - ncImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - ncImageBtn.setIcon(ncImage); - } - } - }); - - } - { - JPanel trPanel = new JPanel(); - componentOverlayPanel.add(trPanel, "TRANSITION"); - trPanel.setLayout(new MigLayout("", "[61px][159.00,grow][45.00][109.00,grow][189.00,grow][grow]", "[16px][][][][][]")); - - JLabel trPartNoLabel = new JLabel("Part No:"); - trPanel.add(trPartNoLabel, "cell 0 0,alignx left"); - - trPartNoTextField = new JTextField(); - trPanel.add(trPartNoTextField, "cell 1 0,growx"); - trPartNoTextField.setColumns(10); - - JLabel trDescLabel = new JLabel("Description:"); - trPanel.add(trDescLabel, "cell 3 0,alignx left"); - - trDescTextField = new JTextField(); - trPanel.add(trDescTextField, "cell 4 0,growx"); - trDescTextField.setColumns(10); - - trFilledCB = new JCheckBox("Filled"); - trPanel.add(trFilledCB, "cell 1 1"); - - JLabel trMassLabel = new JLabel("Mass:"); - trPanel.add(trMassLabel, "cell 3 1,alignx left"); - - trMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - JSpinner spin = new JSpinner(trMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 4 1, growx"); - trPanel.add(new UnitSelector(trMass), "growx"); - - JLabel trShapeLabel = new JLabel("Shape:"); - trPanel.add(trShapeLabel, "cell 0 2,alignx left"); - - trShapeCB = new JComboBox(); - trShapeCB.setModel(new DefaultComboBoxModel(new String[] { Transition.Shape.OGIVE.getName(), Transition.Shape.CONICAL.getName(), Transition.Shape.PARABOLIC.getName(), - Transition.Shape.ELLIPSOID.getName(), Transition.Shape.HAACK.getName() })); - trPanel.add(trShapeCB, "cell 1 2,growx"); - - JLabel trLengthLabel = new JLabel("Length:"); - trPanel.add(trLengthLabel, "cell 3 2,alignx left"); - - trLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 4 2, growx"); - trPanel.add(new UnitSelector(trLength), "growx"); - - JLabel trAftDiaLabel = new JLabel("Aft Dia.:"); - trPanel.add(trAftDiaLabel, "cell 0 3,alignx left"); - - trAftDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trAftDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 1 3, growx"); - trPanel.add(new UnitSelector(trAftDia), "growx"); - - JLabel trForeDiaLabel = new JLabel("Fore Dia.:"); - trPanel.add(trForeDiaLabel, "cell 3 3,alignx left"); - - trForeDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trForeDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 4 3, growx"); - trPanel.add(new UnitSelector(trForeDia), "growx"); - - JLabel trAftShouldDiaLabel = new JLabel("Aft Shoulder Dia.:"); - trPanel.add(trAftShouldDiaLabel, "cell 0 4,alignx left"); - - trAftShoulderDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trAftShoulderDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 1 4, growx"); - trPanel.add(new UnitSelector(trAftShoulderDia), "growx"); - - JLabel trForeShouldDiaLabel = new JLabel("Fore Shoulder Dia.:"); - trPanel.add(trForeShouldDiaLabel, "cell 3 4,alignx left"); - - trForeShoulderDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trForeShoulderDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 4 4, growx"); - trPanel.add(new UnitSelector(trForeShoulderDia), "growx"); - - JLabel trAftShoulderLenLabel = new JLabel("Aft Shoulder Len.:"); - trPanel.add(trAftShoulderLenLabel, "cell 0 5,alignx left"); - - trAftShoulderLen = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trAftShoulderLen.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 1 5, growx"); - trPanel.add(new UnitSelector(trAftShoulderLen), "growx"); - - JLabel lblForeShoulderLen = new JLabel("Fore Shoulder Len.:"); - trPanel.add(lblForeShoulderLen, "cell 3 5,alignx left"); - - trForeShoulderLen = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0, 2); - spin = new JSpinner(trForeShoulderLen.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - trPanel.add(spin, "cell 4 5, growx"); - trPanel.add(new UnitSelector(trForeShoulderLen), "growx"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - trPanel.add(panel, "cell 4 6"); - panel.setLayout(null); - trImageBtn = new JButton("No Image"); - trImageBtn.setMaximumSize(new Dimension(75, 75)); - trImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(trImageBtn); - trImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - trImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - trImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - trImageBtn.setIcon(trImage); - } - } - }); - - } - { - JPanel btPanel = new JPanel(); - componentOverlayPanel.add(btPanel, "BODYTUBE"); - btPanel.setLayout(new MigLayout("", "[][grow][][grow]", "[][][][]")); - JLabel btPartNoLabel = new JLabel("Part No:"); - btPanel.add(btPartNoLabel, "cell 0 0,alignx left"); - - btPartNoTextField = new JTextField(); - btPanel.add(btPartNoTextField, "cell 1 0,growx"); - btPartNoTextField.setColumns(10); - - JLabel btDescLabel = new JLabel("Description:"); - btPanel.add(btDescLabel, "cell 3 0,alignx left"); - - btDescTextField = new JTextField(); - btPanel.add(btDescTextField, "cell 4 0,growx"); - btDescTextField.setColumns(10); - - JLabel btLengthLabel = new JLabel("Length:"); - btPanel.add(btLengthLabel, "cell 0 1,alignx left"); - - btLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(btLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - btPanel.add(spin, "cell 1 1, growx"); - btPanel.add(new UnitSelector(btLength), "growx"); - - JLabel btMassLabel = new JLabel("Mass:"); - btPanel.add(btMassLabel, "cell 3 1,alignx left"); - - btMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(btMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - btPanel.add(spin, "cell 4 1, growx"); - btPanel.add(new UnitSelector(btMass), "w 34lp!"); - - JLabel btInnerDiaLabel = new JLabel("Inner Dia.:"); - btPanel.add(btInnerDiaLabel, "cell 0 2,alignx left"); - - btInnerDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(btInnerDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - btPanel.add(spin, "cell 1 2, growx"); - btPanel.add(new UnitSelector(btInnerDia), "growx"); - - JLabel btOuterDiaLabel = new JLabel("Outer Dia.:"); - btPanel.add(btOuterDiaLabel, "cell 3 2,alignx left"); - - btOuterDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(btOuterDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - btPanel.add(spin, "cell 4 2, growx"); - btPanel.add(new UnitSelector(btOuterDia), "w 34lp!"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - btPanel.add(panel, "cell 4 3"); - panel.setLayout(null); - btImageBtn = new JButton("No Image"); - btImageBtn.setMaximumSize(new Dimension(75, 75)); - btImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(btImageBtn); - btImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - btImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - btImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - btImageBtn.setIcon(btImage); - } - } - }); - - } - { - JPanel tcPanel = new JPanel(); - componentOverlayPanel.add(tcPanel, "TUBECOUPLER"); - tcPanel.setLayout(new MigLayout("", "[][grow][][grow]", "[][][][]")); - JLabel tcPartNoLabel = new JLabel("Part No:"); - tcPanel.add(tcPartNoLabel, "cell 0 0,alignx left"); - - tcPartNoTextField = new JTextField(); - tcPanel.add(tcPartNoTextField, "cell 1 0,growx"); - tcPartNoTextField.setColumns(10); - - JLabel tcDescLabel = new JLabel("Description:"); - tcPanel.add(tcDescLabel, "cell 3 0,alignx left"); - - tcDescTextField = new JTextField(); - tcPanel.add(tcDescTextField, "cell 4 0,growx"); - tcDescTextField.setColumns(10); - - JLabel tcLengthLabel = new JLabel("Length:"); - tcPanel.add(tcLengthLabel, "cell 0 1,alignx left"); - - tcLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(tcLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - tcPanel.add(spin, "cell 1 1, growx"); - tcPanel.add(new UnitSelector(tcLength), "growx"); - - JLabel tcMassLabel = new JLabel("Mass:"); - tcPanel.add(tcMassLabel, "cell 3 1,alignx left"); - - tcMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(tcMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - tcPanel.add(spin, "cell 4 1, growx"); - tcPanel.add(new UnitSelector(tcMass), "w 34lp!"); - - JLabel tcInnerDiaLabel = new JLabel("Inner Dia.:"); - tcPanel.add(tcInnerDiaLabel, "cell 0 2,alignx left"); - - tcInnerDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(tcInnerDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - tcPanel.add(spin, "cell 1 2, growx"); - tcPanel.add(new UnitSelector(tcInnerDia), "growx"); - - JLabel tcOuterDiaLabel = new JLabel("Outer Dia.:"); - tcPanel.add(tcOuterDiaLabel, "cell 3 2,alignx left"); - - tcOuterDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(tcOuterDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - tcPanel.add(spin, "cell 4 2, growx"); - tcPanel.add(new UnitSelector(tcOuterDia), "w 34lp!"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - tcPanel.add(panel, "cell 4 3"); - panel.setLayout(null); - tcImageBtn = new JButton("No Image"); - tcImageBtn.setMaximumSize(new Dimension(75, 75)); - tcImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(tcImageBtn); - tcImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - tcImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - tcImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - tcImageBtn.setIcon(tcImage); - } - } - }); - - - } - { - JPanel bhPanel = new JPanel(); - componentOverlayPanel.add(bhPanel, "BULKHEAD"); - bhPanel.setLayout(new MigLayout("", "[][157.00,grow 79][65.00][grow]", "[][][][]")); - - JLabel bhPartNoLabel = new JLabel("Part No:"); - bhPanel.add(bhPartNoLabel, "cell 0 0,alignx left"); - - bhPartNoTextField = new JTextField(); - bhPanel.add(bhPartNoTextField, "cell 1 0,growx"); - bhPartNoTextField.setColumns(10); - - JLabel bhDescLabel = new JLabel("Description:"); - bhPanel.add(bhDescLabel, "cell 3 0,alignx left"); - - bhDescTextField = new JTextField(); - bhPanel.add(bhDescTextField, "cell 4 0,growx"); - bhDescTextField.setColumns(10); - - JLabel bhLengthLabel = new JLabel("Thickness:"); - bhPanel.add(bhLengthLabel, "cell 0 1,alignx left"); - - bhLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(bhLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - bhPanel.add(spin, "cell 1 1, growx"); - bhPanel.add(new UnitSelector(bhLength), "w 34lp!"); - - JLabel bhMassLabel = new JLabel("Mass:"); - bhPanel.add(bhMassLabel, "cell 3 1,alignx left"); - - bhMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(bhMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - bhPanel.add(spin, "cell 4 1, growx"); - bhPanel.add(new UnitSelector(bhMass), "growx"); - - JLabel bhOuterDiaLabel = new JLabel("Outer Dia.:"); - bhPanel.add(bhOuterDiaLabel, "cell 0 2,alignx left, aligny top, pad 7 0 0 0"); - - bhOuterDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(bhOuterDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - bhPanel.add(spin, "cell 1 2, growx, aligny top"); - bhPanel.add(new UnitSelector(bhOuterDia), "w 34lp!, h 27lp!, aligny top, pad 7 0 0 0"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - bhPanel.add(panel, "cell 4 2"); - panel.setLayout(null); - bhImageBtn = new JButton("No Image"); - bhImageBtn.setMaximumSize(new Dimension(75, 75)); - bhImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(bhImageBtn); - bhImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - bhImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - bhImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - bhImageBtn.setIcon(bhImage); - } - } - }); - - } - { - JPanel crPanel = new JPanel(); - componentOverlayPanel.add(crPanel, "CENTERINGRING"); - crPanel.setLayout(new MigLayout("", "[][grow][][grow]", "[][][][]")); - - JLabel crPartNoLabel = new JLabel("Part No:"); - crPanel.add(crPartNoLabel, "cell 0 0,alignx left"); - - crPartNoTextField = new JTextField(); - crPanel.add(crPartNoTextField, "cell 1 0, growx"); - crPartNoTextField.setColumns(10); - - JLabel crDescLabel = new JLabel("Description:"); - crPanel.add(crDescLabel, "cell 3 0,alignx left"); - - crDescTextField = new JTextField(); - crPanel.add(crDescTextField, "cell 4 0, growx"); - crDescTextField.setColumns(10); - - JLabel crThicknessLabel = new JLabel("Thickness:"); - crPanel.add(crThicknessLabel, "cell 0 1,alignx left"); - - crThickness = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(crThickness.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - crPanel.add(spin, "cell 1 1, growx"); - crPanel.add(new UnitSelector(crThickness), "growx"); - - JLabel crMassLabel = new JLabel("Mass:"); - crPanel.add(crMassLabel, "cell 3 1,alignx left"); - - crMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(crMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - crPanel.add(spin, "cell 4 1, growx"); - crPanel.add(new UnitSelector(crMass), "w 34lp!"); - - JLabel crOuterDiaLabel = new JLabel("Outer Dia.:"); - crPanel.add(crOuterDiaLabel, "cell 0 2,alignx left"); - - crOuterDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(crOuterDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - crPanel.add(spin, "cell 1 2, growx"); - crPanel.add(new UnitSelector(crOuterDia), "w 34lp!"); - - JLabel crInnerDiaLabel = new JLabel("Inner Dia.:"); - crPanel.add(crInnerDiaLabel, "cell 3 2,alignx left"); - - crInnerDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(crInnerDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - crPanel.add(spin, "cell 4 2, growx"); - crPanel.add(new UnitSelector(crInnerDia), "w 34lp!"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - crPanel.add(panel, "cell 4 3"); - panel.setLayout(null); - crImageBtn = new JButton("No Image"); - crImageBtn.setMaximumSize(new Dimension(75, 75)); - crImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(crImageBtn); - crImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - crImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - crImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - crImageBtn.setIcon(crImage); - } - } - }); - - } - { - JPanel ebPanel = new JPanel(); - componentOverlayPanel.add(ebPanel, "ENGINEBLOCK"); - ebPanel.setLayout(new MigLayout("", "[][grow][][grow]", "[][][][]")); - JLabel ebPartNoLabel = new JLabel("Part No:"); - ebPanel.add(ebPartNoLabel, "cell 0 0,alignx left"); - - ebPartNoTextField = new JTextField(); - ebPanel.add(ebPartNoTextField, "cell 1 0,growx"); - ebPartNoTextField.setColumns(10); - - JLabel ebDescLabel = new JLabel("Description:"); - ebPanel.add(ebDescLabel, "cell 3 0,alignx left"); - - ebDescTextField = new JTextField(); - ebPanel.add(ebDescTextField, "cell 4 0,growx"); - ebDescTextField.setColumns(10); - - JLabel ebThicknessLabel = new JLabel("Thickness:"); - ebPanel.add(ebThicknessLabel, "cell 0 1,alignx left"); - - ebThickness = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(ebThickness.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ebPanel.add(spin, "cell 1 1, growx"); - ebPanel.add(new UnitSelector(ebThickness), "growx"); - - JLabel ebMassLabel = new JLabel("Mass:"); - ebPanel.add(ebMassLabel, "cell 3 1,alignx left"); - - ebMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(ebMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ebPanel.add(spin, "cell 4 1, growx"); - ebPanel.add(new UnitSelector(ebMass), "w 34lp!"); - - JLabel ebOuterDiaLabel = new JLabel("Outer Dia.:"); - ebPanel.add(ebOuterDiaLabel, "cell 0 2,alignx left"); - - ebOuterDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(ebOuterDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ebPanel.add(spin, "cell 1 2, growx"); - ebPanel.add(new UnitSelector(ebOuterDia), "growx"); - - JLabel ebInnerDiaLabel = new JLabel("Inner Dia.:"); - ebPanel.add(ebInnerDiaLabel, "cell 3 2,alignx left"); - - ebInnerDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(ebInnerDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - ebPanel.add(spin, "cell 4 2, growx"); - ebPanel.add(new UnitSelector(ebInnerDia), "w 34lp!"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - ebPanel.add(panel, "cell 4 3"); - panel.setLayout(null); - ebImageBtn = new JButton("No Image"); - ebImageBtn.setMaximumSize(new Dimension(75, 75)); - ebImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(ebImageBtn); - ebImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - ebImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - ebImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - ebImageBtn.setIcon(ebImage); - } - } - }); - } - - { - JPanel llPanel = new JPanel(); - componentOverlayPanel.add(llPanel, "LAUNCHLUG"); - llPanel.setLayout(new MigLayout("", "[][grow][][grow]", "[][][][]")); - JLabel llPartNoLabel = new JLabel("Part No:"); - llPanel.add(llPartNoLabel, "cell 0 0,alignx left"); - - llPartNoTextField = new JTextField(); - llPanel.add(llPartNoTextField, "cell 1 0,growx"); - llPartNoTextField.setColumns(10); - - JLabel llDescLabel = new JLabel("Description:"); - llPanel.add(llDescLabel, "cell 3 0,alignx left"); - - llDescTextField = new JTextField(); - llPanel.add(llDescTextField, "cell 4 0,growx"); - llDescTextField.setColumns(10); - - JLabel llLengthLabel = new JLabel("Length:"); - llPanel.add(llLengthLabel, "cell 0 1,alignx left"); - - llLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(llLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - llPanel.add(spin, "cell 1 1, growx"); - llPanel.add(new UnitSelector(llLength), "growx"); - - JLabel llMassLabel = new JLabel("Mass:"); - llPanel.add(llMassLabel, "cell 3 1,alignx left"); - - llMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(llMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - llPanel.add(spin, "cell 4 1, growx"); - llPanel.add(new UnitSelector(llMass), "w 34lp!"); - - JLabel llOuterDiaLabel = new JLabel("Outer Dia.:"); - llPanel.add(llOuterDiaLabel, "cell 0 2,alignx left"); - - llOuterDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(llOuterDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - llPanel.add(spin, "cell 1 2, growx"); - llPanel.add(new UnitSelector(llOuterDia), "growx"); - - JLabel llInnerDiaLabel = new JLabel("Inner Dia.:"); - llPanel.add(llInnerDiaLabel, "cell 3 2,alignx left"); - - llInnerDia = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(llInnerDia.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - llPanel.add(spin, "cell 4 2, growx"); - llPanel.add(new UnitSelector(llInnerDia), "w 34lp!"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - llPanel.add(panel, "cell 4 3"); - panel.setLayout(null); - llImageBtn = new JButton("No Image"); - llImageBtn.setMaximumSize(new Dimension(75, 75)); - llImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(llImageBtn); - llImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - llImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - llImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - llImageBtn.setIcon(llImage); - } - } - }); - } - - { - JPanel stPanel = new JPanel(); - componentOverlayPanel.add(stPanel, "STREAMER"); - stPanel.setLayout(new MigLayout("", "[][grow][][grow]", "[][][][]")); - JLabel stPartNoLabel = new JLabel("Part No:"); - stPanel.add(stPartNoLabel, "cell 0 0,alignx left"); - - stPartNoTextField = new JTextField(); - stPanel.add(stPartNoTextField, "cell 1 0,growx"); - stPartNoTextField.setColumns(10); - - JLabel stDescLabel = new JLabel("Description:"); - stPanel.add(stDescLabel, "cell 3 0,alignx left"); - - stDescTextField = new JTextField(); - stPanel.add(stDescTextField, "cell 4 0,growx"); - stDescTextField.setColumns(10); - - JLabel stLengthLabel = new JLabel("Length:"); - stPanel.add(stLengthLabel, "cell 0 1,alignx left"); - - stLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - JSpinner spin = new JSpinner(stLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - stPanel.add(spin, "cell 1 1, growx"); - stPanel.add(new UnitSelector(stLength), "growx"); - - JLabel stMassLabel = new JLabel("Mass:"); - stPanel.add(stMassLabel, "cell 3 1,alignx left"); - - stMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - spin = new JSpinner(stMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - stPanel.add(spin, "cell 4 1, growx"); - stPanel.add(new UnitSelector(stMass), "growx"); - - JLabel stThicknessLabel = new JLabel("Thickness:"); - stPanel.add(stThicknessLabel, "cell 0 2,alignx left"); - - stThickness = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(stThickness.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - stPanel.add(spin, "cell 1 2, growx"); - stPanel.add(new UnitSelector(stThickness), "growx"); - - JLabel stWidthLabel = new JLabel("Width:"); - stPanel.add(stWidthLabel, "cell 3 2,alignx left"); - - stWidth = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(stWidth.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - stPanel.add(spin, "cell 4 2, growx"); - stPanel.add(new UnitSelector(stWidth), "growx"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - stPanel.add(panel, "cell 4 3"); - panel.setLayout(null); - stImageBtn = new JButton("No Image"); - stImageBtn.setMaximumSize(new Dimension(75, 75)); - stImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(stImageBtn); - stImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - stImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - stImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - stImageBtn.setIcon(stImage); - } - } - }); - } - - { - JPanel pcPanel = new JPanel(); - componentOverlayPanel.add(pcPanel, "PARACHUTE"); - pcPanel.setLayout(new MigLayout("", "[][157.00,grow 79][65.00][grow][][]", "[][][][][][]")); - JLabel pcPartNoLabel = new JLabel("Part No:"); - pcPanel.add(pcPartNoLabel, "cell 0 0,alignx left"); - - pcPartNoTextField = new JTextField(); - pcPanel.add(pcPartNoTextField, "cell 1 0,growx"); - pcPartNoTextField.setColumns(10); - - JLabel pcDescLabel = new JLabel("Description:"); - pcPanel.add(pcDescLabel, "cell 3 0,alignx left"); - - pcDescTextField = new JTextField(); - pcPanel.add(pcDescTextField, "cell 4 0,growx"); - pcDescTextField.setColumns(10); - - JLabel pcSidesLabel = new JLabel("Sides:"); - pcPanel.add(pcSidesLabel, "cell 0 1,alignx left"); - - pcSides = new JTextField(); - pcPanel.add(pcSides, "cell 1 1, growx"); - pcSides.setInputVerifier(NON_NEGATIVE_INTEGER); - pcSides.setColumns(10); - - JLabel pcMassLabel = new JLabel("Mass:"); - pcPanel.add(pcMassLabel, "cell 3 1,alignx left"); - - pcMass = new DoubleModel(0, UnitGroup.UNITS_MASS, 0); - JSpinner spin = new JSpinner(pcMass.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - pcPanel.add(spin, "cell 4 1, growx"); - pcPanel.add(new UnitSelector(pcMass), "growx"); - - JLabel pcDiameterLabel = new JLabel("Diameter:"); - pcPanel.add(pcDiameterLabel, "cell 0 2,alignx left"); - - pcDiameter = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(pcDiameter.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - pcPanel.add(spin, "cell 1 2, growx"); - pcPanel.add(new UnitSelector(pcDiameter)); - - JLabel pcLineLengthLabel = new JLabel("Line Length:"); - pcPanel.add(pcLineLengthLabel, "cell 3 2,alignx left"); - - pcLineLength = new DoubleModel(0, UnitGroup.UNITS_LENGTH, 0); - spin = new JSpinner(pcLineLength.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); - pcPanel.add(spin, "cell 4 2, growx"); - pcPanel.add(new UnitSelector(pcLineLength), "growx"); - - JLabel pcLineCountLabel = new JLabel("Line Count:"); - pcPanel.add(pcLineCountLabel, "cell 3 3,alignx left"); - - pcLineCount = new JTextField(); - pcLineCount.setInputVerifier(NON_NEGATIVE_INTEGER); - pcPanel.add(pcLineCount, "cell 4 3, growx"); - pcLineCount.setColumns(10); - - JLabel pcLineMaterialLabel = new JLabel("Line Material:"); - pcPanel.add(pcLineMaterialLabel, "cell 3 4,alignx left, aligny top, pad 7 0 0 0 "); - - pcLineMaterialChooser = new MaterialChooser(); - pcLineMaterialChooser.setModel(new MaterialModel(PresetEditorDialog.this, Material.Type.LINE)); - pcPanel.add(pcLineMaterialChooser, "cell 4 4, span 3 1, growx, aligny top"); - - JPanel panel = new JPanel(); - panel.setMinimumSize(new Dimension(200, 200)); - pcPanel.add(panel, "cell 1 3, span 1 3"); - panel.setLayout(null); - pcImageBtn = new JButton("No Image"); - pcImageBtn.setMaximumSize(new Dimension(75, 75)); - pcImageBtn.setMinimumSize(new Dimension(75, 75)); - panel.add(pcImageBtn); - pcImageBtn.setBounds(new Rectangle(6, 6, 132, 145)); - - pcImageBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(final ActionEvent e) { - int returnVal = imageChooser.showOpenDialog(PresetEditorDialog.this); - - if (returnVal == JFileChooser.APPROVE_OPTION) { - File file = imageChooser.getSelectedFile(); - pcImage = scaleImage(new ImageIcon(file.getAbsolutePath()).getImage(), 155); - pcImageBtn.setIcon(pcImage); - } - } - }); - } - - JPanel buttonPane = new JPanel(); - getContentPane().add(buttonPane, BorderLayout.SOUTH); - buttonPane.setLayout(new MigLayout("", "[130px][176.00px][131.00px]", "[29px]")); - JButton btnSaveAndNew = new JButton("Save and New"); - btnSaveAndNew.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent arg0) { - saveResult(); - } - }); - buttonPane.add(btnSaveAndNew, "cell 0 0,alignx left,aligny top"); - - JButton okButton = new JButton("Save and Close"); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent event) { - if (saveResult()) { - dispose(); - } - } - }); - okButton.setActionCommand("OK"); - buttonPane.add(okButton, "cell 1 0,alignx left,aligny top"); - getRootPane().setDefaultButton(okButton); - - JButton cancelButton = new JButton("Close"); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent event) { - dispose(); - } - }); - cancelButton.setActionCommand("Close"); - buttonPane.add(cancelButton, "cell 6 0,alignx right,aligny top"); - - if (toEdit != null) { - fillEditor(toEdit, matHolder); - } - holder = matHolder; - } - - /** - * When an existing preset is edited, we want to disable the other types of presets. If the user wants a different - * type of component, then they should delete this one and add a new one. - * - * @param cb the combo box component - * @param preset the preset being edited - */ - private void setItems(DeselectableComboBox cb, ComponentPreset preset) { - cb.addItem(trans.get(NOSE_CONE_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.NOSE_CONE)); - cb.addItem(trans.get(BODY_TUBE_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.BODY_TUBE)); - cb.addItem(trans.get(BULKHEAD_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.BULK_HEAD)); - cb.addItem(trans.get(CR_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.CENTERING_RING)); - cb.addItem(trans.get(EB_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.ENGINE_BLOCK)); - cb.addItem(trans.get(TRANSITION_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.TRANSITION)); - cb.addItem(trans.get(TUBE_COUPLER_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.TUBE_COUPLER)); - cb.addItem(trans.get(LAUNCH_LUG_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.LAUNCH_LUG)); - cb.addItem(trans.get(PARACHUTE_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.PARACHUTE)); - cb.addItem(trans.get(STREAMER_KEY), preset != null && !preset.get(ComponentPreset.TYPE).equals(ComponentPreset.Type.STREAMER)); - } - - /** - * Create an image chooser. Currently png and jpg are supported. - * - * @return a file chooser that looks for image files - */ - private JFileChooser createImageChooser() { - final JFileChooser chooser = new JFileChooser(); - ImagePreviewPanel preview = new ImagePreviewPanel(); - chooser.setAccessory(preview); - chooser.addPropertyChangeListener(preview); - chooser.setAcceptAllFileFilterUsed(false); - chooser.addChoosableFileFilter(new FileNameExtensionFilter("Image Files", "png", "jpg", "jpeg")); - return chooser; - } - - /** - * To support editing of an existing preset, the swing components need to be prepopulated with the field data. - * - * @param preset the preset to edit - */ - private void fillEditor(ComponentPreset preset, MaterialHolder holder) { - ComponentPreset.Type t = preset.getType(); - - mfgTextField.setText(preset.get(ComponentPreset.MANUFACTURER).getDisplayName()); - setMaterial(materialChooser, preset, holder, Material.Type.BULK, ComponentPreset.MATERIAL); - switch (t) { - case BODY_TUBE: - typeCombo.setSelectedItem(trans.get(BODY_TUBE_KEY)); - btDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - - if (preset.has(ComponentPreset.INNER_DIAMETER)) { - btInnerDia.setValue(preset.get(ComponentPreset.INNER_DIAMETER)); - btInnerDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.LENGTH)) { - btLength.setValue(preset.get(ComponentPreset.LENGTH)); - btLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - btMass.setValue(preset.get(ComponentPreset.MASS)); - btMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.OUTER_DIAMETER)) { - btOuterDia.setValue(preset.get(ComponentPreset.OUTER_DIAMETER)); - btOuterDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - btImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - btImageBtn.setIcon(btImage); - } - btPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - case BULK_HEAD: - typeCombo.setSelectedItem(trans.get(BULKHEAD_KEY)); - bhDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.LENGTH)) { - bhLength.setValue(preset.get(ComponentPreset.LENGTH)); - bhLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - bhMass.setValue(preset.get(ComponentPreset.MASS)); - bhMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.OUTER_DIAMETER)) { - bhOuterDia.setValue(preset.get(ComponentPreset.OUTER_DIAMETER)); - bhOuterDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - bhImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - bhImageBtn.setIcon(bhImage); - } - bhPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - case CENTERING_RING: - typeCombo.setSelectedItem(trans.get(CR_KEY)); - crDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.INNER_DIAMETER)) { - crInnerDia.setValue(preset.get(ComponentPreset.INNER_DIAMETER)); - crInnerDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.LENGTH)) { - crThickness.setValue(preset.get(ComponentPreset.LENGTH)); - crThickness.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - crMass.setValue(preset.get(ComponentPreset.MASS)); - crMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.OUTER_DIAMETER)) { - crOuterDia.setValue(preset.get(ComponentPreset.OUTER_DIAMETER)); - crOuterDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - crImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - crImageBtn.setIcon(crImage); - } - crPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - case ENGINE_BLOCK: - typeCombo.setSelectedItem(trans.get(EB_KEY)); - ebDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.INNER_DIAMETER)) { - ebInnerDia.setValue(preset.get(ComponentPreset.INNER_DIAMETER)); - ebInnerDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.LENGTH)) { - ebThickness.setValue(preset.get(ComponentPreset.LENGTH)); - ebThickness.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - ebMass.setValue(preset.get(ComponentPreset.MASS)); - ebMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.OUTER_DIAMETER)) { - ebOuterDia.setValue(preset.get(ComponentPreset.OUTER_DIAMETER)); - ebOuterDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - ebImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - ebImageBtn.setIcon(ebImage); - } - ebPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - case NOSE_CONE: - typeCombo.setSelectedItem(trans.get(NOSE_CONE_KEY)); - ncDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.AFT_OUTER_DIAMETER)) { - ncAftDia.setValue(preset.get(ComponentPreset.AFT_OUTER_DIAMETER)); - ncAftDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.AFT_SHOULDER_DIAMETER)) { - ncAftShoulderDia.setValue(preset.get(ComponentPreset.AFT_SHOULDER_DIAMETER)); - ncAftShoulderDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.AFT_SHOULDER_LENGTH)) { - ncAftShoulderLen.setValue(preset.get(ComponentPreset.AFT_SHOULDER_LENGTH)); - ncAftShoulderLen.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - ncMass.setValue(preset.get(ComponentPreset.MASS)); - ncMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.SHAPE)) { - ncShapeCB.setSelectedItem(preset.get(ComponentPreset.SHAPE).toString()); - } - if (preset.has(ComponentPreset.FILLED)) { - ncFilledCB.setSelected((preset.get(ComponentPreset.FILLED))); - } - if (preset.has(ComponentPreset.LENGTH)) { - ncLength.setValue(preset.get(ComponentPreset.LENGTH)); - ncLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - ncImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - ncImageBtn.setIcon(ncImage); - } - ncPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - case TRANSITION: - typeCombo.setSelectedItem(trans.get(TRANSITION_KEY)); - trDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.AFT_OUTER_DIAMETER)) { - trAftDia.setValue(preset.get(ComponentPreset.AFT_OUTER_DIAMETER)); - trAftDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.AFT_SHOULDER_DIAMETER)) { - trAftShoulderDia.setValue(preset.get(ComponentPreset.AFT_SHOULDER_DIAMETER)); - trAftShoulderDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.AFT_SHOULDER_LENGTH)) { - trAftShoulderLen.setValue(preset.get(ComponentPreset.AFT_SHOULDER_LENGTH)); - trAftShoulderLen.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.FORE_OUTER_DIAMETER)) { - trForeDia.setValue(preset.get(ComponentPreset.FORE_OUTER_DIAMETER)); - trForeDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.FORE_SHOULDER_DIAMETER)) { - trForeShoulderDia.setValue(preset.get(ComponentPreset.FORE_SHOULDER_DIAMETER)); - trForeShoulderDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.FORE_SHOULDER_LENGTH)) { - trForeShoulderLen.setValue(preset.get(ComponentPreset.FORE_SHOULDER_LENGTH)); - trForeShoulderLen.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - trMass.setValue(preset.get(ComponentPreset.MASS)); - trMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.SHAPE)) { - trShapeCB.setSelectedItem(preset.get(ComponentPreset.SHAPE).toString()); - } - if (preset.has(ComponentPreset.FILLED)) { - trFilledCB.setSelected((preset.get(ComponentPreset.FILLED))); - } - if (preset.has(ComponentPreset.LENGTH)) { - trLength.setValue(preset.get(ComponentPreset.LENGTH)); - trLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - trImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - trImageBtn.setIcon(trImage); - } - trPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - case TUBE_COUPLER: - typeCombo.setSelectedItem(trans.get(TUBE_COUPLER_KEY)); - tcDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.INNER_DIAMETER)) { - tcInnerDia.setValue(preset.get(ComponentPreset.INNER_DIAMETER)); - tcInnerDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.LENGTH)) { - tcLength.setValue(preset.get(ComponentPreset.LENGTH)); - tcLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - tcMass.setValue(preset.get(ComponentPreset.MASS)); - tcMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.OUTER_DIAMETER)) { - tcOuterDia.setValue(preset.get(ComponentPreset.OUTER_DIAMETER)); - tcOuterDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - tcPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - if (preset.has(ComponentPreset.IMAGE)) { - tcImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - tcImageBtn.setIcon(tcImage); - } - break; - case LAUNCH_LUG: - typeCombo.setSelectedItem(trans.get(LAUNCH_LUG_KEY)); - llDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.INNER_DIAMETER)) { - llInnerDia.setValue(preset.get(ComponentPreset.INNER_DIAMETER)); - llInnerDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.LENGTH)) { - llLength.setValue(preset.get(ComponentPreset.LENGTH)); - llLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - llMass.setValue(preset.get(ComponentPreset.MASS)); - llMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.OUTER_DIAMETER)) { - llOuterDia.setValue(preset.get(ComponentPreset.OUTER_DIAMETER)); - llOuterDia.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - llPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - if (preset.has(ComponentPreset.IMAGE)) { - llImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - llImageBtn.setIcon(llImage); - } - break; - case PARACHUTE: - setMaterial(materialChooser, preset, holder, Material.Type.SURFACE, ComponentPreset.MATERIAL); - typeCombo.setSelectedItem(trans.get(PARACHUTE_KEY)); - pcDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.LINE_COUNT)) { - pcLineCount.setText(preset.get(ComponentPreset.LINE_COUNT).toString()); - } - if (preset.has(ComponentPreset.SIDES)) { - pcSides.setText(preset.get(ComponentPreset.SIDES).toString()); - } - if (preset.has(ComponentPreset.MASS)) { - pcMass.setValue(preset.get(ComponentPreset.MASS)); - pcMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.DIAMETER)) { - pcDiameter.setValue(preset.get(ComponentPreset.DIAMETER)); - pcDiameter.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.LINE_LENGTH)) { - pcLineLength.setValue(preset.get(ComponentPreset.LINE_LENGTH)); - pcLineLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - pcPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - if (preset.has(ComponentPreset.IMAGE)) { - pcImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - pcImageBtn.setIcon(pcImage); - } - setMaterial(pcLineMaterialChooser, preset, holder, Material.Type.LINE, ComponentPreset.LINE_MATERIAL); - // pcLineMaterialChooser.setModel(new MaterialModel(PresetEditorDialog.this, Material.Type.LINE)); - - // pcLineMaterialChooser.getModel().setSelectedItem(preset.get(ComponentPreset.LINE_MATERIAL)); - break; - case STREAMER: - setMaterial(materialChooser, preset, holder, Material.Type.SURFACE, ComponentPreset.MATERIAL); - typeCombo.setSelectedItem(trans.get(STREAMER_KEY)); - stDescTextField.setText(preset.get(ComponentPreset.DESCRIPTION)); - if (preset.has(ComponentPreset.LENGTH)) { - stLength.setValue(preset.get(ComponentPreset.LENGTH)); - stLength.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.THICKNESS)) { - stThickness.setValue(preset.get(ComponentPreset.LENGTH)); - stThickness.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.MASS)) { - stMass.setValue(preset.get(ComponentPreset.MASS)); - stMass.setCurrentUnit(UnitGroup.UNITS_MASS.getDefaultUnit()); - } - if (preset.has(ComponentPreset.WIDTH)) { - stWidth.setValue(preset.get(ComponentPreset.WIDTH)); - stWidth.setCurrentUnit(UnitGroup.UNITS_LENGTH.getDefaultUnit()); - } - if (preset.has(ComponentPreset.IMAGE)) { - stImage = new ImageIcon(byteArrayToImage(preset.get(ComponentPreset.IMAGE))); - stImageBtn.setIcon(stImage); - } - stPartNoTextField.setText(preset.get(ComponentPreset.PARTNO)); - break; - default: - } - } - - private void setMaterial(final JComboBox chooser, final ComponentPreset preset, final MaterialHolder holder, - final Material.Type theType, final TypedKey key) { - if (holder == null) { - chooser.setModel(new MaterialModel(PresetEditorDialog.this, theType)); - } - else { - chooser.setModel(new MaterialModel(PresetEditorDialog.this, theType, - holder.asDatabase(theType))); - } - if (preset != null) { - chooser.getModel().setSelectedItem(preset.get(key)); - } - } - - /** - * Extract the preset data from the UI fields, create a ComponentPreset instance, and notify the listener. - */ - private boolean saveResult() { - String type = (String) typeCombo.getSelectedItem(); - - ComponentPreset result = null; - - if (type.equals(trans.get(NOSE_CONE_KEY))) { - result = extractNoseCone(); - if (result != null) { - clearNoseCone(); - } - } - else if (type.equals(trans.get(TRANSITION_KEY))) { - result = extractTransition(); - if (result != null) { - clearTransition(); - } - } - else if (type.equals(trans.get(BODY_TUBE_KEY))) { - result = extractBodyTube(); - if (result != null) { - clearBodyTube(); - } - } - else if (type.equals(trans.get(TUBE_COUPLER_KEY))) { - result = extractTubeCoupler(); - if (result != null) { - clearTubeCoupler(); - } - } - else if (type.equals(trans.get(EB_KEY))) { - result = extractEngineBlock(); - if (result != null) { - clearEngineBlock(); - } - } - else if (type.equals(trans.get(CR_KEY))) { - result = extractCenteringRing(); - if (result != null) { - clearCenteringRing(); - } - } - else if (type.equals(trans.get(BULKHEAD_KEY))) { - result = extractBulkhead(); - if (result != null) { - clearBulkhead(); - } - } - else if (type.equals(trans.get(LAUNCH_LUG_KEY))) { - result = extractLaunchLug(); - if (result != null) { - clearLaunchLug(); - } - } - else if (type.equals(trans.get(PARACHUTE_KEY))) { - result = extractParachute(); - if (result != null) { - clearParachute(); - } - } - else if (type.equals(trans.get(STREAMER_KEY))) { - result = extractStreamer(); - if (result != null) { - clearStreamer(); - } - } - if (result != null) { - resultListener.notifyResult(result); - return true; - } - else { - return false; - } - } - - private ComponentPreset extractNoseCone() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - props.put(ComponentPreset.AFT_OUTER_DIAMETER, ncAftDia.getValue()); - props.put(ComponentPreset.AFT_SHOULDER_DIAMETER, ncAftShoulderDia.getValue()); - props.put(ComponentPreset.AFT_SHOULDER_LENGTH, ncAftShoulderLen.getValue()); - props.put(ComponentPreset.DESCRIPTION, ncDescTextField.getText()); - props.put(ComponentPreset.PARTNO, ncPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, ncLength.getValue()); - props.put(ComponentPreset.SHAPE, Transition.Shape.toShape((String) ncShapeCB.getSelectedItem())); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, ncMass.getValue()); - props.put(ComponentPreset.FILLED, ncFilledCB.isSelected()); - if (ncImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(ncImage.getImage())); - } - - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert nose cone attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory nose cone attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearNoseCone() { - ncAftDia.setValue(0); - ncAftShoulderDia.setValue(0); - ncAftShoulderLen.setValue(0); - ncDescTextField.setText(""); - ncPartNoTextField.setText(""); - ncLength.setValue(0); - ncMass.setValue(0); - ncFilledCB.setSelected(false); - ncImage = null; - ncImageBtn.setIcon(null); - } - - private ComponentPreset extractTransition() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - props.put(ComponentPreset.AFT_OUTER_DIAMETER, trAftDia.getValue()); - props.put(ComponentPreset.AFT_SHOULDER_DIAMETER, trAftShoulderDia.getValue()); - props.put(ComponentPreset.AFT_SHOULDER_LENGTH, trAftShoulderLen.getValue()); - props.put(ComponentPreset.FORE_OUTER_DIAMETER, trForeDia.getValue()); - props.put(ComponentPreset.FORE_SHOULDER_DIAMETER, trForeShoulderDia.getValue()); - props.put(ComponentPreset.FORE_SHOULDER_LENGTH, trForeShoulderLen.getValue()); - props.put(ComponentPreset.DESCRIPTION, trDescTextField.getText()); - props.put(ComponentPreset.PARTNO, trPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - - props.put(ComponentPreset.LENGTH, trLength.getValue()); - props.put(ComponentPreset.SHAPE, Transition.Shape.toShape((String) trShapeCB.getSelectedItem())); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, trMass.getValue()); - props.put(ComponentPreset.FILLED, trFilledCB.isSelected()); - if (trImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(trImage.getImage())); - } - - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert transition attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory transition attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearTransition() { - trAftDia.setValue(0); - trAftShoulderDia.setValue(0); - trAftShoulderLen.setValue(0); - trForeDia.setValue(0); - trForeShoulderDia.setValue(0); - trForeShoulderLen.setValue(0); - trDescTextField.setText(""); - trPartNoTextField.setText(""); - trLength.setValue(0); - trMass.setValue(0); - trFilledCB.setSelected(false); - trImage = null; - trImageBtn.setIcon(null); - } - - private ComponentPreset extractBodyTube() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - props.put(ComponentPreset.OUTER_DIAMETER, btOuterDia.getValue()); - props.put(ComponentPreset.INNER_DIAMETER, btInnerDia.getValue()); - props.put(ComponentPreset.DESCRIPTION, btDescTextField.getText()); - props.put(ComponentPreset.PARTNO, btPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, btLength.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, btMass.getValue()); - if (btImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(btImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert body tube attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory body tube attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearBodyTube() { - btOuterDia.setValue(0); - btInnerDia.setValue(0); - btDescTextField.setText(""); - btPartNoTextField.setText(""); - btLength.setValue(0); - btMass.setValue(0); - btImage = null; - btImageBtn.setIcon(null); - } - - public ComponentPreset extractTubeCoupler() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - props.put(ComponentPreset.OUTER_DIAMETER, tcOuterDia.getValue()); - props.put(ComponentPreset.INNER_DIAMETER, tcInnerDia.getValue()); - props.put(ComponentPreset.DESCRIPTION, tcDescTextField.getText()); - props.put(ComponentPreset.PARTNO, tcPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, tcLength.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, tcMass.getValue()); - if (tcImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(tcImage.getImage())); - } - - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert tube coupler attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory tube coupler attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearTubeCoupler() { - tcOuterDia.setValue(0); - tcInnerDia.setValue(0); - tcDescTextField.setText(""); - tcPartNoTextField.setText(""); - tcLength.setValue(0); - tcMass.setValue(0); - tcImage = null; - tcImageBtn.setIcon(null); - } - - private ComponentPreset extractBulkhead() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - props.put(ComponentPreset.OUTER_DIAMETER, bhOuterDia.getValue()); - props.put(ComponentPreset.DESCRIPTION, bhDescTextField.getText()); - props.put(ComponentPreset.PARTNO, bhPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, bhLength.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, bhMass.getValue()); - if (bhImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(bhImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert bulkhead attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory bulkhead attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearBulkhead() { - bhOuterDia.setValue(0); - bhDescTextField.setText(""); - bhPartNoTextField.setText(""); - bhLength.setValue(0); - bhMass.setValue(0); - bhImage = null; - bhImageBtn.setIcon(null); - } - - private ComponentPreset extractCenteringRing() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - props.put(ComponentPreset.OUTER_DIAMETER, crOuterDia.getValue()); - props.put(ComponentPreset.INNER_DIAMETER, crInnerDia.getValue()); - props.put(ComponentPreset.DESCRIPTION, crDescTextField.getText()); - props.put(ComponentPreset.PARTNO, crPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, crThickness.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, crMass.getValue()); - if (crImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(crImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert centering ring attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory centering ring attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearCenteringRing() { - crOuterDia.setValue(0); - crInnerDia.setValue(0); - crDescTextField.setText(""); - crPartNoTextField.setText(""); - crThickness.setValue(0); - crMass.setValue(0); - crImage = null; - crImageBtn.setIcon(null); - } - - public ComponentPreset extractEngineBlock() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - props.put(ComponentPreset.OUTER_DIAMETER, ebOuterDia.getValue()); - props.put(ComponentPreset.INNER_DIAMETER, ebInnerDia.getValue()); - props.put(ComponentPreset.DESCRIPTION, ebDescTextField.getText()); - props.put(ComponentPreset.PARTNO, ebPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, ebThickness.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, ebMass.getValue()); - if (ebImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(ebImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert engine block attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory engine block attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearEngineBlock() { - ebOuterDia.setValue(0); - ebInnerDia.setValue(0); - ebDescTextField.setText(""); - ebPartNoTextField.setText(""); - ebThickness.setValue(0); - ebMass.setValue(0); - ebImage = null; - ebImageBtn.setIcon(null); - } - - public ComponentPreset extractLaunchLug() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - props.put(ComponentPreset.OUTER_DIAMETER, llOuterDia.getValue()); - props.put(ComponentPreset.INNER_DIAMETER, llInnerDia.getValue()); - props.put(ComponentPreset.DESCRIPTION, llDescTextField.getText()); - props.put(ComponentPreset.PARTNO, llPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.LENGTH, llLength.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, llMass.getValue()); - if (llImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(llImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert launch lug attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory launch lug attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearLaunchLug() { - llOuterDia.setValue(0); - llInnerDia.setValue(0); - llDescTextField.setText(""); - llPartNoTextField.setText(""); - llLength.setValue(0); - llMass.setValue(0); - llImage = null; - llImageBtn.setIcon(null); - } - - public ComponentPreset extractParachute() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - props.put(ComponentPreset.DIAMETER, pcDiameter.getValue()); - props.put(ComponentPreset.DESCRIPTION, pcDescTextField.getText()); - props.put(ComponentPreset.PARTNO, pcPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - if (!pcLineCount.getText().equals("")) { - props.put(ComponentPreset.LINE_COUNT, Integer.parseInt(pcLineCount.getText())); - } - if (!pcSides.getText().equals("")) { - props.put(ComponentPreset.SIDES, Integer.parseInt(pcSides.getText())); - } - props.put(ComponentPreset.LINE_LENGTH, pcLineLength.getValue()); - Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - material = (Material) pcLineMaterialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.LINE_MATERIAL, material); - } - props.put(ComponentPreset.MASS, pcMass.getValue()); - if (pcImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(pcImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert parachute attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory parachute attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearParachute() { - ebOuterDia.setValue(0); - ebInnerDia.setValue(0); - ebDescTextField.setText(""); - ebPartNoTextField.setText(""); - ebThickness.setValue(0); - ebMass.setValue(0); - ebImage = null; - ebImageBtn.setIcon(null); - } - - public ComponentPreset extractStreamer() { - TypedPropertyMap props = new TypedPropertyMap(); - try { - props.put(ComponentPreset.TYPE, ComponentPreset.Type.STREAMER); - props.put(ComponentPreset.DESCRIPTION, stDescTextField.getText()); - props.put(ComponentPreset.PARTNO, stPartNoTextField.getText()); - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(mfgTextField.getText())); - props.put(ComponentPreset.THICKNESS, stThickness.getValue()); - props.put(ComponentPreset.LENGTH, stLength.getValue()); - props.put(ComponentPreset.WIDTH, stWidth.getValue()); - final Material material = (Material) materialChooser.getSelectedItem(); - if (material != null) { - props.put(ComponentPreset.MATERIAL, material); - } - else { - JOptionPane.showMessageDialog(null, "A material must be selected.", "Error", JOptionPane.ERROR_MESSAGE); - return null; - } - props.put(ComponentPreset.MASS, stMass.getValue()); - if (stImage != null) { - props.put(ComponentPreset.IMAGE, imageToByteArray(stImage.getImage())); - } - return ComponentPresetFactory.create(props); - } catch (NumberFormatException nfe) { - JOptionPane.showMessageDialog(null, "Could not convert engine block attribute.", "Error", JOptionPane.ERROR_MESSAGE); - } catch (InvalidComponentPresetException e) { - JOptionPane.showMessageDialog(null, craftErrorMessage(e, "Mandatory engine block attribute not set."), "Error", JOptionPane.ERROR_MESSAGE); - } - return null; - } - - private void clearStreamer() { - stWidth.setValue(0); - stLength.setValue(0); - stDescTextField.setText(""); - stPartNoTextField.setText(""); - stThickness.setValue(0); - stMass.setValue(0); - stImage = null; - stImageBtn.setIcon(null); - } - - @Override - public void itemStateChanged(ItemEvent evt) { - CardLayout cl = (CardLayout) (componentOverlayPanel.getLayout()); - final String item = (String) evt.getItem(); - if (materialChooser != null && evt.getStateChange() == ItemEvent.SELECTED) { - if (item.equals(trans.get(PARACHUTE_KEY)) || item.equals(trans.get(STREAMER_KEY))) { - if (!((MaterialModel) materialChooser.getModel()).getType().equals(Material.Type.SURFACE)) { - setMaterial(materialChooser, null, holder, Material.Type.SURFACE, ComponentPreset.MATERIAL); - } - } - else { - if (!((MaterialModel) materialChooser.getModel()).getType().equals(Material.Type.BULK)) { - setMaterial(materialChooser, null, holder, Material.Type.BULK, ComponentPreset.MATERIAL); - } - } - } - cl.show(componentOverlayPanel, componentMap.get(item)); - } - - //Todo: I18N - private String craftErrorMessage(InvalidComponentPresetException e, String baseMsg) { - StringBuilder stringBuilder = new StringBuilder(); - List invalids = e.getErrors(); - stringBuilder.append(baseMsg).append("\n"); - for (int i = 0; i < invalids.size(); i++) { - String s = invalids.get(i); - stringBuilder.append(s).append("\n"); - } - - return stringBuilder.toString(); - } - - /** - * Convert an image to a byte array in png format. - * - * @param originalImage - * - * @return - */ - private byte[] imageToByteArray(Image originalImage) { - byte[] imageInByte = null; - try { - BufferedImage bi = imageToBufferedImage(originalImage); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(bi, "png", baos); - baos.flush(); - imageInByte = baos.toByteArray(); - baos.close(); - } catch (IOException e) { - log.error("Could not read image."); - } - return imageInByte; - } - - private BufferedImage imageToBufferedImage(final Image originalImage) { - BufferedImage bi = new BufferedImage(originalImage.getWidth(null), originalImage.getHeight(null), BufferedImage.TYPE_INT_RGB); - - Graphics2D g2 = bi.createGraphics(); - g2.drawImage(originalImage, 0, 0, null); - return bi; - } - - private BufferedImage byteArrayToImage(byte[] src) { - // convert byte array back to BufferedImage - InputStream in = new ByteArrayInputStream(src); - try { - return ImageIO.read(in); - } catch (IOException e) { - log.error("Could not convert image."); - } - return null; - } - - private ImageIcon scaleImage(Image image, int targetDimension) { - int width = image.getWidth(this); - int height = image.getHeight(this); - double ratio = 1.0; - - /* - * Determine how to scale the image. Since the accessory can expand - * vertically make sure we don't go larger than 150 when scaling - * vertically. - */ - if (width >= height) { - ratio = (double) (targetDimension - 5) / width; - width = targetDimension - 5; - height = (int) (height * ratio); - } - else { - if (getHeight() > 150) { - ratio = (double) (targetDimension - 5) / height; - height = targetDimension - 5; - width = (int) (width * ratio); - } - else { - ratio = (double) getHeight() / height; - height = getHeight(); - width = (int) (width * ratio); - } - } - - return new ImageIcon(image.getScaledInstance(width, height, Image.SCALE_DEFAULT)); - } - - static class PresetInputVerifier extends InputVerifier { - - /** - * Matches user input against a regular expression. - */ - private Matcher matcher; - - PresetInputVerifier(final Pattern thePattern) { - matcher = thePattern.matcher(""); - } - - /** - * Return true only if the untrimmed user input matches the regular expression provided to the constructor. - * - * @param aComponent must be an instance of JTextComponent. - */ - @Override - public boolean verify(JComponent aComponent) { - JTextComponent textComponent = (JTextComponent) aComponent; - String text = textComponent.getText(); - matcher.reset(text); - return matcher.matches(); - } - - /** - * Always returns true, in this implementation, such that focus can always transfer to another - * component whenever the validation fails. - *

- *

If super.shouldYieldFocus returns false, then clear the text field. - * - * @param aComponent is a JTextComponent. - */ - @Override - public boolean shouldYieldFocus(JComponent aComponent) { - if (!super.shouldYieldFocus(aComponent)) { - ((JTextComponent) aComponent).setText(""); - } - return true; - } - } - - class MaterialChooser extends JComboBox { - - public MaterialChooser() { - } - - public MaterialChooser(MaterialModel model) { - super(model); - } - - /** - * Sets the data model that the JComboBox uses to obtain the list of items. - * - * @param aModel the ComboBoxModel that provides the displayed list of items - * - * @beaninfo bound: true description: Model that the combo box uses to get data to display. - */ - @Override - public void setModel(final ComboBoxModel aModel) { - if (getModel() instanceof MaterialModel) { - MaterialModel old = (MaterialModel) getModel(); - old.removeListener(); - } - super.setModel(aModel); - - } - } -} diff --git a/core/src/net/sf/openrocket/gui/preset/PresetResultListener.java b/core/src/net/sf/openrocket/gui/preset/PresetResultListener.java deleted file mode 100644 index a5c2e1be..00000000 --- a/core/src/net/sf/openrocket/gui/preset/PresetResultListener.java +++ /dev/null @@ -1,11 +0,0 @@ - -package net.sf.openrocket.gui.preset; - -import net.sf.openrocket.preset.ComponentPreset; - -/** - */ -public interface PresetResultListener { - - void notifyResult(ComponentPreset preset); -} diff --git a/core/src/net/sf/openrocket/gui/print/AbstractPrintable.java b/core/src/net/sf/openrocket/gui/print/AbstractPrintable.java deleted file mode 100644 index 585e4975..00000000 --- a/core/src/net/sf/openrocket/gui/print/AbstractPrintable.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.sf.openrocket.gui.print; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; - -public abstract class AbstractPrintable extends PrintableComponent { - /** - * A thin stroke. - */ - public final static BasicStroke thinStroke = new BasicStroke(1.0f); - - /** - * A thick stroke. - */ - public final static BasicStroke thickStroke = new BasicStroke(4.0f); - - /** - * Constructor. Initialize this printable with the component to be printed. - * - * @param isDoubleBuffered a boolean, true for double-buffering - * @param transition the component to be printed - */ - public AbstractPrintable(boolean isDoubleBuffered, T transition) { - init(transition); - } - - /** - * Initialize the printable. - * - * @param component the component - */ - protected abstract void init(T component); - - /** - * Draw the component onto the graphics context. - * - * @param g2 the graphics context - */ - protected abstract void draw(Graphics2D g2); - - /** - * Returns a generated image of the component. May then be used wherever AWT images can be used, or converted to - * another image/picture format and used accordingly. - * - * @return an awt image of the printable component - */ - public Image createImage() { - int width = getWidth() + getOffsetX(); - int height = getHeight() + getOffsetY(); - // Create a buffered image in which to draw - BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - // Create a graphics contents on the buffered image - Graphics2D g2d = bufferedImage.createGraphics(); - // Draw graphics - g2d.setBackground(Color.white); - g2d.clearRect(0, 0, width, height); - paintComponent(g2d); - // Graphics context no longer needed so dispose it - g2d.dispose(); - return bufferedImage; - } - - @Override - public void paintComponent(Graphics g) { - Graphics2D g2 = (Graphics2D) g; - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - g2.setColor(Color.BLACK); - g2.setStroke(thinStroke); - g2.translate(getOffsetX(), getOffsetY()); - - draw(g2); - } -} diff --git a/core/src/net/sf/openrocket/gui/print/ConceptPrintDialog.java b/core/src/net/sf/openrocket/gui/print/ConceptPrintDialog.java deleted file mode 100644 index 9a07efa0..00000000 --- a/core/src/net/sf/openrocket/gui/print/ConceptPrintDialog.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.sf.openrocket.gui.print; - -import java.awt.Window; -import java.lang.reflect.InvocationTargetException; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.SwingUtilities; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.GUIUtil; - -public class ConceptPrintDialog extends JDialog { - - public ConceptPrintDialog() { - super((Window) null, "Print"); - - JPanel panel = new JPanel(new MigLayout("fill")); - - JList list = new JList(new Object[] { - "Model name", - "Parts detail", - "Fin templates", - "Design report" - }); - panel.add(new JScrollPane(list), "spanx, growx, wrap"); - - JCheckBox checkbox = new JCheckBox("Show by stage"); - panel.add(checkbox, ""); - - JButton button = new JButton("Settings"); - panel.add(button, "right, wrap para"); - - JLabel label = new JLabel("Printer: LaserJet 6L
Paper size: A4 Portrait"); - panel.add(label); - - button = new JButton("Change"); - panel.add(button, "right, wrap 20lp"); - - panel.add(new JButton("Save as PDF"), "split, spanx, right"); - panel.add(new JButton("Preview"), "right"); - panel.add(new JButton("Print"), "right"); - panel.add(new JButton("Close"), "right"); - - - this.add(panel); - - } - - - - public static void main(String[] args) throws InterruptedException, InvocationTargetException { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - GUIUtil.setBestLAF(); - JDialog dialog = new ConceptPrintDialog(); - GUIUtil.setDisposableDialogOptions(dialog, null); - dialog.setSize(450, 350); - dialog.setVisible(true); - } - }); - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/DesignReport.java b/core/src/net/sf/openrocket/gui/print/DesignReport.java deleted file mode 100644 index 54c0f3eb..00000000 --- a/core/src/net/sf/openrocket/gui/print/DesignReport.java +++ /dev/null @@ -1,550 +0,0 @@ -/* - * DesignReport.java - */ -package net.sf.openrocket.gui.print; - -import java.awt.Graphics2D; -import java.io.IOException; -import java.text.DecimalFormat; -import java.util.List; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.figureelements.FigureElement; -import net.sf.openrocket.gui.figureelements.RocketInfo; -import net.sf.openrocket.gui.scalefigure.RocketPanel; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.Coordinate; - -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Element; -import com.itextpdf.text.Paragraph; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.BaseFont; -import com.itextpdf.text.pdf.DefaultFontMapper; -import com.itextpdf.text.pdf.PdfContentByte; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; - -/** - *

- * #  Title # Section describing the rocket in general without motors
- * # Section describing the rocket in general without motors
- * 

- * design name - * empty mass & CG - * CP position - * CP position at 5 degree AOA (or similar) - * number of stages - * parachute/streamer sizes - * max. diameter (caliber) - * velocity at exit of rail/rod - * minimum safe velocity reached in x inches/cm - *

- * # Section for each motor configuration - *

- * a summary of the motors, e.g. 3xC6-0; B4-6 - * a list of the motors including the manufacturer, designation (maybe also info like burn time, grams of propellant, - * total impulse) - * total grams of propellant - * total impulse - * takeoff weight - * CG and CP position, stability margin - * predicted flight altitude, max. velocity and max. acceleration - * predicted velocity at chute deployment - * predicted descent rate - * Thrust to Weight Ratio of each stage - *

- *

- */ -public class DesignReport { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - public static final double SCALE_FUDGE_FACTOR = 0.4d; - - /** - * The OR Document. - */ - private OpenRocketDocument rocketDocument; - - /** - * A panel used for rendering of the design diagram. - */ - final RocketPanel panel; - - /** - * The iText document. - */ - protected Document document; - - /** - * The figure rotation. - */ - private double rotation = 0d; - - /** The displayed strings. */ - private static final String STAGES = "Stages: "; - private static final String MASS_WITH_MOTORS = "Mass (with motors): "; - private static final String MASS_WITH_MOTOR = "Mass (with motor): "; - private static final String MASS_EMPTY = "Mass (Empty): "; - private static final String STABILITY = "Stability: "; - private static final String CG = "CG: "; - private static final String CP = "CP: "; - private static final String MOTOR = "Motor"; - private static final String AVG_THRUST = "Avg Thrust"; - private static final String BURN_TIME = "Burn Time"; - private static final String MAX_THRUST = "Max Thrust"; - private static final String TOTAL_IMPULSE = "Total Impulse"; - private static final String THRUST_TO_WT = "Thrust to Wt"; - private static final String PROPELLANT_WT = "Propellant Wt"; - private static final String SIZE = "Size"; - private static final String ALTITUDE = "Altitude"; - private static final String FLIGHT_TIME = "Flight Time"; - private static final String TIME_TO_APOGEE = "Time to Apogee"; - private static final String VELOCITY_OFF_PAD = "Velocity off Pad"; - private static final String MAX_VELOCITY = "Max Velocity"; - private static final String DEPLOYMENT_VELOCITY = "Velocity at Deployment"; - private static final String LANDING_VELOCITY = "Landing Velocity"; - private static final String ROCKET_DESIGN = "Rocket Design"; - private static final double GRAVITY_CONSTANT = 9.80665d; - - /** - * Constructor. - * - * @param theRocDoc the OR document - * @param theIDoc the iText document - * @param figureRotation the angle the figure is rotated on the screen; printed report will mimic - */ - public DesignReport(OpenRocketDocument theRocDoc, Document theIDoc, Double figureRotation) { - document = theIDoc; - rocketDocument = theRocDoc; - panel = new RocketPanel(rocketDocument); - rotation = figureRotation; - } - - /** - * Main entry point. Prints the rocket drawing and design data. - * - * @param writer a direct byte writer - */ - public void writeToDocument(PdfWriter writer) { - if (writer == null) { - return; - } - com.itextpdf.text.Rectangle pageSize = document.getPageSize(); - int pageImageableWidth = (int) pageSize.getWidth() - (int) pageSize.getBorderWidth() * 2; - int pageImageableHeight = (int) pageSize.getHeight() / 2 - (int) pageSize.getBorderWidthTop(); - - PrintUtilities.addText(document, PrintUtilities.BIG_BOLD, ROCKET_DESIGN); - - Rocket rocket = rocketDocument.getRocket(); - final Configuration configuration = rocket.getDefaultConfiguration().clone(); - configuration.setAllStages(); - PdfContentByte canvas = writer.getDirectContent(); - - final PrintFigure figure = new PrintFigure(configuration); - figure.setRotation(rotation); - - FigureElement cp = panel.getExtraCP(); - FigureElement cg = panel.getExtraCG(); - RocketInfo text = panel.getExtraText(); - - double scale = paintRocketDiagram(pageImageableWidth, pageImageableHeight, canvas, figure, cp, cg); - - canvas.beginText(); - canvas.setFontAndSize(ITextHelper.getBaseFont(), PrintUtilities.NORMAL_FONT_SIZE); - int figHeightPts = (int) (PrintUnit.METERS.toPoints(figure.getFigureHeight()) * 0.4 * (scale / PrintUnit.METERS - .toPoints(1))); - final int diagramHeight = pageImageableHeight * 2 - 70 - (figHeightPts); - canvas.moveText(document.leftMargin() + pageSize.getBorderWidthLeft(), diagramHeight); - canvas.moveTextWithLeading(0, -16); - - float initialY = canvas.getYTLM(); - - canvas.showText(rocketDocument.getRocket().getName()); - - canvas.newlineShowText(STAGES); - canvas.showText("" + rocket.getStageCount()); - - - if (configuration.hasMotors()) { - if (configuration.getStageCount() > 1) { - canvas.newlineShowText(MASS_WITH_MOTORS); - } else { - canvas.newlineShowText(MASS_WITH_MOTOR); - } - } else { - canvas.newlineShowText(MASS_EMPTY); - } - canvas.showText(text.getMass(UnitGroup.UNITS_MASS.getDefaultUnit())); - - canvas.newlineShowText(STABILITY); - canvas.showText(text.getStability()); - - canvas.newlineShowText(CG); - canvas.showText(text.getCg()); - - canvas.newlineShowText(CP); - canvas.showText(text.getCp()); - canvas.endText(); - - try { - //Move the internal pointer of the document below that of what was just written using the direct byte buffer. - Paragraph paragraph = new Paragraph(); - float finalY = canvas.getYTLM(); - int heightOfDiagramAndText = (int) (pageSize.getHeight() - (finalY - initialY + diagramHeight)); - - paragraph.setSpacingAfter(heightOfDiagramAndText); - document.add(paragraph); - - String[] motorIds = rocket.getMotorConfigurationIDs(); - List simulations = rocketDocument.getSimulations(); - - for (int j = 0; j < motorIds.length; j++) { - String motorId = motorIds[j]; - if (motorId != null) { - PdfPTable parent = new PdfPTable(2); - parent.setWidthPercentage(100); - parent.setHorizontalAlignment(Element.ALIGN_LEFT); - parent.setSpacingBefore(0); - parent.setWidths(new int[] { 1, 3 }); - int leading = 0; - //The first motor config is always null. Skip it and the top-most motor, then set the leading. - if (j > 1) { - leading = 25; - } - FlightData flight = findSimulation(motorId, simulations); - addFlightData(flight, rocket, motorId, parent, leading); - addMotorData(rocket, motorId, parent); - document.add(parent); - } - } - } catch (DocumentException e) { - log.error("Could not modify document.", e); - } - } - - - /** - * Paint a diagram of the rocket into the PDF document. - * - * @param thePageImageableWidth the number of points in the width of the page available for drawing - * @param thePageImageableHeight the number of points in the height of the page available for drawing - * @param theCanvas the direct byte writer - * @param theFigure the print figure - * @param theCp the center of pressure figure element - * @param theCg the center of gravity figure element - * - * @return the scale of the diagram - */ - private double paintRocketDiagram(final int thePageImageableWidth, final int thePageImageableHeight, - final PdfContentByte theCanvas, final PrintFigure theFigure, - final FigureElement theCp, final FigureElement theCg) { - theFigure.clearAbsoluteExtra(); - theFigure.clearRelativeExtra(); - theFigure.addRelativeExtra(theCp); - theFigure.addRelativeExtra(theCg); - theFigure.updateFigure(); - - double scale = - (thePageImageableWidth * 2.2) / theFigure.getFigureWidth(); - theFigure.setScale(scale); - /* - * page dimensions are in points-per-inch, which, in Java2D, are the same as pixels-per-inch; thus we don't need any conversion - */ - theFigure.setSize(thePageImageableWidth, thePageImageableHeight); - theFigure.updateFigure(); - - final DefaultFontMapper mapper = new DefaultFontMapper(); - Graphics2D g2d = theCanvas.createGraphics(thePageImageableWidth, thePageImageableHeight * 2, mapper); - final double halfFigureHeight = SCALE_FUDGE_FACTOR * theFigure.getFigureHeightPx()/2; - int y = PrintUnit.POINTS_PER_INCH; - //If the y dimension is negative, then it will potentially be drawn off the top of the page. Move the origin - //to allow for this. - if (theFigure.getDimensions().getY() < 0.0d) { - y += (int)halfFigureHeight; - } - g2d.translate(20, y); - - g2d.scale(SCALE_FUDGE_FACTOR, SCALE_FUDGE_FACTOR); - theFigure.paint(g2d); - g2d.dispose(); - return scale; - } - - /** - * Add the motor data for a motor configuration to the table. - * - * @param rocket the rocket - * @param motorId the motor ID to output - * @param parent the parent to which the motor data will be added - */ - private void addMotorData(Rocket rocket, String motorId, final PdfPTable parent) { - - PdfPTable motorTable = new PdfPTable(8); - motorTable.setWidthPercentage(68); - motorTable.setHorizontalAlignment(Element.ALIGN_LEFT); - - final PdfPCell motorCell = ITextHelper.createCell(MOTOR, PdfPCell.BOTTOM, PrintUtilities.SMALL); - final int mPad = 10; - motorCell.setPaddingLeft(mPad); - motorTable.addCell(motorCell); - motorTable.addCell(ITextHelper.createCell(AVG_THRUST, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - motorTable.addCell(ITextHelper.createCell(BURN_TIME, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - motorTable.addCell(ITextHelper.createCell(MAX_THRUST, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - motorTable.addCell(ITextHelper.createCell(TOTAL_IMPULSE, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - motorTable.addCell(ITextHelper.createCell(THRUST_TO_WT, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - motorTable.addCell(ITextHelper.createCell(PROPELLANT_WT, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - motorTable.addCell(ITextHelper.createCell(SIZE, PdfPCell.BOTTOM, PrintUtilities.SMALL)); - - DecimalFormat ttwFormat = new DecimalFormat("0.00"); - - MassCalculator massCalc = new BasicMassCalculator(); - - Configuration config = new Configuration(rocket); - config.setMotorConfigurationID(motorId); - - int totalMotorCount = 0; - double totalPropMass = 0; - double totalImpulse = 0; - double totalTTW = 0; - - int stage = 0; - double stageMass = 0; - - boolean topBorder = false; - for (RocketComponent c : rocket) { - - if (c instanceof Stage) { - config.setToStage(stage); - stage++; - stageMass = massCalc.getCG(config, MassCalcType.LAUNCH_MASS).weight; - // Calculate total thrust-to-weight from only lowest stage motors - totalTTW = 0; - topBorder = true; - } - - if (c instanceof MotorMount && ((MotorMount) c).isMotorMount()) { - MotorMount mount = (MotorMount) c; - - if (mount.isMotorMount() && mount.getMotor(motorId) != null) { - Motor motor = mount.getMotor(motorId); - int motorCount = c.toAbsolute(Coordinate.NUL).length; - - - int border = Rectangle.NO_BORDER; - if (topBorder) { - border = Rectangle.TOP; - topBorder = false; - } - - String name = motor.getDesignation(); - if (motorCount > 1) { - name += " (" + Chars.TIMES + motorCount + ")"; - } - - final PdfPCell motorVCell = ITextHelper.createCell(name, border); - motorVCell.setPaddingLeft(mPad); - motorTable.addCell(motorVCell); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getAverageThrustEstimate()), border)); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit().toStringUnit(motor.getBurnTimeEstimate()), border)); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getMaxThrustEstimate()), border)); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(motor.getTotalImpulseEstimate()), border)); - - double ttw = motor.getAverageThrustEstimate() / (stageMass * GRAVITY_CONSTANT); - motorTable.addCell(ITextHelper.createCell( - ttwFormat.format(ttw) + ":1", border)); - - double propMass = (motor.getLaunchCG().weight - motor.getEmptyCG().weight); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(propMass), border)); - - final Unit motorUnit = UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit(); - motorTable.addCell(ITextHelper.createCell(motorUnit.toString(motor.getDiameter()) + - "/" + - motorUnit.toString(motor.getLength()) + " " + - motorUnit.toString(), border)); - - // Sum up total count - totalMotorCount += motorCount; - totalPropMass += propMass * motorCount; - totalImpulse += motor.getTotalImpulseEstimate() * motorCount; - totalTTW += ttw * motorCount; - } - } - } - - if (totalMotorCount > 1) { - int border = Rectangle.TOP; - final PdfPCell motorVCell = ITextHelper.createCell("Total:", border); - motorVCell.setPaddingLeft(mPad); - motorTable.addCell(motorVCell); - motorTable.addCell(ITextHelper.createCell("", border)); - motorTable.addCell(ITextHelper.createCell("", border)); - motorTable.addCell(ITextHelper.createCell("", border)); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(totalImpulse), border)); - motorTable.addCell(ITextHelper.createCell( - ttwFormat.format(totalTTW) + ":1", border)); - motorTable.addCell(ITextHelper.createCell( - UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(totalPropMass), border)); - motorTable.addCell(ITextHelper.createCell("", border)); - - } - - PdfPCell c = new PdfPCell(motorTable); - c.setBorder(PdfPCell.LEFT); - c.setBorderWidthTop(0f); - parent.addCell(c); - } - - - /** - * Add the flight data for a simulation configuration to the table. - * - * @param flight the flight data for a single simulation - * @param theRocket the rocket - * @param motorId a motor configuration id - * @param parent the parent to which the simulation flight data will be added - * @param leading the number of points for the leading - */ - private void addFlightData(final FlightData flight, final Rocket theRocket, final String motorId, final PdfPTable parent, int leading) { - - // Output the flight data - if (flight != null) { - try { - final Unit distanceUnit = UnitGroup.UNITS_DISTANCE.getDefaultUnit(); - final Unit velocityUnit = UnitGroup.UNITS_VELOCITY.getDefaultUnit(); - final Unit flightTimeUnit = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit(); - - PdfPTable labelTable = new PdfPTable(2); - labelTable.setWidths(new int[] { 3, 2 }); - final Paragraph chunk = ITextHelper.createParagraph(stripBrackets( - theRocket.getMotorConfigurationNameOrDescription(motorId)), PrintUtilities.BOLD); - chunk.setLeading(leading); - chunk.setSpacingAfter(3f); - - document.add(chunk); - - final PdfPCell cell = ITextHelper.createCell(ALTITUDE, 2, 2); - cell.setUseBorderPadding(false); - cell.setBorderWidthTop(0f); - labelTable.addCell(cell); - labelTable.addCell(ITextHelper.createCell(distanceUnit.toStringUnit(flight.getMaxAltitude()), 2, 2)); - - labelTable.addCell(ITextHelper.createCell(FLIGHT_TIME, 2, 2)); - labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getFlightTime()), 2, 2)); - - labelTable.addCell(ITextHelper.createCell(TIME_TO_APOGEE, 2, 2)); - labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getTimeToApogee()), 2, 2)); - - labelTable.addCell(ITextHelper.createCell(VELOCITY_OFF_PAD, 2, 2)); - labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getLaunchRodVelocity()), 2, 2)); - - labelTable.addCell(ITextHelper.createCell(MAX_VELOCITY, 2, 2)); - labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getMaxVelocity()), 2, 2)); - - labelTable.addCell(ITextHelper.createCell(DEPLOYMENT_VELOCITY, 2,2)); - labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getDeploymentVelocity()),2,2)); - - labelTable.addCell(ITextHelper.createCell(LANDING_VELOCITY, 2, 2)); - labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getGroundHitVelocity()), 2, 2)); - - //Add the table to the parent; have to wrap it in a cell - PdfPCell c = new PdfPCell(labelTable); - c.setBorder(PdfPCell.RIGHT); - c.setBorderWidthTop(0); - c.setTop(0); - parent.addCell(c); - } catch (DocumentException e) { - log.error("Could not add flight data to document.", e); - } - } - } - - /** - * Locate the simulation based on the motor id. Copy the simulation and execute it, then return the resulting - * flight data. - * - * @param motorId the motor id corresponding to the simulation to find - * @param simulations the list of simulations currently associated with the rocket - * - * @return the flight data from the simulation for the specified motor id, or null if not found - */ - private FlightData findSimulation(final String motorId, List simulations) { - // Perform flight simulation - FlightData flight = null; - try { - for (int i = 0; i < simulations.size(); i++) { - Simulation simulation = simulations.get(i); - if (simulation.getOptions().getMotorConfigurationID().equals(motorId)) { - simulation = simulation.copy(); - simulation.simulate(); - flight = simulation.getSimulatedData(); - break; - } - } - } catch (SimulationException e1) { - // Ignore - } - return flight; - } - - /** - * Strip [] brackets from a string. - * - * @param target the original string - * - * @return target with [] removed - */ - private String stripBrackets(String target) { - return stripLeftBracket(stripRightBracket(target)); - } - - /** - * Strip [ from a string. - * - * @param target the original string - * - * @return target with [ removed - */ - private String stripLeftBracket(String target) { - return target.replace("[", ""); - } - - /** - * Strip ] from a string. - * - * @param target the original string - * - * @return target with ] removed - */ - private String stripRightBracket(String target) { - return target.replace("]", ""); - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/FinMarkingGuide.java b/core/src/net/sf/openrocket/gui/print/FinMarkingGuide.java deleted file mode 100644 index 64b617ab..00000000 --- a/core/src/net/sf/openrocket/gui/print/FinMarkingGuide.java +++ /dev/null @@ -1,483 +0,0 @@ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - -import javax.swing.JPanel; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * This is the core Swing representation of a fin marking guide. It can handle multiple fin sets on the same or - * different body tubes. One marking guide will be created for any body tube that has a finset. If a tube has multiple - * finsets, then they are combined onto one marking guide. It also includes launch lug marking line(s) if lugs are - * present. If (and only if) a launch lug exists, then the word 'Front' is affixed to the leading edge of the guide to - * give orientation. - *

- */ -public class FinMarkingGuide extends JPanel { - - /** - * The stroke of normal lines. - */ - private final static BasicStroke thinStroke = new BasicStroke(1.0f); - - /** - * The size of the arrow in points. - */ - private static final int ARROW_SIZE = 10; - - /** - * Typical thickness of a piece of printer paper (~20-24 lb paper). Wrapping paper around a tube results in the - * radius being increased by the thickness of the paper. The smaller the tube, the more pronounced this becomes as a - * percentage of circumference. Using 1/10mm as an approximation here. - */ - private static final double PAPER_THICKNESS_IN_METERS = PrintUnit.MILLIMETERS.toMeters(0.1d); - - /** - * The default guide width in inches. - */ - public final static double DEFAULT_GUIDE_WIDTH = 3d; - - /** - * 2 PI radians (represents a circle). - */ - public final static double TWO_PI = 2 * Math.PI; - - /** - * The I18N translator. - */ - private static final Translator trans = Application.getTranslator(); - - /** - * The margin. - */ - private static final int MARGIN = (int) PrintUnit.INCHES.toPoints(0.25f); - - /** - * The height (circumference) of the biggest body tube with a finset. - */ - private int maxHeight = 0; - - /** - * A map of body tubes, to a list of components that contains finsets and launch lugs. - */ - private Map> markingGuideItems; - - /** - * Constructor. - * - * @param rocket the rocket instance - */ - public FinMarkingGuide(Rocket rocket) { - super(false); - setBackground(Color.white); - markingGuideItems = init(rocket); - //Max of 2 drawing guides horizontally per page. - setSize((int) PrintUnit.INCHES.toPoints(DEFAULT_GUIDE_WIDTH) * 2 + 3 * MARGIN, maxHeight); - } - - /** - * Initialize the marking guide class by iterating over a rocket and finding all finsets. - * - * @param component the root rocket component - this is iterated to find all finset and launch lugs - * - * @return a map of body tubes to lists of finsets and launch lugs. - */ - private Map> init(Rocket component) { - Iterator iter = component.iterator(false); - Map> results = new LinkedHashMap>(); - BodyTube current = null; - int totalHeight = 0; - int iterationHeight = 0; - int count = 0; - - while (iter.hasNext()) { - RocketComponent next = iter.next(); - if (next instanceof BodyTube) { - current = (BodyTube) next; - } - else if (next instanceof FinSet || next instanceof LaunchLug) { - java.util.List list = results.get(current); - if (list == null && current != null) { - list = new ArrayList(); - results.put(current, list); - - double radius = current.getOuterRadius(); - int circumferenceInPoints = (int) PrintUnit.METERS.toPoints(radius * TWO_PI); - - // Find the biggest body tube circumference. - if (iterationHeight < (circumferenceInPoints + MARGIN)) { - iterationHeight = circumferenceInPoints + MARGIN; - } - //At most, two marking guides horizontally. After that, move down and back to the left margin. - count++; - if (count % 2 == 0) { - totalHeight += iterationHeight; - iterationHeight = 0; - } - } - if (list != null) { - list.add((ExternalComponent) next); - } - } - } - maxHeight = totalHeight + iterationHeight; - return results; - } - - /** - * Returns a generated image of the fin marking guide. May then be used wherever AWT images can be used, or - * converted to another image/picture format and used accordingly. - * - * @return an awt image of the fin marking guide - */ - public Image createImage() { - int width = getWidth() + 25; - int height = getHeight() + 25; - // Create a buffered image in which to draw - BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - // Create a graphics context on the buffered image - Graphics2D g2d = bufferedImage.createGraphics(); - // Draw graphics - g2d.setBackground(Color.white); - g2d.clearRect(0, 0, width, height); - paintComponent(g2d); - // Graphics context no longer needed so dispose it - g2d.dispose(); - return bufferedImage; - } - - /** - *

-     *   ---------------------- Page Edge --------------------------------------------------------
-     *   |                                        ^
-     *   |                                        |
-     *   |
-     *   |                                        y
-     *   |
-     *   |                                        |
-     *   P                                        v
-     *   a      ---                 +----------------------------+  ------------
-     *   g<------^-- x ------------>+                            +       ^
-     *   e       |                  +                            +       |
-     *           |                  +                            +     baseYOffset
-     *   E       |                  +                            +       v
-     *   d       |                  +<----------Fin------------->+ -------------
-     *   g       |                  +                            +
-     *   e       |                  +                            +
-     *   |       |                  +                            +
-     *   |       |                  +                            +
-     *   |       |                  +                            +   baseSpacing
-     *   |       |                  +                            +
-     *   |       |                  +                            +
-     *   |       |                  +                            +
-     *   |       |                  +                            +
-     *   |       |                  +<----------Fin------------->+  --------------
-     *   |       |                  +                            +
-     *   | circumferenceInPoints    +                            +
-     *   |       |                  +                            +
-     *   |       |                  +                            +
-     *   |       |                  +                            +    baseSpacing
-     *   |       |                  +<------Launch Lug --------->+           -----
-     *   |       |                  +                            +                 \
-     *   |       |                  +                            +                 + yLLOffset
-     *   |       |                  +                            +                 /
-     *   |       |                  +<----------Fin------------->+  --------------
-     *   |       |                  +                            +       ^
-     *   |       |                  +                            +       |
-     *   |       |                  +                            +    baseYOffset
-     *   |       v                  +                            +       v
-     *   |      ---                 +----------------------------+  --------------
-     *
-     *                              |<-------- width ----------->|
-     *
-     * yLLOffset is computed from the difference between the base rotation of the fin and the radial direction of the
-     * lug.
-     *
-     * Note: There is a current limitation that a tube with multiple launch lugs may not render the lug lines
-     * correctly.
-     * 
- * - * @param g the Graphics context - */ - @Override - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g; - paintFinMarkingGuide(g2); - } - - private void paintFinMarkingGuide(Graphics2D g2) { - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - g2.setColor(Color.BLACK); - g2.setStroke(thinStroke); - int x = MARGIN; - int y = MARGIN; - - int width = (int) PrintUnit.INCHES.toPoints(DEFAULT_GUIDE_WIDTH); - - int column = 0; - - for (BodyTube next : markingGuideItems.keySet()) { - double circumferenceInPoints = PrintUnit.METERS.toPoints((next.getOuterRadius() + PAPER_THICKNESS_IN_METERS) * - TWO_PI); - List componentList = markingGuideItems.get(next); - //Don't draw the lug if there are no fins. - if (hasFins(componentList)) { - - drawMarkingGuide(g2, x, y, (int) Math.ceil(circumferenceInPoints), width); - - //Sort so that fins always precede lugs - sort(componentList); - - boolean hasMultipleComponents = componentList.size() > 1; - - double baseSpacing = 0d; - double baseYOrigin = 0; - double finRadial = 0d; - int yFirstFin = y; - int yLastFin = y; - boolean firstFinSet = true; - - //fin1: 42 fin2: 25 - for (ExternalComponent externalComponent : componentList) { - if (externalComponent instanceof FinSet) { - FinSet fins = (FinSet) externalComponent; - int finCount = fins.getFinCount(); - int offset = 0; - baseSpacing = (circumferenceInPoints / finCount); - double baseRotation = fins.getBaseRotation(); - if (!firstFinSet) { - //Adjust the rotation to a positive number. - while (baseRotation < 0) { - baseRotation += TWO_PI / finCount; - } - offset = computeYOffset(y, circumferenceInPoints, baseSpacing, baseYOrigin, finRadial, baseRotation); - } - else { - //baseYOrigin is the distance from the top of the marking guide to the first fin of the first fin set. - //This measurement is used to base all subsequent finsets and lugs off of. - baseYOrigin = baseSpacing / 2; - offset = (int) (baseYOrigin) + y; - firstFinSet = false; - } - yFirstFin = y; - yLastFin = y; - finRadial = baseRotation; - - //Draw the fin marking lines. - for (int fin = 0; fin < finCount; fin++) { - if (fin > 0) { - offset += baseSpacing; - yLastFin = offset; - } - else { - yFirstFin = offset; - } - drawDoubleArrowLine(g2, x, offset, x + width, offset); - // if (hasMultipleComponents) { - g2.drawString(externalComponent.getName(), x + (width / 3), offset - 2); - // } - } - } - else if (externalComponent instanceof LaunchLug) { - LaunchLug lug = (LaunchLug) externalComponent; - double yLLOffset = (lug.getRadialDirection() - finRadial) / TWO_PI; - //The placement of the lug line must respect the boundary of the outer marking guide. In order - //to do that, place it above or below either the top or bottom fin line, based on the difference - //between their rotational directions. - if (yLLOffset < 0) { - yLLOffset = yLLOffset * circumferenceInPoints + yLastFin; - } - else { - yLLOffset = yLLOffset * circumferenceInPoints + yFirstFin; - } - drawDoubleArrowLine(g2, x, (int) yLLOffset, x + width, (int) yLLOffset); - g2.drawString(lug.getName(), x + (width / 3), (int) yLLOffset - 2); - - } - } - //Only if the tube has a lug or multiple finsets does the orientation of the marking guide matter. So print 'Front'. - if (hasMultipleComponents) { - drawFrontIndication(g2, x, y, (int) baseSpacing, (int) circumferenceInPoints, width); - } - - //At most, two marking guides horizontally. After that, move down and back to the left margin. - column++; - if (column % 2 == 0) { - x = MARGIN; - y += circumferenceInPoints + MARGIN; - } - else { - x += MARGIN + width; - } - } - } - } - - /** - * Compute the y offset for the next fin line. - * - * @param y the top margin - * @param circumferenceInPoints the circumference (height) of the guide - * @param baseSpacing the circumference / fin count - * @param baseYOrigin the offset from the top of the guide to the first fin of the first fin set drawn - * @param prevBaseRotation the rotation of the previous finset - * @param baseRotation the rotation of the current finset - * - * @return number of points from the top of the marking guide to the line to be drawn - */ - private int computeYOffset(int y, double circumferenceInPoints, double baseSpacing, double baseYOrigin, double prevBaseRotation, double baseRotation) { - int offset; - double finRadialDifference = (baseRotation - prevBaseRotation) / TWO_PI; - //If the fin line would be off the top of the marking guide, then readjust. - if (baseYOrigin + finRadialDifference * circumferenceInPoints < 0) { - offset = (int) (baseYOrigin + baseSpacing + finRadialDifference * circumferenceInPoints) + y; - } - else if (baseYOrigin - finRadialDifference * circumferenceInPoints > 0) { - offset = (int) (finRadialDifference * circumferenceInPoints + baseYOrigin) + y; - } - else { - offset = (int) (finRadialDifference * circumferenceInPoints - baseYOrigin) + y; - } - return offset; - } - - /** - * Determines if the list contains a FinSet. - * - * @param list a list of ExternalComponent - * - * @return true if the list contains at least one FinSet - */ - private boolean hasFins(List list) { - for (ExternalComponent externalComponent : list) { - if (externalComponent instanceof FinSet) { - return true; - } - } - return false; - } - - /** - * Sort a list of ExternalComponent in-place. Forces FinSets to precede Launch Lugs. - * - * @param componentList a list of ExternalComponent - */ - private void sort(List componentList) { - Collections.sort(componentList, new Comparator() { - @Override - public int compare(ExternalComponent o1, ExternalComponent o2) { - if (o1 instanceof FinSet) { - return -1; - } - if (o2 instanceof FinSet) { - return 1; - } - return 0; - } - }); - } - - /** - * Draw the marking guide outline. - * - * @param g2 the graphics context - * @param x the starting x coordinate - * @param y the starting y coordinate - * @param length the length, or height, in print units of the marking guide; should be equivalent to the outer tube - * circumference - * @param width the width of the marking guide in print units; somewhat arbitrary - */ - private void drawMarkingGuide(Graphics2D g2, int x, int y, int length, int width) { - Path2D outline = new Path2D.Float(GeneralPath.WIND_EVEN_ODD, 4); - outline.moveTo(x, y); - outline.lineTo(width + x, y); - outline.lineTo(width + x, length + y); - outline.lineTo(x, length + y); - outline.closePath(); - g2.draw(outline); - - //Draw tick marks for alignment, 1/4 of the width in from either edge - int fromEdge = (width) / 4; - final int tickLength = 8; - //Upper left - g2.drawLine(x + fromEdge, y, x + fromEdge, y + tickLength); - //Upper right - g2.drawLine(x + width - fromEdge, y, x + width - fromEdge, y + tickLength); - //Lower left - g2.drawLine(x + fromEdge, y + length - tickLength, x + fromEdge, y + length); - //Lower right - g2.drawLine(x + width - fromEdge, y + length - tickLength, x + width - fromEdge, y + length); - } - - /** - * Draw a vertical string indicating the front of the rocket. This is necessary when a launch lug exists to give - * proper orientation of the guide (assuming that the lug is asymmetrically positioned with respect to a fin). - * - * @param g2 the graphics context - * @param x the starting x coordinate - * @param y the starting y coordinate - * @param spacing the space between fin lines - * @param length the length, or height, in print units of the marking guide; should be equivalent to the outer tube - * circumference - * @param width the width of the marking guide in print units; somewhat arbitrary - */ - private void drawFrontIndication(Graphics2D g2, int x, int y, int spacing, int length, int width) { - //The magic numbers here are fairly arbitrary. They're chosen in a manner that best positions 'Front' to be - //readable, without going to complex string layout prediction logic. - int rotateX = x + width - 16; - int rotateY = y + (int) (spacing * 1.5) + 20; - if (rotateY > y + length + 14) { - rotateY = y + length / 2 - 10; - } - g2.translate(rotateX, rotateY); - g2.rotate(Math.PI / 2); - g2.drawString(trans.get("FinMarkingGuide.lbl.Front"), 0, 0); - g2.rotate(-Math.PI / 2); - g2.translate(-rotateX, -rotateY); - } - - /** - * Draw a horizontal line with arrows on both endpoints. Depicts a fin alignment. - * - * @param g2 the graphics context - * @param x1 the starting x coordinate - * @param y1 the starting y coordinate - * @param x2 the ending x coordinate - * @param y2 the ending y coordinate - */ - void drawDoubleArrowLine(Graphics2D g2, int x1, int y1, int x2, int y2) { - int len = x2 - x1; - - g2.drawLine(x1, y1, x1 + len, y2); - g2.fillPolygon(new int[]{x1 + len, x1 + len - ARROW_SIZE, x1 + len - ARROW_SIZE, x1 + len}, - new int[]{y2, y2 - ARROW_SIZE / 2, y2 + ARROW_SIZE / 2, y2}, 4); - - g2.fillPolygon(new int[]{x1, x1 + ARROW_SIZE, x1 + ARROW_SIZE, x1}, - new int[]{y1, y1 - ARROW_SIZE / 2, y1 + ARROW_SIZE / 2, y1}, 4); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/ITextHelper.java b/core/src/net/sf/openrocket/gui/print/ITextHelper.java deleted file mode 100644 index 45650543..00000000 --- a/core/src/net/sf/openrocket/gui/print/ITextHelper.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * ITextHelper.java - */ -package net.sf.openrocket.gui.print; - -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; - -import com.itextpdf.text.Chunk; -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Font; -import com.itextpdf.text.Paragraph; -import com.itextpdf.text.Phrase; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.BaseFont; -import com.itextpdf.text.pdf.PdfContentByte; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; - -/** - * A bunch of helper methods for creating iText components. - */ -public final class ITextHelper { - - public static BaseFont getBaseFont(){ - try { - return BaseFont.createFont("/dejavu-font/DejaVuSerif.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); - } catch (Exception ex ) { - throw new RuntimeException(ex); - } - } - /** - * Create a cell for an iText table. - * - * @return a cell with bottom border - */ - public static PdfPCell createCell () { - return createCell(Rectangle.BOTTOM); - } - - /** - * Create a cell for an iText table with the given border location. - * - * @param border the border location - * - * @return a cell with given border - */ - public static PdfPCell createCell (int border) { - PdfPCell result = new PdfPCell(); - result.setBorder(border); - - return result; - } - - /** - * Create a cell whose contents are a table. No border. - * - * @param table the table to insert into the cell - * - * @return the cell containing a table - */ - public static PdfPCell createCell (PdfPTable table) { - PdfPCell result = new PdfPCell(); - result.setBorder(PdfPCell.NO_BORDER); - result.addElement(table); - - return result; - } - - /** - * Create a cell whose contents are the given string. No border. Standard PrintUtilities.NORMAL font. - * - * @param v the text of the cell. - * - * @return the cell containing the text - */ - public static PdfPCell createCell (String v) { - return createCell(v, Rectangle.NO_BORDER, PrintUtilities.NORMAL); - } - - /** - * Create a cell whose contents are the given string , rendered with the given font. No border. - * - * @param v the text of the cell - * @param font the font - * - * @return the cell containing the text - */ - public static PdfPCell createCell (String v, Font font) { - return createCell(v, Rectangle.NO_BORDER, font); - } - - /** - * Create a cell whose contents are the given string with specified left and right padding (spacing). - * - * @param v the text of the cell - * @param leftPad the number of points to precede the text - * @param rightPad the number of points to follow the text - * - * @return the cell containing the text - */ - public static PdfPCell createCell (String v, int leftPad, int rightPad) { - PdfPCell c = createCell(v, Rectangle.NO_BORDER, PrintUtilities.NORMAL); - c.setPaddingLeft(leftPad); - c.setPaddingRight(rightPad); - return c; - } - - /** - * Create a cell whose contents are the given string with the given border. Uses NORMAL font. - * - * @param v the text of the cell - * @param border the border type - * - * @return the cell containing the text - */ - public static PdfPCell createCell (String v, int border) { - return createCell(v, border, PrintUtilities.NORMAL); - } - - /** - * Complete create cell - fully qualified. Create a cell whose contents are the given string with the given border - * and font. - * - * @param v the text of the cell - * @param border the border type - * @param font the font - * - * @return the cell containing the text - */ - public static PdfPCell createCell (String v, int border, Font font) { - PdfPCell result = new PdfPCell(); - result.setBorder(border); - Chunk c = new Chunk(); - c.setFont(font); - c.append(v); - result.addElement(c); - return result; - } - - /** - * Create a phrase with the given text and font. - * - * @param text the text - * @param font the font - * - * @return an iText phrase - */ - public static Phrase createPhrase (String text, Font font) { - Phrase p = new Phrase(); - final Chunk chunk = new Chunk(text); - chunk.setFont(font); - p.add(chunk); - return p; - } - - /** - * Create a phrase with the given text. - * - * @param text the text - * - * @return an iText phrase - */ - public static Phrase createPhrase (String text) { - return createPhrase(text, PrintUtilities.NORMAL); - } - - /** - * Create a paragraph with the given text and font. - * - * @param text the text - * @param font the font - * - * @return an iText paragraph - */ - public static Paragraph createParagraph (String text, Font font) { - Paragraph p = new Paragraph(); - final Chunk chunk = new Chunk(text); - chunk.setFont(font); - p.add(chunk); - return p; - } - - /** - * Create a paragraph with the given text and using NORMAL font. - * - * @param text the text - * - * @return an iText paragraph - */ - public static Paragraph createParagraph (String text) { - return createParagraph(text, PrintUtilities.NORMAL); - } - - /** - * Break a large image up into page-size pieces and output each page in order to an iText document. The image is - * overlayed with an matrix of pages running from left to right until the right side of the image is reached. Then - * the next 'row' of pages is output from left to right, and so on. - * - * @param pageSize a rectangle that defines the bounds of the page size - * @param doc the iText document - * @param writer the underlying content writer - * @param image the source image - * - * @throws DocumentException thrown if the document could not be written - */ - public static void renderImageAcrossPages (Rectangle pageSize, Document doc, PdfWriter writer, java.awt.Image image) - throws DocumentException { - final int margin = (int)Math.min(doc.topMargin(), PrintUnit.POINTS_PER_INCH * 0.3f); - float wPage = pageSize.getWidth() - 2 * margin; - float hPage = pageSize.getHeight() - 2 * margin; - - float wImage = image.getWidth(null); - float hImage = image.getHeight(null); - java.awt.Rectangle crop = new java.awt.Rectangle(0, 0, (int) Math.min(wPage, wImage), (int) Math.min(hPage, - hImage)); - PdfContentByte content = writer.getDirectContent(); - - int ymargin = 0; - - while (true) { - BufferedImage subImage = ((BufferedImage) image).getSubimage((int) crop.getX(), (int) crop.getY(), - (int) crop.getWidth(), (int) crop.getHeight()); - - Graphics2D g2 = content.createGraphics(pageSize.getWidth(), pageSize.getHeight()); - g2.drawImage(subImage, margin, ymargin, null); - g2.dispose(); - - // After the first page, the y-margin needs to be set. - ymargin = margin; - - final int newX = (int) (crop.getWidth() + crop.getX()); - if (newX < wImage) { - double adjust = Math.min(wImage - newX, wPage); - crop = new java.awt.Rectangle(newX, (int) crop.getY(), (int) adjust, - (int) crop.getHeight()); - } - else { - final int newY = (int) (crop.getHeight() + crop.getY()); - if (newY < hImage) { - double adjust = Math.min(hImage - newY, hPage); - crop = new java.awt.Rectangle(0, newY, (int) Math.min(wPage, wImage), (int) adjust); - } - else { - break; - } - } - doc.newPage(); - } - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java b/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java deleted file mode 100644 index 5bfd924c..00000000 --- a/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * OpenRocketPrintable.java - */ -package net.sf.openrocket.gui.print; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; - -/** - * This enumeration identifies the various types of information that may be printed. - */ - -public enum OpenRocketPrintable { - // Design Report - DESIGN_REPORT("OpenRocketPrintable.DesignReport", false, 1), - // Parts detail - PARTS_DETAIL("OpenRocketPrintable.Partsdetail", true, 2), - // Nose Cone Templates - NOSE_CONE_TEMPLATE("OpenRocketPrintable.Noseconetemplates", false, 3), - // Transition Templates - TRANSITION_TEMPLATE("OpenRocketPrintable.Transitiontemplates", false, 4), - // Centering Ring Templates - CENTERING_RING_TEMPLATE("OpenRocketPrintable.Centeringringtemplates", false, 5), - // Finset shape - FIN_TEMPLATE("OpenRocketPrintable.Fintemplates", true, 6), - // Fin marking guide. - FIN_MARKING_GUIDE("OpenRocketPrintable.Finmarkingguide", false, 7); - - - private static final Translator trans = Application.getTranslator(); - - /** - * The description - will be displayed in the JTree. - */ - private String description; - - /** - * Flag that indicates if the enum value is different depending upon stage. - */ - private boolean stageSpecific; - - /** - * The order of the item as it appears in the printed document. - */ - private int order; - - /** - * Constructor. - * - * @param s the displayable description - * @param staged indicates if the printable is stage dependent - * @param idx the relative print order - */ - OpenRocketPrintable(String s, boolean staged, int idx) { - description = s; - stageSpecific = staged; - order = idx; - } - - /** - * Get the description of this printable. - * - * @return a displayable string - */ - public String getDescription() { - return trans.get(description); - } - - /** - * Answers if this enum value has different meaning depending upon the stage. - * - * @return true if the printable is stage dependent - */ - public boolean isStageSpecific() { - return stageSpecific; - } - - /** - * Answer the print order. This is relative to other enum values. No two enum values will have the same print - * order value. - * - * @return a 0 based order (0 being first, or highest) - */ - public int getPrintOrder() { - return order; - } - - /** - * Look up an enum value based on the description. - * - * @param target the description - * - * @return an instance of this enum class or null if not found - */ - public static OpenRocketPrintable findByDescription(String target) { - OpenRocketPrintable[] values = values(); - for (OpenRocketPrintable value : values) { - if (value.getDescription().equalsIgnoreCase(target)) { - return value; - } - } - return null; - } - - /** - * Get a list of ordered enum values that do not have stage affinity. - * - * @return a list of OpenRocketPrintable - */ - public static List getUnstaged() { - List unstaged = new ArrayList(); - OpenRocketPrintable[] values = values(); - for (OpenRocketPrintable value : values) { - if (!value.isStageSpecific()) { - unstaged.add(value); - } - } - return unstaged; - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PDFPrintStreamDoc.java b/core/src/net/sf/openrocket/gui/print/PDFPrintStreamDoc.java deleted file mode 100644 index 90cf4610..00000000 --- a/core/src/net/sf/openrocket/gui/print/PDFPrintStreamDoc.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * PDFPrintStreamDoc.java - */ -package net.sf.openrocket.gui.print; - -import javax.print.Doc; -import javax.print.DocFlavor; -import javax.print.attribute.AttributeSetUtilities; -import javax.print.attribute.DocAttributeSet; -import java.io.*; - -/** - * This class implements a javax Doc specifically for PDF printing. All reports in OpenRocket are PDF (iText) based. - */ -public class PDFPrintStreamDoc implements Doc { - - /** The source stream of the PDF document. */ - private InputStream stream; - - /** The document's attributes. */ - private DocAttributeSet attributeSet; - - /** - * Constructor. - * - * @param ostream an output stream representing the pdf doc - * @param attributes the attributes of the document - */ - public PDFPrintStreamDoc (ByteArrayOutputStream ostream, DocAttributeSet attributes) { - stream = new ByteArrayInputStream(ostream.toByteArray()); - if (attributes != null) { - attributeSet = AttributeSetUtilities.unmodifiableView(attributes); - } - } - - /** - * Flavor is PDF. - * - * @return PDF flavor - */ - @Override - public DocFlavor getDocFlavor () { - return DocFlavor.INPUT_STREAM.PDF; - } - - @Override - public DocAttributeSet getAttributes () { - return attributeSet; - } - - /* Since the data is to be supplied as an InputStream delegate to - * getStreamForBytes(). - */ - @Override - public Object getPrintData () throws IOException { - return getStreamForBytes(); - } - - /** - * Intentionally null since the flavor is PDF. - * - * @return null - */ - @Override - public Reader getReaderForText () { - return null; - } - - /* Return the print data as an InputStream. - * Always return the same instance. - */ - @Override - public InputStream getStreamForBytes () throws IOException { - return stream; - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PaperOrientation.java b/core/src/net/sf/openrocket/gui/print/PaperOrientation.java deleted file mode 100644 index 0e973e0f..00000000 --- a/core/src/net/sf/openrocket/gui/print/PaperOrientation.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.gui.print; - -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.RectangleReadOnly; - -public enum PaperOrientation { - - PORTRAIT("Portrait") { - @Override - public Rectangle orient(Rectangle rect) { - return new RectangleReadOnly(rect); - } - }, - LANDSCAPE("Landscape") { - @Override - public Rectangle orient(Rectangle rect) { - return new RectangleReadOnly(new Rectangle(rect).rotate()); - } - }; - - - private final String name; - - private PaperOrientation(String name) { - this.name = name; - } - - /** - * Change the orientation of a portrait paper to the orientation represented by this - * orientation. - * - * @param rect the original paper size rectangle - * @return the oriented paper size rectangle - */ - public abstract Rectangle orient(Rectangle rect); - - - @Override - public String toString() { - return name; - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PaperSize.java b/core/src/net/sf/openrocket/gui/print/PaperSize.java deleted file mode 100644 index 1908fa28..00000000 --- a/core/src/net/sf/openrocket/gui/print/PaperSize.java +++ /dev/null @@ -1,193 +0,0 @@ -package net.sf.openrocket.gui.print; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.Locale; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -import com.itextpdf.text.PageSize; -import com.itextpdf.text.Rectangle; - -public enum PaperSize { - A3("A3", PageSize.A3), - A4("A4", PageSize.A4), - A5("A5", PageSize.A5), - LETTER("Letter", PageSize.LETTER), - LEGAL("Legal", PageSize.LEGAL); - - private final String name; - private final Rectangle size; - - private PaperSize(String name, Rectangle size) { - this.name = name; - this.size = size; - } - - public Rectangle getSize() { - return size; - } - - @Override - public String toString() { - return name; - } - - - - ////////////////////////// - - private static final LogHelper log = Application.getLogger(); - private static PaperSize defaultSize = null; - - /** - * Return the default paper size for the current system. - * @return the default paper size - */ - public static PaperSize getDefault() { - if (defaultSize == null) { - - // Test environment variable "PAPERSIZE" (Unix) - defaultSize = getDefaultFromEnvironmentVariable(); - if (defaultSize != null) { - log.info("Selecting default paper size from PAPERSIZE environment variable: " + defaultSize); - return defaultSize; - } - - // Test /etc/papersize (Unix) - defaultSize = getDefaultFromEtcPapersize(); - if (defaultSize != null) { - log.info("Selecting default paper size from /etc/papersize: " + defaultSize); - return defaultSize; - } - - // Test user.country - defaultSize = getDefaultForCountry(System.getProperty("user.country")); - if (defaultSize != null) { - log.info("Selecting default paper size based on user.country: " + defaultSize); - return defaultSize; - } - - // Test locale country - defaultSize = getDefaultForCountry(Locale.getDefault().getCountry()); - if (defaultSize != null) { - log.info("Selecting default paper size based on locale country: " + defaultSize); - return defaultSize; - } - - // Fallback to A4 - defaultSize = A4; - log.info("Selecting default paper size fallback: " + defaultSize); - } - - return defaultSize; - } - - - /** - * Attempt to read the default paper size from the "PAPERSIZE" environment variable. - * - * @return the default paper size if successful, or null if unable to read/parse file. - */ - private static PaperSize getDefaultFromEnvironmentVariable() { - String str = System.getenv("PAPERSIZE"); - return getSizeFromString(str); - } - - /** - * Attempt to read the default paper size from the file defined by the environment variable - * PAPERCONF or from /etc/papersize. - * - * @return the default paper size if successful, or null if unable to read/parse file. - */ - private static PaperSize getDefaultFromEtcPapersize() { - - // Find file to read - String file = System.getenv("PAPERCONF"); - if (file == null) { - file = "/etc/papersize"; - } - - // Attempt to read the file - BufferedReader in = null; - try { - - String str; - in = new BufferedReader(new FileReader(file)); - while ((str = in.readLine()) != null) { - if (str.matches("^\\s*(#.*|$)")) { - continue; - } - break; - } - - return getSizeFromString(str); - - } catch (IOException e) { - - // Could not read file - return null; - - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - } - } - } - } - - - /** - * Get a paper size based on a string. The string is trimmed and case-insensitively - * compared to the base names of the paper sizes. - * - * @param size the size string (may be null) - * @return the corresponding paper size, or null if unknown - */ - static PaperSize getSizeFromString(String size) { - if (size == null) { - return null; - } - - size = size.trim(); - for (PaperSize p : PaperSize.values()) { - if (p.name.equalsIgnoreCase(size)) { - return p; - } - } - return null; - } - - - /** - * Get default paper size for a specific country. This method falls back to A4 for - * any country not known to use Letter. - * - * @param country the 2-char country code (may be null) - * @return the paper size, or null if country is not a country code - */ - static PaperSize getDefaultForCountry(String country) { - /* - * List is based on info from http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/territory_language_information.html - * OpenOffice.org agrees with this: http://wiki.services.openoffice.org/wiki/DefaultPaperSize#Summary - */ - final String[] letterCountries = { "BZ", "CA", "CL", "CO", "CR", "SV", "GT", "MX", "NI", "PA", "PH", "PR", "US", "VE" }; - - if (country == null || !country.matches("^[a-zA-Z][a-zA-Z]$")) { - return null; - } - - country = country.toUpperCase(Locale.ENGLISH); - for (String c : letterCountries) { - if (c.equals(country)) { - return LETTER; - } - } - return A4; - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintController.java b/core/src/net/sf/openrocket/gui/print/PrintController.java deleted file mode 100644 index 2e62df2a..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintController.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * PrintController.java - * - */ -package net.sf.openrocket.gui.print; - -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.ExceptionConverter; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.PdfBoolean; -import com.itextpdf.text.pdf.PdfName; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.gui.print.components.Rule; -import net.sf.openrocket.gui.print.visitor.CenteringRingStrategy; -import net.sf.openrocket.gui.print.visitor.FinMarkingGuideStrategy; -import net.sf.openrocket.gui.print.visitor.FinSetPrintStrategy; -import net.sf.openrocket.gui.print.visitor.PageFitPrintStrategy; -import net.sf.openrocket.gui.print.visitor.PartsDetailVisitorStrategy; -import net.sf.openrocket.gui.print.visitor.TransitionStrategy; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Iterator; -import java.util.Set; - -/** - * This is the main active object for printing. It performs all actions necessary to create and populate the print - * file. - */ -public class PrintController { - - /** - * Print the selected components to a PDF document. - * - * @param doc the OR document - * @param toBePrinted the user chosen items to print - * @param outputFile the file being written to - * @param settings the print settings - * @param rotation the angle the rocket figure is rotated - */ - public void print(OpenRocketDocument doc, Iterator toBePrinted, OutputStream outputFile, - PrintSettings settings, double rotation) { - - Document idoc = new Document(getSize(settings)); - PdfWriter writer = null; - try { - writer = PdfWriter.getInstance(idoc, outputFile); - writer.setStrictImageSequence(true); - - writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); - writer.addViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfBoolean.PDFTRUE); - try { - idoc.open(); - Thread.sleep(1000); - } - catch (InterruptedException e) { - } - - // Used to combine multiple components onto fewer sheets of paper - PageFitPrintStrategy pageFitPrint = new PageFitPrintStrategy(idoc, writer); - - boolean addRule = false; - - while (toBePrinted.hasNext()) { - PrintableContext printableContext = toBePrinted.next(); - - Set stages = printableContext.getStageNumber(); - - switch (printableContext.getPrintable()) { - case DESIGN_REPORT: - DesignReport dp = new DesignReport(doc, idoc, rotation); - dp.writeToDocument(writer); - idoc.newPage(); - break; - - case FIN_TEMPLATE: - final FinSetPrintStrategy finWriter = new FinSetPrintStrategy(idoc, writer, stages, pageFitPrint); - finWriter.writeToDocument(doc.getRocket()); - addRule = true; - break; - - case PARTS_DETAIL: - final PartsDetailVisitorStrategy detailVisitor = new PartsDetailVisitorStrategy(idoc, writer, stages); - detailVisitor.writeToDocument(doc.getRocket()); - detailVisitor.close(); - idoc.newPage(); - break; - - case TRANSITION_TEMPLATE: - final TransitionStrategy tranWriter = new TransitionStrategy(idoc, writer, stages, pageFitPrint); - if (tranWriter.writeToDocument(doc.getRocket(), false)) { - addRule = true; - } - break; - - case NOSE_CONE_TEMPLATE: - final TransitionStrategy coneWriter = new TransitionStrategy(idoc, writer, stages, pageFitPrint); - if (coneWriter.writeToDocument(doc.getRocket(), true)) { - addRule = true; - } - break; - - case CENTERING_RING_TEMPLATE: - final CenteringRingStrategy crWriter = new CenteringRingStrategy(idoc, writer, stages, - pageFitPrint); - crWriter.writeToDocument(doc.getRocket()); - addRule = true; - break; - - case FIN_MARKING_GUIDE: - final FinMarkingGuideStrategy fmg = new FinMarkingGuideStrategy(idoc, writer); - fmg.writeToDocument(doc.getRocket()); - idoc.newPage(); - addRule = true; - break; - } - } - - if (addRule) { - //Add a ruler to the output. - pageFitPrint.addComponent(new Rule(Rule.Orientation.BOTTOM)); - } - - // Write out parts that we are going to combine onto single sheets of paper - pageFitPrint.writeToDocument(doc.getRocket()); - idoc.newPage(); - - //Stupid iText throws a really nasty exception if there is no data when close is called. - if (writer.getCurrentDocumentSize() <= 140) { - writer.setPageEmpty(false); - } - writer.close(); - idoc.close(); - } - catch (DocumentException e) { - } - catch (ExceptionConverter ec) { - } - finally { - if (outputFile != null) { - try { - outputFile.close(); - } - catch (IOException e) { - } - } - } - } - - /** - * Get the correct paper size from the print settings. - * - * @param settings the print settings - * - * @return the paper size - */ - private Rectangle getSize(PrintSettings settings) { - PaperSize size = settings.getPaperSize(); - PaperOrientation orientation = settings.getPaperOrientation(); - return orientation.orient(size.getSize()); - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintFigure.java b/core/src/net/sf/openrocket/gui/print/PrintFigure.java deleted file mode 100644 index 648e7231..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintFigure.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * PrintFigure.java - */ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.gui.scalefigure.RocketFigure; -import net.sf.openrocket.rocketcomponent.Configuration; - -/** - * A figure used to override the scale factor in RocketFigure. This allows pinpoint scaling to allow a diagram - * to fit in the width of the chosen page size. - */ -public class PrintFigure extends RocketFigure { - - /** - * Constructor. - * - * @param configuration the configuration - */ - public PrintFigure(final Configuration configuration) { - super(configuration); - } - - @Override - protected double computeTy(int heightPx) { - super.computeTy(heightPx); - return 0; - } - - public void setScale(final double theScale) { - this.scale = theScale; //dpi/0.0254*scaling; - updateFigure(); - } - - public double getFigureHeightPx() { - return this.figureHeightPx; - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintSettings.java b/core/src/net/sf/openrocket/gui/print/PrintSettings.java deleted file mode 100644 index 6537f400..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintSettings.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.gui.print; - -import java.awt.Color; - -import net.sf.openrocket.util.AbstractChangeSource; - -/** - * A class containing all printing settings. - */ -public class PrintSettings extends AbstractChangeSource { - - private Color templateFillColor = Color.LIGHT_GRAY; - private Color templateBorderColor = Color.DARK_GRAY; - - private PaperSize paperSize = PaperSize.getDefault(); - private PaperOrientation paperOrientation = PaperOrientation.PORTRAIT; - - - public Color getTemplateFillColor() { - return templateFillColor; - } - - public void setTemplateFillColor(Color templateFillColor) { - // Implicitly tests against setting null - if (templateFillColor.equals(this.templateFillColor)) { - return; - } - this.templateFillColor = templateFillColor; - fireChangeEvent(); - } - - public Color getTemplateBorderColor() { - return templateBorderColor; - } - - public void setTemplateBorderColor(Color templateBorderColor) { - // Implicitly tests against setting null - if (templateBorderColor.equals(this.templateBorderColor)) { - return; - } - this.templateBorderColor = templateBorderColor; - fireChangeEvent(); - } - - public PaperSize getPaperSize() { - return paperSize; - } - - public void setPaperSize(PaperSize paperSize) { - if (paperSize.equals(this.paperSize)) { - return; - } - this.paperSize = paperSize; - fireChangeEvent(); - } - - public PaperOrientation getPaperOrientation() { - return paperOrientation; - } - - public void setPaperOrientation(PaperOrientation orientation) { - if (orientation.equals(paperOrientation)) { - return; - } - this.paperOrientation = orientation; - fireChangeEvent(); - } - - - - /** - * Load settings from the specified print settings. - * @param settings the settings to load - */ - public void loadFrom(PrintSettings settings) { - this.templateFillColor = settings.templateFillColor; - this.templateBorderColor = settings.templateBorderColor; - this.paperSize = settings.paperSize; - this.paperOrientation = settings.paperOrientation; - fireChangeEvent(); - } - - - @Override - public String toString() { - return "PrintSettings [templateFillColor=" + templateFillColor + ", templateBorderColor=" + templateBorderColor + ", paperSize=" + paperSize + ", paperOrientation=" + paperOrientation + "]"; - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintSimulationWorker.java b/core/src/net/sf/openrocket/gui/print/PrintSimulationWorker.java deleted file mode 100644 index 53a710c8..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintSimulationWorker.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * PrintSimulationWorker.java - */ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.main.SimulationWorker; -import net.sf.openrocket.simulation.FlightData; - -/** - * A SimulationWorker that simulates the rocket flight in the background and sets the results to the extra text when - * finished. The worker can be cancelled if necessary. - */ -public class PrintSimulationWorker { - - public static FlightData doit(Simulation sim) { - return new InnerPrintSimulationWorker(sim).doit(); - } - - static class InnerPrintSimulationWorker extends SimulationWorker { - - public InnerPrintSimulationWorker(Simulation sim) { - super(sim); - } - - public FlightData doit() { - return doInBackground(); - } - - @Override - protected void simulationDone() { - // Do nothing if cancelled - if (isCancelled()) { - return; - } - - simulation.getSimulatedData(); - } - - - /** - * Called if the simulation is interrupted due to an exception. - * - * @param t the Throwable that caused the interruption - */ - @Override - protected void simulationInterrupted(final Throwable t) { - } - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/PrintUnit.java b/core/src/net/sf/openrocket/gui/print/PrintUnit.java deleted file mode 100644 index 734e433b..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintUnit.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * PrintUnit.java - */ -package net.sf.openrocket.gui.print; - -/** - * Utilities for print units. - */ -public enum PrintUnit { - FOOT { - public double toInches(double d) { return d*12; } - public double toMillis(double d) { return d/FEET_PER_MM; } - public double toCentis(double d) { return d/(FEET_PER_MM*TEN); } - public double toMeters(double d) { return d/(FEET_PER_MM*TEN*TEN*TEN); } - public double toPoints(double d) { return (d * POINTS_PER_INCH * 12); } - public double convert(double d, PrintUnit u) { return u.toInches(d)/12; } - }, - INCHES { - public double toInches(double d) { return d; } - public double toMillis(double d) { return d/INCHES_PER_MM; } - public double toCentis(double d) { return d/(INCHES_PER_MM*TEN); } - public double toMeters(double d) { return d/(INCHES_PER_MM*TEN*TEN*TEN); } - public double toPoints(double d) { return (d * POINTS_PER_INCH); } - public double convert(double d, PrintUnit u) { return u.toInches(d); } - }, - MILLIMETERS { - public double toInches(double d) { return d * INCHES_PER_MM; } - public double toMillis(double d) { return d; } - public double toCentis(double d) { return d/TEN; } - public double toMeters(double d) { return d/(TEN*TEN*TEN); } - public double toPoints(double d) { return INCHES.toPoints(toInches(d)); } - public double convert(double d, PrintUnit u) { return u.toMillis(d); } - }, - CENTIMETERS { - public double toInches(double d) { return d * INCHES_PER_MM * TEN; } - public double toMillis(double d) { return d * TEN; } - public double toCentis(double d) { return d; } - public double toMeters(double d) { return d/(TEN*TEN); } - public double toPoints(double d) { return INCHES.toPoints(toInches(d)); } - public double convert(double d, PrintUnit u) { return u.toCentis(d); } - }, - METERS { - public double toInches(double d) { return d * INCHES_PER_MM * TEN * TEN * TEN; } - public double toMillis(double d) { return d * TEN * TEN * TEN; } - public double toCentis(double d) { return d * TEN * TEN; } - public double toMeters(double d) { return d; } - public double toPoints(double d) { return INCHES.toPoints(toInches(d)); } - public double convert(double d, PrintUnit u) { return u.toMeters(d); } - }, - POINTS { - public double toInches(double d) { return d/POINTS_PER_INCH; } - public double toMillis(double d) { return d/(POINTS_PER_INCH * INCHES_PER_MM); } - public double toCentis(double d) { return toMillis(d)/TEN; } - public double toMeters(double d) { return toMillis(d)/(TEN*TEN*TEN); } - public double toPoints(double d) { return d; } - public double convert(double d, PrintUnit u) { return u.toPoints(d); } - }; - - // Handy constants for conversion methods - public static final double INCHES_PER_MM = 0.0393700787d; - public static final double FEET_PER_MM = INCHES_PER_MM /12; - public static final double MM_PER_INCH = 1.0d/INCHES_PER_MM; - public static final long TEN = 10; - /** - * PPI is Postscript Point and is a standard of 72. Java2D also uses this internally as a pixel-per-inch, so pixels - * and points are for the most part interchangeable (unless the defaults are changed), which makes translating - * between the screen and a print job easier. - * - * Not to be confused with Dots-Per-Inch, which is printer and print mode dependent. - */ - public static final int POINTS_PER_INCH = 72; - - // To maintain full signature compatibility with 1.5, and to improve the - // clarity of the generated javadoc (see 6287639: Abstract methods in - // enum classes should not be listed as abstract), method convert - // etc. are not declared abstract but otherwise act as abstract methods. - - /** - * Convert the given length in the given unit to this - * unit. Conversions from finer to coarser granularities - * truncate, so may lose precision. - * - *

For example, to convert 10 inches to point, use: - * PrintUnit.POINTS.convert(10L, PrintUnit.INCHES) - * - * @param sourceLength the length in the given sourceUnit - * @param sourceUnit the unit of the sourceDuration argument - * - * @return the converted length in this unit, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - */ - public double convert(double sourceLength, PrintUnit sourceUnit) { - throw new AbstractMethodError(); - } - - /** - * Equivalent to INCHES.convert(length, this). - * - * @param length the length - * - * @return the converted length, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert - */ - public double toInches(double length) { - throw new AbstractMethodError(); - } - - /** - * Equivalent to MILLIMETERS.convert(length, this). - * - * @param length the length - * - * @return the converted length, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert - */ - public double toMillis(double length) { - throw new AbstractMethodError(); - } - - /** - * Equivalent to CENTIMETERS.convert(length, this). - * - * @param length the length - * - * @return the converted length, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert - */ - public double toCentis(double length) { - throw new AbstractMethodError(); - } - - /** - * Equivalent to METERS.convert(length, this). - * - * @param length the length - * - * @return the converted length, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert - */ - public double toMeters(double length) { - throw new AbstractMethodError(); - } - - /** - * Equivalent to POINTS.convert(length, this). - * - * @param length the length - * - * @return the converted length, - * or Long.MIN_VALUE if conversion would negatively - * overflow, or Long.MAX_VALUE if it would positively overflow. - * @see #convert - */ - public double toPoints(double length) { - throw new AbstractMethodError(); - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/PrintUtilities.java b/core/src/net/sf/openrocket/gui/print/PrintUtilities.java deleted file mode 100644 index 3e8af143..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintUtilities.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * PrintUtilities.java - */ -package net.sf.openrocket.gui.print; - - -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.print.PageFormat; -import java.awt.print.Printable; - -import javax.swing.RepaintManager; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -import com.itextpdf.text.Chunk; -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Font; -import com.itextpdf.text.Paragraph; - -/** - * Utilities methods and fonts used for printing. - */ -public class PrintUtilities implements Printable { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - public static final int NORMAL_FONT_SIZE = Font.DEFAULTSIZE - 3; - public static final int SMALL_FONT_SIZE = NORMAL_FONT_SIZE - 3; - - public static final Font BOLD = new Font(ITextHelper.getBaseFont(), NORMAL_FONT_SIZE, Font.BOLD); - public static final Font BIG_BOLD = new Font(ITextHelper.getBaseFont(), NORMAL_FONT_SIZE + 3, Font.BOLD); - public static final Font BOLD_UNDERLINED = new Font(ITextHelper.getBaseFont(), NORMAL_FONT_SIZE, - Font.BOLD | Font.UNDERLINE); - public static final Font NORMAL = new Font(ITextHelper.getBaseFont(), NORMAL_FONT_SIZE); - public static final Font SMALL = new Font(ITextHelper.getBaseFont(), SMALL_FONT_SIZE); - - - private Component componentToBePrinted; - - public PrintUtilities(Component componentToBePrinted) { - this.componentToBePrinted = componentToBePrinted; - } - - @Override - public int print(Graphics g, PageFormat pageFormat, int pageIndex) { - if (pageIndex > 0) { - return (NO_SUCH_PAGE); - } else { - Graphics2D g2d = (Graphics2D) g; - translateToJavaOrigin(g2d, pageFormat); - disableDoubleBuffering(componentToBePrinted); - componentToBePrinted.paint(g2d); - enableDoubleBuffering(componentToBePrinted); - return (PAGE_EXISTS); - } - } - - public static void disableDoubleBuffering(Component c) { - RepaintManager currentManager = RepaintManager.currentManager(c); - currentManager.setDoubleBufferingEnabled(false); - } - - public static void enableDoubleBuffering(Component c) { - RepaintManager currentManager = RepaintManager.currentManager(c); - currentManager.setDoubleBufferingEnabled(true); - } - - - /** - * Translate the page format coordinates onto the graphics object using Java's origin (top left). - * - * @param g2d the graphics object - * @param pageFormat the print page format - */ - public static void translateToJavaOrigin(Graphics2D g2d, PageFormat pageFormat) { - g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); - } - - /** - * Add text as a new paragraph in a given font to the document. - * - * @param document the document - * @param font the font - * @param title the title - */ - public static void addText(Document document, com.itextpdf.text.Font font, String title) { - Chunk sectionHeader = new Chunk(title); - sectionHeader.setFont(font); - try { - Paragraph p = new Paragraph(); - p.add(sectionHeader); - document.add(p); - } catch (DocumentException e) { - log.error("Could not add paragraph.", e); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintableCenteringRing.java b/core/src/net/sf/openrocket/gui/print/PrintableCenteringRing.java deleted file mode 100644 index 00c4e89c..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintableCenteringRing.java +++ /dev/null @@ -1,196 +0,0 @@ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.gui.print.visitor.CenteringRingStrategy; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.ClusterConfiguration; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.Coordinate; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * This class creates a renderable centering ring. It depends only on AWT/Swing and can be called from other actors - * (like iText handlers) to render the centering ring on different graphics contexts. - */ -public class PrintableCenteringRing extends AbstractPrintable { - /** - * If the component to be drawn is a centering ring, save a reference to it. - */ - private CenteringRing target; - - /** - * The line length of the cross hairs. - */ - private final int lineLength = 10; - - /** - * A set of the inner 'holes'. At least one, but will have many if clustered. - */ - private Set innerCenterPoints = new HashSet(); - - /** - * Construct a simple, non-clustered, printable centering ring, or if the motor mount represents a clustered - * configuration then get the cluster points to create the centering ring. - * - * @param theRing the component to print - * @param theMotorMount the motor mount if clustered, else null - */ - private PrintableCenteringRing(CenteringRing theRing, InnerTube theMotorMount) { - super(false, theRing); - if (theMotorMount == null || theMotorMount.getClusterConfiguration().equals(ClusterConfiguration.SINGLE)) { - //Single motor. - final float v = (float) PrintUnit.METERS.toPoints(target.getOuterRadius()); - innerCenterPoints.add( - new CenteringRingStrategy.Dimension(v, v, - (float) PrintUnit.METERS.toPoints((target.getInnerRadius())))); - } - else { - List coords = theMotorMount.getClusterPoints(); - List points = new ArrayList(); - for (Coordinate coordinate : coords) { - points.add(coordinate.setX(theMotorMount.getOuterRadius())); - } - populateCenterPoints(points); - } - } - - /** - * Constructor for a clustered centering ring. This version is for a "split cluster", where each motor mount tube - * is a distinct entity. - * - * @param theRing the centering ring component - * @param theMotorMounts a list of the motor mount tubes that are physically supported by the centering ring - */ - private PrintableCenteringRing(CenteringRing theRing, List theMotorMounts) { - super(false, theRing); - List points = new ArrayList(); - //Transform the radial positions of the tubes. - for (InnerTube it : theMotorMounts) { - if (it.getClusterCount() > 1) { - List c = it.getClusterPoints(); - for (Coordinate coordinate : c) { - points.add(coordinate.setX(it.getOuterRadius())); - } - } - else { - double y = it.getRadialShiftY(); - double z = it.getRadialShiftZ(); - Coordinate coordinate = new Coordinate(it.getOuterRadius(), y, z); - points.add(coordinate); - } - } - populateCenterPoints(points); - } - - /** - * Factory method to create a printable centering ring. - * - * @param theRing the component to print - * @param theMotorMounts the motor mount if clustered, else null - */ - public static PrintableCenteringRing create(CenteringRing theRing, List theMotorMounts) { - if (theMotorMounts == null) { - return new PrintableCenteringRing(theRing, (InnerTube) null); - } - else if (theMotorMounts.size() <= 1) { - return new PrintableCenteringRing(theRing, theMotorMounts.isEmpty() ? null : theMotorMounts.get(0)); - } - else { - return new PrintableCenteringRing(theRing, theMotorMounts); - } - } - - /** - * Initialize the set of center points for each motor mount tube, based on the tube coordinates. - * - * @param theCoords the list of tube coordinates; each coordinate is in the OR units (meters) and must be - * transformed to the printing (points) coordinate system - */ - private void populateCenterPoints(final List theCoords) { - float radius = (float) PrintUnit.METERS.toPoints(target.getOuterRadius()); - for (Coordinate coordinate : theCoords) { - innerCenterPoints.add(new CenteringRingStrategy.Dimension( - (float) PrintUnit.METERS.toPoints(coordinate.y) + radius, //center point x - (float) PrintUnit.METERS.toPoints(coordinate.z) + radius, //center point y - (float) PrintUnit.METERS.toPoints(coordinate.x))); //radius of motor mount - } - } - - /** - * @param component the centering ring component - */ - @Override - protected void init(final CenteringRing component) { - - target = component; - - double radius = target.getOuterRadius(); - setSize((int) PrintUnit.METERS.toPoints(2 * radius), - (int) PrintUnit.METERS.toPoints(2 * radius)); - } - - /** - * Draw a centering ring. - * - * @param g2 the graphics context - */ - @Override - protected void draw(Graphics2D g2) { - double radius = PrintUnit.METERS.toPoints(target.getOuterRadius()); - - Color original = g2.getBackground(); - Shape outerCircle = new Ellipse2D.Double(0, 0, radius * 2, radius * 2); - g2.setColor(Color.lightGray); - g2.fill(outerCircle); - g2.setColor(Color.black); - g2.draw(outerCircle); - - for (CenteringRingStrategy.Dimension next : innerCenterPoints) { - drawInnerCircle(g2, next.getWidth(), next.getHeight(), next.getBreadth()); - } - g2.setColor(original); - } - - /** - * Draw one inner circle, representing the motor mount tube, with cross hairs in the center. - * - * @param g2 the graphics context - * @param theCenterX the center x in points - * @param theCenterY the center y in points - */ - private void drawInnerCircle(final Graphics2D g2, final double theCenterX, final double theCenterY, - final double innerRadius) { - Shape innerCircle = new Ellipse2D.Double(theCenterX - innerRadius, theCenterY - innerRadius, innerRadius * 2, innerRadius * 2); - g2.setColor(Color.white); - g2.fill(innerCircle); - g2.setColor(Color.black); - g2.draw(innerCircle); - - drawCross(g2, (int) theCenterX, (int) theCenterY, lineLength, lineLength); - } - - /** - * Draw the center cross-hair. - * - * @param g the graphics context - * @param x the x coordinate of the center point - * @param y the y coordinate of the center point - * @param width the width in pixels of the horizontal hair - * @param height the width in pixels of the vertical hair - */ - private void drawCross(Graphics g, int x, int y, int width, int height) { - g.setColor(Color.black); - ((Graphics2D) g).setStroke(thinStroke); - g.drawLine(x - width / 2, y, x + width / 2, y); - g.drawLine(x, y - height / 2, x, y + height / 2); - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintableComponent.java b/core/src/net/sf/openrocket/gui/print/PrintableComponent.java deleted file mode 100644 index de345fb9..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintableComponent.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * PrintableComponent.java - */ -package net.sf.openrocket.gui.print; - -import javax.swing.JPanel; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.print.PageFormat; -import java.awt.print.Printable; -import java.awt.print.PrinterException; - -/** - * Common interface for components we want to print. Used by PageFitPrintStrategy - * - * @author Jason Blood - */ -public class PrintableComponent extends JPanel implements Printable, Comparable { - - /** - * The printing offsets. - */ - private int offsetX = 0; - private int offsetY = 0; - - /** - * Constructor. - */ - public PrintableComponent() { - super(false); - } - - /** - * From the java.awt.print.Printable interface. - *

- * Prints the page at the specified index into the specified {@link java.awt.Graphics} context in the specified - * format. A PrinterJob calls the Printable interface to request that a page be rendered - * into the context specified by graphics. The format of the page to be drawn is specified by - * pageFormat. The zero based index of the requested page is specified by pageIndex. If - * the requested page does not exist then this method returns NO_SUCH_PAGE; otherwise PAGE_EXISTS is returned. The - * Graphics class or subclass implements the {@link java.awt.print.PrinterGraphics} interface to - * provide additional information. If the Printable object aborts the print job then it throws a - * {@link java.awt.print.PrinterException}. - *

- * Note: This is not currently used in OpenRocket. It's only here for reference. - * - * @param graphics the context into which the page is drawn - * @param pageFormat the size and orientation of the page being drawn - * @param pageIndex the zero based index of the page to be drawn - * - * @return PAGE_EXISTS if the page is rendered successfully or NO_SUCH_PAGE if pageIndex specifies a - * non-existent page. - * - * @throws java.awt.print.PrinterException - * thrown when the print job is terminated. - */ - @Override - public int print (final Graphics graphics, final PageFormat pageFormat, final int pageIndex) - throws PrinterException { - - Graphics2D g2d = (Graphics2D) graphics; - PrintUtilities.translateToJavaOrigin(g2d, pageFormat); - PrintUtilities.disableDoubleBuffering(this); - paint(g2d); - PrintUtilities.enableDoubleBuffering(this); - return Printable.PAGE_EXISTS; - } - - /** - * Set the offset this component will be printed to the page. - * @param x X offset to print at. - * @param y Y offset to print at. - */ - public void setPrintOffset(int x, int y) { - offsetX = x; - offsetY = y; - } - - /** - * Get the X offset this component will be printed to the page. - * @return X offset to print at. - */ - public int getOffsetX() { - return offsetX; - } - - /** - * Get the Y offset this component will be printed to the page. - * @return Y offset to print at. - */ - public int getOffsetY() { - return offsetY; - } - - - /** - * Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer - * as this object is less than, equal to, or greater than the specified object. - * - * Bin packing theory says that trying to fit the biggest items first may have a better outcome. So this is sorted - * in size descending order, with width taking precedence over height. - * - * @param other the object to be compared. - * - * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the - * specified object. - * - * @throws NullPointerException if the specified object is null - * @throws ClassCastException if the specified object's type prevents it from being compared to this object. - */ - @Override - public int compareTo(final PrintableComponent other) { - int widthDiff = other.getWidth() - getWidth(); - if (widthDiff > 0) { - return 1; - } - else if (widthDiff < 0) { - return -1; - } - return other.getHeight() - getHeight(); - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintableContext.java b/core/src/net/sf/openrocket/gui/print/PrintableContext.java deleted file mode 100644 index 4a5ddcac..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintableContext.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * PrintableContext.java - * - */ -package net.sf.openrocket.gui.print; - -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -/** - * Instances of this class are meant to keep track of what the user has selected to be printed. - */ -public class PrintableContext implements Comparable, Iterable { - - /** - * The stage number. May be null for printables that have no stage meaning. - */ - private Set stageNumber; - - /** - * The type of thing to be printed. - */ - private OpenRocketPrintable printable; - - /** - * Sort of a reverse map that tracks each type of printable item and the stages for which that item is to be printed. - */ - private final Map> previous = new TreeMap>(); - - /** - * Constructor. - */ - public PrintableContext() { - } - - /** - * Constructor. - * - * @param theStageNumber the stage number of the printable; may be null if not applicable - * @param thePrintable the type of the thing to be printed - * - * @throws IllegalArgumentException thrown if thePrintable.isStageSpecific - */ - private PrintableContext(final Set theStageNumber, final OpenRocketPrintable thePrintable) - throws IllegalArgumentException { - if (thePrintable.isStageSpecific() && theStageNumber == null) { - throw new IllegalArgumentException("A stage number must be provided when a printable is stage specific."); - } - stageNumber = theStageNumber; - printable = thePrintable; - } - - /** - * Add a type of printable to a stage (number). - * - * @param theStageNumber the stage number - * @param thePrintable the printable to associate with the stage - */ - public void add(final Integer theStageNumber, final OpenRocketPrintable thePrintable) { - Set stages = previous.get(thePrintable); - if (stages == null) { - stages = new TreeSet(); - previous.put(thePrintable, stages); - } - if (theStageNumber != null) { - stages.add(theStageNumber); - } - } - - /** PrintableContext iterator. */ - @Override - public Iterator iterator() { - return new Iterator() { - - Iterator keyIter = previous.keySet().iterator(); - - @Override - public boolean hasNext() { - return keyIter.hasNext(); - } - - @Override - public PrintableContext next() { - final OpenRocketPrintable key = keyIter.next(); - return new PrintableContext(previous.get(key), key); - } - - @Override - public void remove() { - } - }; - - } - - /** - * Get the stage number, if it's applicable to the printable. - * - * @return the stage number - */ - public Set getStageNumber() { - return stageNumber; - } - - /** - * Get the printable. - * - * @return the printable - */ - public OpenRocketPrintable getPrintable() { - return printable; - } - - @Override - public int compareTo(final PrintableContext other) { - return this.printable.getPrintOrder() - other.printable.getPrintOrder(); - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintableFinSet.java b/core/src/net/sf/openrocket/gui/print/PrintableFinSet.java deleted file mode 100644 index 8e5389b2..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintableFinSet.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * PrintableFinSet.java - */ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.util.Coordinate; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.geom.GeneralPath; -import java.awt.image.BufferedImage; - -/** - * This class allows for a FinSet to be printable. It does so by decorating an existing finset (which will not be - * modified) and rendering it within a JPanel. The JPanel is not actually visualized on a display, but instead renders - * it to a print device. - */ -public class PrintableFinSet extends PrintableComponent { - - /** - * The object that represents the shape (outline) of the fin. This gets drawn onto the Swing component. - */ - protected GeneralPath polygon = null; - - /** - * The minimum X coordinate. - */ - private int minX = 0; - /** - * The minimum Y coordinate. - */ - private int minY = 0; - - /** - * Constructor. - * - * @param fs the finset to print - */ - public PrintableFinSet (FinSet fs) { - this(fs.getFinPointsWithTab()); - } - - /** - * Construct a fin set from a set of points. - * - * @param points an array of points. - */ - public PrintableFinSet (Coordinate[] points) { - init(points); - } - - /** - * Initialize the fin set polygon and set the size of the component. - * - * @param points an array of points. - */ - private void init (Coordinate[] points) { - - polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD, points.length); - polygon.moveTo(0, 0); - - int maxX = 0; - int maxY = 0; - - for (Coordinate point : points) { - final long x = (long)PrintUnit.METERS.toPoints(point.x); - final long y = (long)PrintUnit.METERS.toPoints(point.y); - minX = (int) Math.min(x, minX); - minY = (int) Math.min(y, minY); - maxX = (int) Math.max(x, maxX); - maxY = (int) Math.max(y, maxY); - polygon.lineTo(x, y); - } - polygon.closePath(); - - setSize(maxX - minX, maxY - minY); - } - - /** - * Returns a generated image of the fin set. May then be used wherever AWT images can be used, or converted to - * another image/picture format and used accordingly. - * - * @return an awt image of the fin set - */ - public Image createImage () { - int width = getWidth(); - int height = getHeight(); - // Create a buffered image in which to draw - BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - // Create a graphics contents on the buffered image - Graphics2D g2d = bufferedImage.createGraphics(); - // Draw graphics - g2d.setBackground(Color.white); - g2d.clearRect(0, 0, width, height); - paintComponent(g2d); - // Graphics context no longer needed so dispose it - g2d.dispose(); - return bufferedImage; - } - - /** - * Render the fin set onto the graphics context. This is done by creating a GeneralPath component that follows the - * outline of the fin set coordinates to create a polygon, which is then drawn onto the graphics context. - * Through-the-wall fin tabs are supported if they are present. - * - * @param g the Java2D graphics context - */ - @Override - public void paintComponent(Graphics g) { - Graphics2D g2d = (Graphics2D) g; - - int x = 0; - int y = 0; - - int marginX = this.getOffsetX(); - int marginY = this.getOffsetY(); - - // The minimum X/Y can be negative (primarily only Y due to fin tabs; rarely (never) X, but protect both anyway). - if (minX < marginX) { - x = marginX + Math.abs(minX); - } - if (minY < marginY) { - y = marginY + Math.abs(minY); - } - // Reset the origin. - g2d.translate(x, y); - g2d.setPaint(TemplateProperties.getFillColor()); - g2d.fill(polygon); - g2d.setPaint(TemplateProperties.getLineColor()); - g2d.draw(polygon); - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintableNoseCone.java b/core/src/net/sf/openrocket/gui/print/PrintableNoseCone.java deleted file mode 100644 index 2cfdfa68..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintableNoseCone.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.gui.rocketfigure.TransitionShapes; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.util.Transformation; - -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.Shape; - -public class PrintableNoseCone extends AbstractPrintable { - - /** - * If the component to be drawn is a nose cone, save a reference to it. - */ - private NoseCone target; - - /** - * Construct a printable nose cone. - * - * @param noseCone the component to print - */ - public PrintableNoseCone(NoseCone noseCone) { - super(false, noseCone); - } - - @Override - protected void init(NoseCone component) { - - target = component; - double radius = target.getForeRadius(); - if (radius < target.getAftRadius()) { - radius = target.getAftRadius(); - } - setSize((int) PrintUnit.METERS.toPoints(2 * radius) + 4, - (int) PrintUnit.METERS.toPoints(target.getLength() + target.getAftShoulderLength()) + 4); - } - - /** - * Draw a nose cone. Presumes that the graphics context has already had the x/y position translated based on - * where it should be drawn. - * - * @param g2 the graphics context - */ - @Override - protected void draw(Graphics2D g2) { - Shape[] shapes = TransitionShapes.getShapesSide(target, Transformation.rotate_x(0d), PrintUnit.METERS.toPoints(1)); - - if (shapes != null && shapes.length > 0) { - Rectangle r = shapes[0].getBounds(); - g2.translate(r.getHeight() / 2, 0); - g2.rotate(Math.PI / 2); - for (Shape shape : shapes) { - g2.draw(shape); - } - g2.rotate(-Math.PI / 2); - } - } -} diff --git a/core/src/net/sf/openrocket/gui/print/PrintableTransition.java b/core/src/net/sf/openrocket/gui/print/PrintableTransition.java deleted file mode 100644 index 41a9958a..00000000 --- a/core/src/net/sf/openrocket/gui/print/PrintableTransition.java +++ /dev/null @@ -1,214 +0,0 @@ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.rocketcomponent.Transition; - -import java.awt.BasicStroke; -import java.awt.Graphics2D; -import java.awt.geom.Arc2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Path2D; -import java.awt.geom.Point2D; - -/** - * This class allows for a Transition to be printable. It does so by decorating an existing transition (which will not be - * modified) and rendering it within a JPanel. The JPanel is not actually visualized on a display, but instead renders - * it to a print device. - *

- * Note: Currently nose cones are only supported by drawing the 2D projection of the profile. A more useful approach - * may be to draw a myriahedral projection that can be cut out and bent to form the shape. - */ -public class PrintableTransition extends AbstractPrintable { - - /** - * Dashed array value. - */ - private final static float dash1[] = { 4.0f }; - /** - * The dashed stroke for glue tab. - */ - private final static BasicStroke dashed = new BasicStroke(1.0f, - BasicStroke.CAP_BUTT, - BasicStroke.JOIN_MITER, - 10.0f, dash1, 0.0f); - - /** - * The layout is an outer arc, an inner arc, and two lines one either endpoints that connect the arcs. - * Most of the math involves transposing geometric cartesian coordinates to the Java AWT coordinate system. - */ - private Path2D gp; - - /** - * The glue tab. - */ - private Path2D glueTab1; - - /** - * The alignment marks. - */ - private Line2D tick1, tick2; - - /** - * The x coordinates for the two ticks drawn at theta degrees. - */ - private int tick3X, tick4X; - - /** - * The angle, in degrees. - */ - private float theta; - - /** - * The x,y coordinates for where the virtual circle center is located. - */ - private int circleCenterX, circleCenterY; - - /** - * Constructor. - * - * @param transition the transition to print - */ - public PrintableTransition(Transition transition) { - super(false, transition); - } - - /** - * Compute the basic values of each arc of the transition/shroud. This is adapted from - * The Properties of - * Model Rocket Body Tube Transitions, by J.R. Brohm - * - * @param component the component - */ - @Override - protected void init(Transition component) { - - double r1 = component.getAftRadius(); - double r2 = component.getForeRadius(); - - //Regardless of orientation, we have the convention of R1 as the smaller radius. Flip if different. - if (r1 > r2) { - r1 = r2; - r2 = component.getAftRadius(); - } - double len = component.getLength(); - double v = r2 - r1; - double tmp = Math.sqrt(v * v + len * len); - double factor = tmp / v; - - theta = (float) (360d * v / tmp); - - int r1InPoints = (int) PrintUnit.METERS.toPoints(r1 * factor); - int r2InPoints = (int) PrintUnit.METERS.toPoints(r2 * factor); - - int x = 0; - int tabOffset = 35; - int y = tabOffset; - - Arc2D.Double outerArc = new Arc2D.Double(); - Arc2D.Double innerArc = new Arc2D.Double(); - - //If the arcs are more than 3/4 of a circle, then assume the height (y) is the same as the radius of the bigger arc. - if (theta >= 270) { - y += r2InPoints; - } - //If the arc is between 1/2 and 3/4 of a circle, then compute the actual height based upon the angle and radius - //of the bigger arc. - else if (theta >= 180) { - double thetaRads = Math.toRadians(theta - 180); - y += (int) ((Math.cos(thetaRads) * r2InPoints) * Math.tan(thetaRads)); - } - - circleCenterY = y; - circleCenterX = r2InPoints + x; - - //Create the larger arc. - outerArc.setArcByCenter(circleCenterX, circleCenterY, r2InPoints, 180, theta, Arc2D.OPEN); - - //Create the smaller arc. - innerArc.setArcByCenter(circleCenterX, circleCenterY, r1InPoints, 180, theta, Arc2D.OPEN); - - //Create the line between the start of the larger arc and the start of the smaller arc. - Path2D.Double line = new Path2D.Double(); - line.setWindingRule(Path2D.WIND_NON_ZERO); - line.moveTo(x, y); - final int width = r2InPoints - r1InPoints; - line.lineTo(width + x, y); - - //Create the line between the endpoint of the larger arc and the endpoint of the smaller arc. - Path2D.Double closingLine = new Path2D.Double(); - closingLine.setWindingRule(Path2D.WIND_NON_ZERO); - Point2D innerArcEndPoint = innerArc.getEndPoint(); - closingLine.moveTo(innerArcEndPoint.getX(), innerArcEndPoint.getY()); - Point2D outerArcEndPoint = outerArc.getEndPoint(); - closingLine.lineTo(outerArcEndPoint.getX(), outerArcEndPoint.getY()); - - //Add all shapes to the polygon path. - gp = new Path2D.Float(GeneralPath.WIND_EVEN_ODD, 4); - gp.append(line, false); - gp.append(outerArc, false); - gp.append(closingLine, false); - gp.append(innerArc, false); - - //Create the glue tab. - glueTab1 = new Path2D.Float(GeneralPath.WIND_EVEN_ODD, 4); - glueTab1.moveTo(x, y); - glueTab1.lineTo(x + tabOffset, y - tabOffset); - glueTab1.lineTo(width + x - tabOffset, y - tabOffset); - glueTab1.lineTo(width + x, y); - - //Create tick marks for alignment, 1/4 of the width in from either edge - int fromEdge = width / 4; - final int tickLength = 8; - //Upper left - tick1 = new Line2D.Float(x + fromEdge, y, x + fromEdge, y + tickLength); - //Upper right - tick2 = new Line2D.Float(x + width - fromEdge, y, x + width - fromEdge, y + tickLength); - - tick3X = r2InPoints - fromEdge; - tick4X = r1InPoints + fromEdge; - - setSize(gp.getBounds().width, gp.getBounds().height + tabOffset); - } - - /** - * Draw alignment marks on an angle. - * - * @param g2 the graphics context - * @param x the center of the circle's x coordinate - * @param y the center of the circle's y - * @param line the line to draw - * @param theta the angle - */ - private void drawAlignmentMarks(Graphics2D g2, int x, int y, Line2D.Float line, float theta) { - g2.translate(x, y); - g2.rotate(Math.toRadians(-theta)); - g2.draw(line); - g2.rotate(Math.toRadians(theta)); - g2.translate(-x, -y); - } - - /** - * Draw a transition. - * - * @param g2 the graphics context - */ - @Override - protected void draw(Graphics2D g2) { - //Render it. - g2.draw(gp); - g2.draw(tick1); - g2.draw(tick2); - drawAlignmentMarks(g2, circleCenterX, - circleCenterY, - new Line2D.Float(-tick3X, 0, -tick3X, -8), - theta); - drawAlignmentMarks(g2, circleCenterX, - circleCenterY, - new Line2D.Float(-tick4X, 0, -tick4X, -8), - theta); - - g2.setStroke(dashed); - g2.draw(glueTab1); - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/TemplateProperties.java b/core/src/net/sf/openrocket/gui/print/TemplateProperties.java deleted file mode 100644 index 6f88e576..00000000 --- a/core/src/net/sf/openrocket/gui/print/TemplateProperties.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * TemplateProperties.java - */ -package net.sf.openrocket.gui.print; - -import java.awt.Color; - -import javax.swing.UIManager; - -/** - * This class is responsible for managing various properties of print templates (fin, nose cone, transitions, etc.). - * - * TODO: HIGH: Remove this entire class, and instead pass the PrintSettings object to the print methods. - */ -public class TemplateProperties { - - /** - * The property that defines the fill color. - */ - public static final String TEMPLATE_FILL_COLOR_PROPERTY = "template.fill.color"; - - /** - * The property that defines the line color. - */ - public static final String TEMPLATE_LINE_COLOR_PROPERTY = "template.line.color"; - - /** - * Get the current fill color. - * - * @return a color to be used as the fill in template shapes - */ - public static Color getFillColor() { - Color fillColor = UIManager.getColor(TemplateProperties.TEMPLATE_FILL_COLOR_PROPERTY); - if (fillColor == null) { - fillColor = Color.lightGray; - } - return fillColor; - } - - - /** - * Set the template fill color. - */ - public static void setFillColor(Color c) { - UIManager.put(TemplateProperties.TEMPLATE_FILL_COLOR_PROPERTY, c); - } - - - /** - * Get the current line color. - * - * @return a color to be used as the line in template shapes - */ - public static Color getLineColor() { - Color lineColor = UIManager.getColor(TemplateProperties.TEMPLATE_LINE_COLOR_PROPERTY); - if (lineColor == null) { - lineColor = Color.darkGray; - } - return lineColor; - } - - /** - * Set the template line color. - */ - public static void setLineColor(Color c) { - UIManager.put(TemplateProperties.TEMPLATE_LINE_COLOR_PROPERTY, c); - } - - /** - * Set the template colors from the print settings. - */ - public static void setColors(PrintSettings settings) { - setFillColor(settings.getTemplateFillColor()); - setLineColor(settings.getTemplateBorderColor()); - } -} diff --git a/core/src/net/sf/openrocket/gui/print/components/CheckBoxNode.java b/core/src/net/sf/openrocket/gui/print/components/CheckBoxNode.java deleted file mode 100644 index 7fbab0a6..00000000 --- a/core/src/net/sf/openrocket/gui/print/components/CheckBoxNode.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * CheckBoxNode.java - */ -package net.sf.openrocket.gui.print.components; - -/** - * A class that acts as the textual node of the check box within the JTree. - */ -public class CheckBoxNode { - - /** - * The text label of the check box. - */ - String text; - - /** - * State flag indicating if the check box has been selected. - */ - boolean selected; - - /** - * Constructor. - * - * @param theText the check box label - * @param isSelected true if selected - */ - public CheckBoxNode (String theText, boolean isSelected) { - text = theText; - selected = isSelected; - } - - /** - * Get the current state of the check box. - * - * @return true if selected - */ - public boolean isSelected () { - return selected; - } - - /** - * Set the current state of the check box. Note: this just tracks the state - it - * does NOT actually set the state of the check box. - * - * @param isSelected true if selected - */ - public void setSelected (boolean isSelected) { - selected = isSelected; - } - - /** - * Get the text of the label. - * - * @return the text of the label - */ - public String getText () { - return text; - } - - /** - * Set the text of the label of the check box. - * - * @param theText the text of the label - */ - public void setText (String theText) { - text = theText; - } - - /** - * If someone prints this object, the text label will be displayed. - * - * @return the text label - */ - public String toString () { - return text; - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/components/CheckTreeCellRenderer.java b/core/src/net/sf/openrocket/gui/print/components/CheckTreeCellRenderer.java deleted file mode 100644 index e4a93373..00000000 --- a/core/src/net/sf/openrocket/gui/print/components/CheckTreeCellRenderer.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * CheckTreeCellRenderer.java - */ -package net.sf.openrocket.gui.print.components; - -import javax.swing.JCheckBox; -import javax.swing.JPanel; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreeCellRenderer; -import javax.swing.tree.TreePath; -import java.awt.BorderLayout; -import java.awt.Component; - -/** - * A cell renderer for JCheckBoxes within nodes of a JTree. - *

- * Based in part on a blog by Santhosh Kumar. http://www.jroller.com/santhosh/date/20050610 - */ -public class CheckTreeCellRenderer extends JPanel implements TreeCellRenderer { - - /** - * The selection model. - */ - private CheckTreeSelectionModel selectionModel; - /** - * The delegated cell renderer. - */ - private DefaultTreeCellRenderer delegate; - /** - * The check box within this cell. - */ - private JCheckBox checkBox = new JCheckBox(); - - /** - * Constructor. - * - * @param theDelegate the delegated cell renderer - * @param theSelectionModel the selection model - */ - public CheckTreeCellRenderer (DefaultTreeCellRenderer theDelegate, CheckTreeSelectionModel theSelectionModel) { - delegate = theDelegate; - - delegate.setLeafIcon(null); - delegate.setClosedIcon(null); - delegate.setOpenIcon(null); - - - selectionModel = theSelectionModel; - setLayout(new BorderLayout()); - setOpaque(false); - checkBox.setOpaque(false); - checkBox.setSelected(true); - } - - /** - * @{inheritDoc} - */ - @Override - public Component getTreeCellRendererComponent (JTree tree, Object value, boolean selected, boolean expanded, - boolean leaf, int row, boolean hasFocus) { - Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, - hasFocus); - - TreePath path = tree.getPathForRow(row); - if (path != null) { - final boolean b = selectionModel.isPathSelected(path, true); - checkBox.setSelected(b); - if (value instanceof DefaultMutableTreeNode) { - Object obj = ((DefaultMutableTreeNode) value).getUserObject(); - if (obj instanceof CheckBoxNode) { - ((CheckBoxNode) obj).setSelected(b); - } - } - } - - removeAll(); - add(checkBox, BorderLayout.WEST); - add(renderer, BorderLayout.CENTER); - return this; - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/components/CheckTreeManager.java b/core/src/net/sf/openrocket/gui/print/components/CheckTreeManager.java deleted file mode 100644 index 719e50d7..00000000 --- a/core/src/net/sf/openrocket/gui/print/components/CheckTreeManager.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * CheckTreeManager.java - */ -package net.sf.openrocket.gui.print.components; - -import javax.swing.JCheckBox; -import javax.swing.JTree; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreePath; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * This class manages mouse clicks within the JTree, handling selection/deselections within the JCheckBox of each cell in the tree. - */ -public class CheckTreeManager extends MouseAdapter implements TreeSelectionListener { - - /** The selection model. */ - private CheckTreeSelectionModel selectionModel; - /** The actual JTree instance. */ - private JTree tree; - /** The number of pixels of width of the check box. Clicking anywhere within the box will trigger actions. */ - int hotspot = new JCheckBox().getPreferredSize().width; - - /** - * Construct a check box tree manager. - * - * @param theTree the actual tree being managed - */ - public CheckTreeManager (RocketPrintTree theTree) { - tree = theTree; - selectionModel = new CheckTreeSelectionModel(tree.getModel()); - theTree.setCheckBoxSelectionModel(selectionModel); - tree.setCellRenderer(new CheckTreeCellRenderer((DefaultTreeCellRenderer)tree.getCellRenderer(), selectionModel)); - tree.addMouseListener(this); - selectionModel.addTreeSelectionListener(this); - - for (int x = 0; x < tree.getRowCount(); x++) { - tree.getSelectionModel().setSelectionPath(tree.getPathForRow(x)); - } - } - - public void addTreeSelectionListener (TreeSelectionListener tsl) { - selectionModel.addTreeSelectionListener(tsl); - } - - /** - * Called when the mouse clicks within the tree. - * - * @param me the event that triggered this - */ - @Override - public void mouseClicked (MouseEvent me) { - TreePath path = tree.getPathForLocation(me.getX(), me.getY()); - if (path == null) { - return; - } - if (me.getX() > tree.getPathBounds(path).x + hotspot) { - return; - } - - boolean selected = selectionModel.isPathSelected(path, true); - selectionModel.removeTreeSelectionListener(this); - - try { - if (selected) { - selectionModel.removeSelectionPath(path); - } - else { - selectionModel.addSelectionPath(path); - } - } - finally { - selectionModel.addTreeSelectionListener(this); - tree.treeDidChange(); - } - } - - /** - * Get the selection model being used by this manager. - * - * @return the selection model - */ - public CheckTreeSelectionModel getSelectionModel () { - return selectionModel; - } - - /** - * Notify the tree that it changed. - * - * @param e unused - */ - @Override - public void valueChanged (TreeSelectionEvent e) { - tree.treeDidChange(); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/components/CheckTreeSelectionModel.java b/core/src/net/sf/openrocket/gui/print/components/CheckTreeSelectionModel.java deleted file mode 100644 index 9f34b4b5..00000000 --- a/core/src/net/sf/openrocket/gui/print/components/CheckTreeSelectionModel.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * CheckTreeSelectionModel.java - */ -package net.sf.openrocket.gui.print.components; - -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.util.ArrayList; -import java.util.Stack; - -/** - * This class implements the selection model for the checkbox tree. This specifically is used to keep - * track of the TreePaths that have a selected CheckBox. - */ -public class CheckTreeSelectionModel extends DefaultTreeSelectionModel { - - /** - * The tree model. - */ - private TreeModel model; - - /** - * Constructor. - * - * @param theModel the model in use for the tree - */ - public CheckTreeSelectionModel (TreeModel theModel) { - model = theModel; - setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); - } - - /** - * Tests whether there is any selected node in the subtree of given path. - * - * @param path the path to walk - * - * @return true if any item in the path or its descendants are selected - */ - public boolean isPartiallySelected (TreePath path) { - if (isPathSelected(path, true)) { - return false; - } - TreePath[] selectionPaths = getSelectionPaths(); - if (selectionPaths == null) { - return false; - } - for (TreePath selectionPath : selectionPaths) { - if (isDescendant(selectionPath, path)) { - return true; - } - } - return false; - } - - /** - * Tells whether given path is selected. If dig is true, then a path is assumed to be selected, if one of its - * ancestor is selected. - * - * @param path the path to interrogate - * @param dig if true then check if an ancestor is selected - * - * @return true if the path is selected - */ - public boolean isPathSelected (TreePath path, boolean dig) { - if (!dig) { - return super.isPathSelected(path); - } - while (path != null && !super.isPathSelected(path)) { - path = path.getParentPath(); - } - return path != null; - } - - /** - * Determines if path1 is a descendant of path2. - * - * @param path1 descendant? - * @param path2 ancestor? - * - * @return true if path1 is a descendant of path2 - */ - private boolean isDescendant (TreePath path1, TreePath path2) { - Object obj1[] = path1.getPath(); - Object obj2[] = path2.getPath(); - for (int i = 0; i < obj2.length; i++) { - if (i < obj1.length) { - if (obj1[i] != obj2[i]) { - return false; - } - } - else { - return false; - } - } - return true; - } - - - /** - * Unsupported exception. - * - * @param pPaths an array of paths - */ - public void setSelectionPaths (TreePath[] pPaths) { - TreePath selected[] = getSelectionPaths(); - for (TreePath aSelected : selected) { - removeSelectionPath(aSelected); - } - for (TreePath pPath : pPaths) { - addSelectionPath(pPath); - } - } - - /** - * Add a set of TreePath nodes to the selection model. - * - * @param paths an array of tree path nodes - */ - public void addSelectionPaths (TreePath[] paths) { - // deselect all descendants of paths[] - for (TreePath path : paths) { - TreePath[] selectionPaths = getSelectionPaths(); - if (selectionPaths == null) { - break; - } - ArrayList toBeRemoved = new ArrayList(); - for (TreePath selectionPath : selectionPaths) { - if (isDescendant(selectionPath, path)) { - toBeRemoved.add(selectionPath); - } - } - super.removeSelectionPaths(toBeRemoved.toArray(new TreePath[toBeRemoved.size()])); - } - - // if all siblings are selected then deselect them and select parent recursively - // otherwise just select that path. - for (TreePath path : paths) { - TreePath temp = null; - while (areSiblingsSelected(path)) { - temp = path; - if (path.getParentPath() == null) { - break; - } - path = path.getParentPath(); - } - if (temp != null) { - if (temp.getParentPath() != null) { - addSelectionPath(temp.getParentPath()); - } - else { - if (!isSelectionEmpty()) { - removeSelectionPaths(getSelectionPaths()); - } - super.addSelectionPaths(new TreePath[]{temp}); - } - } - else { - super.addSelectionPaths(new TreePath[]{path}); - } - } - } - - /** - * Tells whether all siblings of given path are selected. - * - * @param path the tree path node - * - * @return true if all sibling nodes are selected - */ - private boolean areSiblingsSelected (TreePath path) { - TreePath parent = path.getParentPath(); - if (parent == null) { - return true; - } - Object node = path.getLastPathComponent(); - Object parentNode = parent.getLastPathComponent(); - - int childCount = model.getChildCount(parentNode); - for (int i = 0; i < childCount; i++) { - Object childNode = model.getChild(parentNode, i); - if (childNode == node) { - continue; - } - if (!isPathSelected(parent.pathByAddingChild(childNode))) { - return false; - } - } - return true; - } - - /** - * Remove paths from the selection model. - * - * @param paths the array of path nodes - */ - public void removeSelectionPaths (TreePath[] paths) { - for (TreePath path : paths) { - if (path.getPathCount() == 1) { - super.removeSelectionPaths(new TreePath[]{path}); - } - else { - toggleRemoveSelection(path); - } - } - } - - /** - * If any ancestor node of given path is selected then deselect it and selection all its descendants except given - * path and descendants. otherwise just deselect the given path. - * - * @param path the tree path node - */ - private void toggleRemoveSelection (TreePath path) { - Stack stack = new Stack(); - TreePath parent = path.getParentPath(); - while (parent != null && !isPathSelected(parent)) { - stack.push(parent); - parent = parent.getParentPath(); - } - if (parent != null) { - stack.push(parent); - } - else { - super.removeSelectionPaths(new TreePath[]{path}); - return; - } - - while (!stack.isEmpty()) { - TreePath temp = stack.pop(); - TreePath peekPath = stack.isEmpty() ? path : stack.peek(); - Object node = temp.getLastPathComponent(); - Object peekNode = peekPath.getLastPathComponent(); - int childCount = model.getChildCount(node); - for (int i = 0; i < childCount; i++) { - Object childNode = model.getChild(node, i); - if (childNode != peekNode) { - super.addSelectionPaths(new TreePath[]{temp.pathByAddingChild(childNode)}); - } - } - } - super.removeSelectionPaths(new TreePath[]{parent}); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/components/RocketPrintTree.java b/core/src/net/sf/openrocket/gui/print/components/RocketPrintTree.java deleted file mode 100644 index 5296ea47..00000000 --- a/core/src/net/sf/openrocket/gui/print/components/RocketPrintTree.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * RocketPrintTree.java - */ -package net.sf.openrocket.gui.print.components; - -import net.sf.openrocket.gui.print.OpenRocketPrintable; -import net.sf.openrocket.gui.print.PrintableContext; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; - -import javax.swing.*; -import javax.swing.event.TreeExpansionEvent; -import javax.swing.event.TreeWillExpandListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.ExpandVetoException; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -/** - * A specialized JTree for displaying various rocket items that can be printed. - */ -public class RocketPrintTree extends JTree { - - /** - * All check boxes are initially set to true (selected). - */ - public static final boolean INITIAL_CHECKBOX_SELECTED = true; - - /** - * The selection model that tracks the check box state. - */ - private TreeSelectionModel theCheckBoxSelectionModel; - - /** - * Constructor. - * - * @param root the vector of check box nodes (rows) to place into the tree - */ - private RocketPrintTree(Vector root) { - super(root); - - //Remove the little down and sideways arrows. These are not needed because the tree expansion is fixed. - ((javax.swing.plaf.basic.BasicTreeUI) this.getUI()). - setExpandedIcon(null); - ((javax.swing.plaf.basic.BasicTreeUI) this.getUI()). - setCollapsedIcon(null); - } - - /** - * Factory method to create a specialized JTree. This version is for rocket's that have more than one stage. - * - * @param rocketName the name of the rocket - * @param stages the array of all stages - * - * @return an instance of JTree - */ - public static RocketPrintTree create(String rocketName, List stages) { - Vector root = new Vector(); - Vector toAddTo = root; - - if (stages != null) { - if (stages.size() > 1) { - final Vector parent = new NamedVector(rocketName != null ? rocketName : "Rocket"); - - root.add(parent); - toAddTo = parent; - } - for (RocketComponent stage : stages) { - if (stage instanceof Stage) { - toAddTo.add(createNamedVector(stage.getName(), createPrintTreeNode(true), stage.getStageNumber())); - } - } - } - - List unstaged = OpenRocketPrintable.getUnstaged(); - for (int i = 0; i < unstaged.size(); i++) { - toAddTo.add(new CheckBoxNode(unstaged.get(i).getDescription(), - INITIAL_CHECKBOX_SELECTED)); - } - - RocketPrintTree tree = new RocketPrintTree(root); - - tree.addTreeWillExpandListener - (new TreeWillExpandListener() { - @Override - public void treeWillExpand(TreeExpansionEvent e) { - } - - @Override - public void treeWillCollapse(TreeExpansionEvent e) - throws ExpandVetoException { - throw new ExpandVetoException(e, "you can't collapse this JTree"); - } - }); - - return tree; - } - - /** - * Factory method to create a specialized JTree. This version is for a rocket with only one stage. - * - * @param rocketName the name of the rocket - * - * @return an instance of JTree - */ - public static RocketPrintTree create(String rocketName) { - Vector root = new Vector(); - root.add(new NamedVector(rocketName != null ? rocketName : "Rocket", createPrintTreeNode(false))); - - RocketPrintTree tree = new RocketPrintTree(root); - - tree.addTreeWillExpandListener - (new TreeWillExpandListener() { - @Override - public void treeWillExpand(TreeExpansionEvent e) { - } - - @Override - public void treeWillCollapse(TreeExpansionEvent e) - throws ExpandVetoException { - throw new ExpandVetoException(e, "you can't collapse this JTree"); - } - }); - - return tree; - } - - /** - * This tree needs to have access both to the normal selection model (for the textual row) which is managed by the - * superclass, as well as the selection model for the check boxes. This mutator method allows an external class to - * set the model back onto this class. Because of some unfortunate circular dependencies this cannot be set at - * construction. - *

- * TODO: Ensure these circular references get cleaned up properly at dialog disposal so everything can be GC'd. - * - * @param checkBoxSelectionModel the selection model used to keep track of the check box state - */ - public void setCheckBoxSelectionModel(TreeSelectionModel checkBoxSelectionModel) { - theCheckBoxSelectionModel = checkBoxSelectionModel; - } - - /** - * Add a selection path to the internal check box selection model. The normal JTree selection model is unaffected. - * This has the effect of "selecting" the check box, but not highlighting the row. - * - * @param path the path (row) - */ - @Override - public void addSelectionPath(TreePath path) { - theCheckBoxSelectionModel.addSelectionPath(path); - } - - /** - * Helper to construct a named vector. - * - * @param name the name of the vector - * @param nodes the array of nodes to put into the vector - * @param stage the stage number - * - * @return a NamedVector suitable for adding to a JTree - */ - private static Vector createNamedVector(String name, CheckBoxNode[] nodes, int stage) { - return new NamedVector(name, nodes, stage); - } - - /** - * Helper to construct the set of check box rows for each stage. - * - * @param onlyStageSpecific if true then only stage specific OpenRocketPrintable rows are represented (in this part - * of the tree). - * - * @return an array of CheckBoxNode - */ - private static CheckBoxNode[] createPrintTreeNode(boolean onlyStageSpecific) { - List nodes = new ArrayList(); - OpenRocketPrintable[] printables = OpenRocketPrintable.values(); - for (OpenRocketPrintable openRocketPrintable : printables) { - if (!onlyStageSpecific || openRocketPrintable.isStageSpecific()) { - nodes.add(new CheckBoxNode(openRocketPrintable.getDescription(), - INITIAL_CHECKBOX_SELECTED)); - } - } - return nodes.toArray(new CheckBoxNode[nodes.size()]); - } - - /** - * Get the set of items to be printed, as selected by the user. - * - * @return the things to be printed, returned as an Iterator - */ - public Iterator getToBePrinted() { - final DefaultMutableTreeNode mutableTreeNode = (DefaultMutableTreeNode) getModel().getRoot(); - PrintableContext pc = new PrintableContext(); - add(pc, mutableTreeNode); - return pc.iterator(); - } - - /** - * Walk a tree, finding everything that has been selected and aggregating it into something that can be iterated upon - * This method is recursive. - * - * @param pc the printable context that aggregates the choices into an iterator - * @param theMutableTreeNode the root node - */ - private void add(final PrintableContext pc, final DefaultMutableTreeNode theMutableTreeNode) { - int children = theMutableTreeNode.getChildCount(); - for (int x = 0; x < children; x++) { - - final DefaultMutableTreeNode at = (DefaultMutableTreeNode) theMutableTreeNode.getChildAt(x); - if (at.getUserObject() instanceof CheckBoxNode) { - CheckBoxNode cbn = (CheckBoxNode) at.getUserObject(); - if (cbn.isSelected()) { - final OpenRocketPrintable printable = OpenRocketPrintable.findByDescription(cbn.getText()); - pc.add( - printable.isStageSpecific() ? ((NamedVector) theMutableTreeNode.getUserObject()) - .getStage() : null, - printable); - } - } - add(pc, at); - } - } - -} - -/** - * JTree's work off of Vector's (unfortunately). This class is tailored for use with check boxes in the JTree. - */ -class NamedVector extends Vector { - String name; - - int stageNumber; - - public NamedVector(String theName) { - name = theName; - } - - public NamedVector(String theName, CheckBoxNode elements[], int stage) { - this(theName, elements); - stageNumber = stage; - } - - public NamedVector(String theName, CheckBoxNode elements[]) { - name = theName; - for (int i = 0, n = elements.length; i < n; i++) { - add(elements[i]); - } - } - - @Override - public String toString() { - return name; - } - - public int getStage() { - return stageNumber; - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/components/Rule.java b/core/src/net/sf/openrocket/gui/print/components/Rule.java deleted file mode 100644 index b26d6528..00000000 --- a/core/src/net/sf/openrocket/gui/print/components/Rule.java +++ /dev/null @@ -1,274 +0,0 @@ -package net.sf.openrocket.gui.print.components; - -import net.sf.openrocket.gui.print.PrintUnit; -import net.sf.openrocket.gui.print.PrintableComponent; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; - -/** - * This class creates a Swing ruler. The ruler has both vertical and horizontal rules, as well as divisions for both - * inches and centimeters. - */ -public class Rule extends PrintableComponent { - - public static enum Orientation { - TOP, - BOTTOM - } - - public static final int TINIEST_TICK_LENGTH = 3; - public static final int MINOR_TICK_LENGTH = 6; - public static final int MID_MAJOR_TICK_LENGTH = 9; - public static final int MAJOR_TICK_LENGTH = 14; - - private Orientation orientation; - - /** - * Constructor. - * - * @param theOrientation defines if the horizontal ruler should be on the top or bottom; the vertical is always - * left justified - */ - public Rule(Orientation theOrientation) { - orientation = theOrientation; - int dim = (int) PrintUnit.INCHES.toPoints(2) + 32; - setSize(dim, dim); - } - - /** - * Render the component onto a graphics context. - * - * @param g the opaque graphics context - */ - public void paintComponent(Graphics g) { - Graphics2D g2 = (Graphics2D) g; - - double div = PrintUnit.INCHES.toPoints(1) / 8; //1/8 inch increment - final int width = (int) PrintUnit.INCHES.toPoints(2); - int x = 20; - int y = x + 20; - boolean inchOutSide = true; - - g2.translate(getOffsetX(), getOffsetY()); - - if (orientation == Orientation.TOP) { - Font f = g.getFont(); - g.setFont(f.deriveFont(f.getSize() - 2f)); - g.drawString("in cm", x - MAJOR_TICK_LENGTH, y + width + 20); - g.drawString("in", x + width + 4, y + 4); - g.drawString("cm", x + width + 4, y + 18); - y += 6; - - drawVerticalRule(g2, true, inchOutSide, x, y, width, 0, div * 2, div * 4, div * 8); - drawHorizontalRule(g2, true, !inchOutSide, x, y, width, 0, div * 2, div * 4, div * 8); - div = PrintUnit.MILLIMETERS.toPoints(1); //mm increment - drawVerticalRule(g2, true, !inchOutSide, x, y, width, 0, 0, div * 5, div * 10); - drawHorizontalRule(g2, true, inchOutSide, x, y, width, 0, 0, div * 5, div * 10); - } - else { - Font f = g.getFont(); - g.setFont(f.deriveFont(f.getSize() - 2f)); - g.drawString("in cm", x - MAJOR_TICK_LENGTH, y); - g.drawString("cm", x + width + 6, y + width + 4); - g.drawString("in", x + width + 6, y + width + 18); - y += 6; - - //Draw Inches first, with 1/2", 1/4", and 1/8" tick marks. - drawVerticalRule(g2, false, inchOutSide, x, y, width, 0, div * 2, div * 4, div * 8); - drawHorizontalRule(g2, true, inchOutSide, x, y + width, width, 0, div * 2, div * 4, div * 8); - div = PrintUnit.MILLIMETERS.toPoints(1); //mm increment - //Draw cm (10mm) and 1/2 cm (5mm) marks - drawVerticalRule(g2, false, !inchOutSide, x, y, width, 0, 0, div * 5, div * 10); - drawHorizontalRule(g2, true, !inchOutSide, x, y + width, width, 0, 0, div * 5, div * 10); - } - } - - /** - * Draw a horizontal ruler. - * - * @param g the graphics context - * @param vertexAtLeft true if the horizontal/vertical vertex is oriented to the top - * @param drawTicksDown true if the ruler should draw interval tick marks to the underside of the solid ruler line - * @param x starting x position of the ruler - * @param y starting y position of the rule - * @param length the number of points in length to extend the vertical ruler - * @param tinyEveryX the number of points for each tiny division tick line; if zero or negative tiny will not be - * drawn - * @param minorEveryX the number of points for each minor division tick line; if zero or negative minor will not - * be drawn - * @param midMajorEveryX the number of points for each mid-major division tick line - * @param majorEveryX the number of points for each major division tick line (this is typically the inch or cm - * distance in points). - */ - private void drawHorizontalRule(Graphics2D g, - boolean vertexAtLeft, - boolean drawTicksDown, - int x, int y, int length, - double tinyEveryX, - double minorEveryX, - double midMajorEveryX, - double majorEveryX) { - - //Draw solid horizontal line - g.setColor(Color.black); - g.drawLine(x, y, x + length, y); - - int tiniest = drawTicksDown ? TINIEST_TICK_LENGTH : -1 * TINIEST_TICK_LENGTH; - int minor = drawTicksDown ? MINOR_TICK_LENGTH : -1 * MINOR_TICK_LENGTH; - int mid = drawTicksDown ? MID_MAJOR_TICK_LENGTH : -1 * MID_MAJOR_TICK_LENGTH; - int major = drawTicksDown ? MAJOR_TICK_LENGTH : -1 * MAJOR_TICK_LENGTH; - - //Draw vertical rule ticks for the horizontal ruler - //Draw minor ticks - int initial = x; - int end = initial + length; - double increment = tinyEveryX; - boolean lessThanEqual = true; - if (!vertexAtLeft) { - initial = x + length; - end = x; - lessThanEqual = false; - } - - if (tinyEveryX > 0) { - if (!vertexAtLeft) { - increment = -1 * increment; - } - for (double xtick = initial; lessThanEqual ? (xtick <= end) : (xtick >= end); xtick += increment) { - g.drawLine((int) xtick, y, (int) xtick, y + tiniest); - } - } - //Draw minor ticks - if (minorEveryX > 0) { - if (!vertexAtLeft) { - increment = -1 * minorEveryX; - } - else { - increment = minorEveryX; - } - for (double xtick = initial; lessThanEqual ? (xtick <= end) : (xtick >= end); xtick += increment) { - g.drawLine((int) xtick, y, (int) xtick, y + minor); - } - } - - //Draw mid-major ticks - if (midMajorEveryX > 0) { - if (!vertexAtLeft) { - increment = -1 * midMajorEveryX; - } - else { - increment = midMajorEveryX; - } - for (double xtick = initial; lessThanEqual ? (xtick <= end) : (xtick >= end); xtick += increment) { - g.drawLine((int) xtick, y, (int) xtick, y + mid); - } - } - if (!vertexAtLeft) { - increment = -1 * majorEveryX; - } - else { - increment = majorEveryX; - } - //Draw major ticks - for (double xtick = initial; lessThanEqual ? (xtick <= end) : (xtick >= end); xtick += increment) { - g.drawLine((int) xtick, y, (int) xtick, y + major); - } - - } - - /** - * Draw a vertical ruler. - * - * @param g the graphics context - * @param vertexAtTop true if the horizontal/vertical vertex is oriented to the top - * @param drawTicksRight true if the ruler should draw interval tick marks to the right side of the solid ruler - * line - * @param x starting x position of the ruler - * @param y starting y position of the rule - * @param length the number of points in length to extend the vertical ruler - * @param tinyEveryY the number of points for each tiny division tick line; if zero or negative tiny will not be - * drawn - * @param minorEveryY the number of points for each minor division tick line; if zero or negative minor will not - * be drawn - * @param midMajorEveryY the number of points for each mid-major division tick line - * @param majorEveryY the number of points for each major division tick line (this is typically the inch or cm - * distance in points). - */ - private void drawVerticalRule(Graphics2D g, - boolean vertexAtTop, - boolean drawTicksRight, int x, int y, int length, - double tinyEveryY, - double minorEveryY, - double midMajorEveryY, - double majorEveryY) { - - int tiniest = drawTicksRight ? TINIEST_TICK_LENGTH : -1 * TINIEST_TICK_LENGTH; - int minor = drawTicksRight ? MINOR_TICK_LENGTH : -1 * MINOR_TICK_LENGTH; - int mid = drawTicksRight ? MID_MAJOR_TICK_LENGTH : -1 * MID_MAJOR_TICK_LENGTH; - int major = drawTicksRight ? MAJOR_TICK_LENGTH : -1 * MAJOR_TICK_LENGTH; - - //Draw solid vertical line - g.setColor(Color.black); - g.drawLine(x, y, x, y + length); - - //Draw horizontal rule ticks for the vertical ruler - //Draw tiny ticks - int initial = y; - int end = initial + length; - double increment = tinyEveryY; - boolean lessThanEqual = true; - if (!vertexAtTop) { - initial = y + length; - end = y; - lessThanEqual = false; - } - - if (tinyEveryY > 0) { - if (!vertexAtTop) { - increment = -1 * increment; - } - for (double tick = initial; lessThanEqual ? (tick <= end) : (tick >= end); tick += increment) { - g.drawLine(x, (int) tick, x - tiniest, (int) tick); - } - } - - //Draw minor ticks - if (minorEveryY > 0) { - if (!vertexAtTop) { - increment = -1 * minorEveryY; - } - else { - increment = minorEveryY; - } - for (double tick = initial; lessThanEqual ? (tick <= end) : (tick >= end); tick += increment) { - g.drawLine(x, (int) tick, x - minor, (int) tick); - } - } - - //Draw mid-major ticks - if (!vertexAtTop) { - increment = -1 * midMajorEveryY; - } - else { - increment = midMajorEveryY; - } - for (double tick = initial; lessThanEqual ? (tick <= end) : (tick >= end); tick += increment) { - g.drawLine(x, (int) tick, x - mid, (int) tick); - } - - //Draw major ticks - if (!vertexAtTop) { - increment = -1 * majorEveryY; - } - else { - increment = majorEveryY; - } - for (double tick = initial; lessThanEqual ? (tick <= end) : (tick >= end); tick += increment) { - g.drawLine(x, (int) tick, x - major, (int) tick); - } - - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/visitor/CenteringRingStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/CenteringRingStrategy.java deleted file mode 100644 index 1df75699..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/CenteringRingStrategy.java +++ /dev/null @@ -1,270 +0,0 @@ -package net.sf.openrocket.gui.print.visitor; - -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.gui.print.AbstractPrintable; -import net.sf.openrocket.gui.print.ITextHelper; -import net.sf.openrocket.gui.print.PrintUnit; -import net.sf.openrocket.gui.print.PrintableCenteringRing; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayList; - -import java.awt.image.BufferedImage; -import java.util.List; -import java.util.Set; - -/** - * A strategy for printing a centering ring to iText. - */ -public class CenteringRingStrategy { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * The stages selected. - */ - protected Set stages; - - /** - * Strategy for fitting multiple components onto a page. - */ - protected PageFitPrintStrategy pageFitPrint; - - /** - * Constructor. - * - * @param doc The iText document - * @param theWriter The direct iText writer - * @param theStagesToVisit The stages to be visited by this strategy - */ - public CenteringRingStrategy(Document doc, PdfWriter theWriter, Set theStagesToVisit, PageFitPrintStrategy pageFit) { - document = doc; - writer = theWriter; - stages = theStagesToVisit; - pageFitPrint = pageFit; - } - - /** - * Recurse through the given rocket component. - * - * @param root the root component; all children will be visited recursively - */ - public void writeToDocument(final RocketComponent root) { - List rc = root.getChildren(); - goDeep(rc); - } - - - /** - * Recurse through the given rocket component. - * - * @param theRc an array of rocket components; all children will be visited recursively - */ - protected void goDeep(final List theRc) { - for (RocketComponent rocketComponent : theRc) { - if (rocketComponent instanceof CenteringRing) { - render((CenteringRing) rocketComponent); - } - else if (rocketComponent.getChildCount() > 0) { - goDeep(rocketComponent.getChildren()); - } - } - } - - /** - * Find the inner tubes that are physically supported by the given centering ring. Note that this only looks for - * motor mount tubes that are siblings to the centering ring. - * - * @param rc the centering ring, for which all motor mount tubes that run through it are located. - * - * @return the list of tubes found - */ - private List findMotorMount(CenteringRing rc) { - RocketComponent parent = rc.getParent(); - List siblings = parent.getChildren(); - - List mounts = new ArrayList(); - for (RocketComponent rocketComponents : siblings) { - if (rocketComponents != rc) { - if (rocketComponents instanceof InnerTube) { - InnerTube it = (InnerTube) rocketComponents; - if (overlaps(rc, it)) { - mounts.add(it); - } - } - } - } - - return mounts; - } - - /** - * Determine if the centering ring physically overlaps with the inner tube. - * - * @param one the centering ring - * @param two the inner body tube - * - * @return true if the two physically intersect, from which we infer that the centering ring supports the tube - */ - private boolean overlaps(CenteringRing one, InnerTube two) { - final double crTopPosition = one.asPositionValue(RocketComponent.Position.ABSOLUTE, one.getParent()); - final double mmTopPosition = two.asPositionValue(RocketComponent.Position.ABSOLUTE, two.getParent()); - final double crBottomPosition = one.getLength() + crTopPosition; - final double mmBottomPosition = two.getLength() + mmTopPosition; - - if (crTopPosition >= mmTopPosition && crTopPosition <= mmBottomPosition) { - return true; - } - if (crBottomPosition >= mmTopPosition && crBottomPosition <= mmBottomPosition) { - return true; - } - return false; - } - - /** - * The core behavior of this visitor. - * - * @param component the object to extract info about; a graphical image of the centering ring shape is drawn to the - * document - */ - private void render(final CenteringRing component) { - try { - AbstractPrintable pfs; - pfs = PrintableCenteringRing.create(component, findMotorMount(component)); - - java.awt.Dimension size = pfs.getSize(); - final Dimension pageSize = getPageSize(); - if (fitsOnOnePage(pageSize, size.getWidth(), size.getHeight())) { - pageFitPrint.addComponent(pfs); - } - else { - int off = (int) (PrintUnit.POINTS_PER_INCH * 0.3f); - pfs.setPrintOffset(off, off); - BufferedImage image = (BufferedImage) pfs.createImage(); - ITextHelper.renderImageAcrossPages(new Rectangle(pageSize.getWidth(), pageSize.getHeight()), - document, writer, image); - document.newPage(); - } - } - catch (DocumentException e) { - log.error("Could not render the centering ring.", e); - } - } - - /** - * Determine if the image will fit on the given page. - * - * @param pageSize the page size - * @param wImage the width of the thing to be printed - * @param hImage the height of the thing to be printed - * - * @return true if the thing to be printed will fit on a single page - */ - private boolean fitsOnOnePage(Dimension pageSize, double wImage, double hImage) { - double wPage = pageSize.getWidth(); - double hPage = pageSize.getHeight(); - - int wRatio = (int) Math.ceil(wImage / wPage); - int hRatio = (int) Math.ceil(hImage / hPage); - - return wRatio <= 1.0d && hRatio <= 1.0d; - } - - /** - * Get the dimensions of the paper page. - * - * @return an internal Dimension - */ - protected Dimension getPageSize() { - return new Dimension(document.getPageSize().getWidth(), - document.getPageSize().getHeight()); - } - - /** - * Convenience class to model a dimension. - */ - public static class Dimension { - /** - * Width, in points. - */ - public float width; - /** - * Height, in points. - */ - public float height; - /** - * Breadth, in points. - */ - public float breadth = 0f; - - /** - * Constructor. - * - * @param w width - * @param h height - */ - public Dimension(float w, float h) { - width = w; - height = h; - } - - /** - * Constructor. - * - * @param w width - * @param h height - * @param b breadth; optionally used to represent radius - */ - public Dimension(float w, float h, float b) { - width = w; - height = h; - breadth = b; - } - - /** - * Get the width. - * - * @return the width - */ - public float getWidth() { - return width; - } - - /** - * Get the height. - * - * @return the height - */ - public float getHeight() { - return height; - } - - /** - * Get the breadth. - * - * @return the breadth - */ - public float getBreadth() { - return breadth; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/print/visitor/FinMarkingGuideStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/FinMarkingGuideStrategy.java deleted file mode 100644 index f4e5a526..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/FinMarkingGuideStrategy.java +++ /dev/null @@ -1,167 +0,0 @@ -package net.sf.openrocket.gui.print.visitor; - -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.PdfContentByte; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.gui.print.FinMarkingGuide; -import net.sf.openrocket.gui.print.ITextHelper; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; - -import java.awt.*; -import java.awt.image.BufferedImage; - -/** - * A strategy for drawing a fin marking guide. As currently implemented, each body tube with a finset will have - * a marking guide. If a tube has multiple fin sets, they are combined onto one marking guide. Launch lugs are supported - * as well. - */ -public class FinMarkingGuideStrategy { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * Constructor. - * - * @param doc The iText document - * @param theWriter The direct iText writer - */ - public FinMarkingGuideStrategy(Document doc, PdfWriter theWriter) { - document = doc; - writer = theWriter; - } - - /** - * Recurse through the given rocket component. - * - * @param root the root component; all children will be visited recursively - */ - public void writeToDocument(final Rocket root) { - render(root); - } - - - /** - * The core behavior of this strategy. - * - * @param rocket the rocket to render all - */ - private void render(final Rocket rocket) { - try { - FinMarkingGuide pfs = new FinMarkingGuide(rocket); - - java.awt.Dimension size = pfs.getSize(); - final Dimension pageSize = getPageSize(); - if (fitsOnOnePage(pageSize, size.getWidth(), size.getHeight())) { - printOnOnePage(pfs); - } else { - BufferedImage image = (BufferedImage) pfs.createImage(); - ITextHelper.renderImageAcrossPages(new Rectangle(pageSize.getWidth(), pageSize.getHeight()), - document, writer, image); - } - } catch (DocumentException e) { - log.error("Could not render the fin marking guide.", e); - } - } - - /** - * Determine if the image will fit on the given page. - * - * @param pageSize the page size - * @param wImage the width of the thing to be printed - * @param hImage the height of the thing to be printed - * @return true if the thing to be printed will fit on a single page - */ - private boolean fitsOnOnePage(Dimension pageSize, double wImage, double hImage) { - double wPage = pageSize.getWidth(); - double hPage = pageSize.getHeight(); - - int wRatio = (int) Math.ceil(wImage / wPage); - int hRatio = (int) Math.ceil(hImage / hPage); - - return wRatio <= 1.0d && hRatio <= 1.0d; - } - - /** - * Print the transition. - * - * @param theMarkingGuide the fin marking guide - */ - private void printOnOnePage(final FinMarkingGuide theMarkingGuide) { - Dimension d = getPageSize(); - PdfContentByte cb = writer.getDirectContent(); - Graphics2D g2 = cb.createGraphics(d.width, d.height); - theMarkingGuide.print(g2); - g2.dispose(); - document.newPage(); - } - - /** - * Get the dimensions of the paper page. - * - * @return an internal Dimension - */ - protected Dimension getPageSize() { - return new Dimension(document.getPageSize().getWidth(), - document.getPageSize().getHeight()); - } - - /** - * Convenience class to model a dimension. - */ - class Dimension { - /** - * Width, in points. - */ - public float width; - /** - * Height, in points. - */ - public float height; - - /** - * Constructor. - * - * @param w width - * @param h height - */ - public Dimension(float w, float h) { - width = w; - height = h; - } - - /** - * Get the width. - * - * @return the width - */ - public float getWidth() { - return width; - } - - /** - * Get the height. - * - * @return the height - */ - public float getHeight() { - return height; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/print/visitor/FinSetPrintStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/FinSetPrintStrategy.java deleted file mode 100644 index 38704908..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/FinSetPrintStrategy.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * FinSetPrintStrategy.java - */ -package net.sf.openrocket.gui.print.visitor; - -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.gui.print.ITextHelper; -import net.sf.openrocket.gui.print.PrintUnit; -import net.sf.openrocket.gui.print.PrintableFinSet; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - -import java.awt.image.BufferedImage; -import java.util.List; -import java.util.Set; - -/** - * A strategy for drawing fin templates. - */ -public class FinSetPrintStrategy { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * The stages selected. - */ - protected Set stages; - - /** - * Strategy for fitting multiple components onto a page. - */ - protected PageFitPrintStrategy pageFitPrint; - - /** - * Constructor. - * - * @param doc The iText document - * @param theWriter The direct iText writer - * @param theStages The stages to be printed by this strategy - */ - public FinSetPrintStrategy(Document doc, PdfWriter theWriter, Set theStages, PageFitPrintStrategy pageFit) { - document = doc; - writer = theWriter; - stages = theStages; - pageFitPrint = pageFit; - } - - /** - * Recurse through the given rocket component. - * - * @param root the root component; all children will be printed recursively - */ - public void writeToDocument (final RocketComponent root) { - List rc = root.getChildren(); - goDeep(rc); - } - - - /** - * Recurse through the given rocket component. - * - * @param theRc an array of rocket components; all children will be printed recursively - */ - protected void goDeep (final List theRc) { - for (RocketComponent rocketComponent : theRc) { - if (rocketComponent instanceof FinSet) { - printFinSet((FinSet) rocketComponent); - } - else if (rocketComponent.getChildCount() > 0) { - goDeep(rocketComponent.getChildren()); - } - } - } - - /** - * The core behavior of this strategy. - * - * @param finSet the object to extract info about; a graphical image of the fin shape is drawn to the document - */ - private void printFinSet(final FinSet finSet) { - if (shouldPrintStage(finSet.getStageNumber())) { - try { - PrintableFinSet pfs = new PrintableFinSet(finSet); - - java.awt.Dimension finSize = pfs.getSize(); - final Dimension pageSize = getPageSize(); - if (fitsOnOnePage(pageSize, finSize.getWidth(), finSize.getHeight())) { - pageFitPrint.addComponent(pfs); - } - else { - int off = (int)(PrintUnit.POINTS_PER_INCH * 0.3f); - pfs.setPrintOffset(off, off); - BufferedImage image = (BufferedImage) pfs.createImage(); - ITextHelper.renderImageAcrossPages(new Rectangle(pageSize.getWidth(), pageSize.getHeight()), - document, writer, image); - document.newPage(); - } - } - catch (DocumentException e) { - log.error("Could not render fin.", e); - } - } - } - - /** - * Determine if the strategy's set of stage numbers (to print) contains the specified stage. - * - * @param stageNumber a stage number - * - * @return true if the strategy contains the stage number provided - */ - public boolean shouldPrintStage(int stageNumber) { - if (stages == null || stages.isEmpty()) { - return false; - } - - for (final Integer stage : stages) { - if (stage == stageNumber) { - return true; - } - } - - return false; - } - - /** - * Determine if the image will fit on the given page. - * - * @param pageSize the page size - * @param wImage the width of the thing to be printed - * @param hImage the height of the thing to be printed - * - * @return true if the thing to be printed will fit on a single page - */ - private boolean fitsOnOnePage (Dimension pageSize, double wImage, double hImage) { - double wPage = pageSize.getWidth(); - double hPage = pageSize.getHeight(); - - int wRatio = (int) Math.ceil(wImage / wPage); - int hRatio = (int) Math.ceil(hImage / hPage); - - return wRatio <= 1.0d && hRatio <= 1.0d; - } - - /** - * Get the dimensions of the paper page. - * - * @return an internal Dimension - */ - protected Dimension getPageSize () { - return new Dimension(document.getPageSize().getWidth(), - document.getPageSize().getHeight()); - } - - /** - * Convenience class to model a dimension. - */ - class Dimension { - /** Width, in points. */ - public float width; - /** Height, in points. */ - public float height; - - /** - * Constructor. - * @param w width - * @param h height - */ - public Dimension (float w, float h) { - width = w; - height = h; - } - - /** - * Get the width. - * - * @return the width - */ - public float getWidth () { - return width; - } - - /** - * Get the height. - * - * @return the height - */ - public float getHeight () { - return height; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/print/visitor/PageFitPrintStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/PageFitPrintStrategy.java deleted file mode 100644 index 10ca7351..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/PageFitPrintStrategy.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * PageFitPrintStrategy.java - */ -package net.sf.openrocket.gui.print.visitor; - -import com.itextpdf.text.Document; -import com.itextpdf.text.pdf.PdfContentByte; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.gui.print.PrintUnit; -import net.sf.openrocket.gui.print.PrintableComponent; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - -import java.awt.Graphics2D; -import java.util.ArrayList; -import java.util.Collections; -import java.util.ListIterator; -import java.util.Set; - -/** - * A strategy for drawing multiple rocket components onto as few pages as possible. - * - * @author Jason Blood - */ -public class PageFitPrintStrategy { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * The stages selected. - */ - protected Set stages; - - protected ArrayList componentToPrint; - - /** - * Constructor. - * - * @param doc The iText document - * @param theWriter The direct iText writer - */ - public PageFitPrintStrategy(Document doc, PdfWriter theWriter) { - document = doc; - writer = theWriter; - componentToPrint = new ArrayList(); - } - - /** - * Add a component we want to print. - * - * @param component The component to add for printing - */ - public void addComponent(PrintableComponent component) { - componentToPrint.add(component); - } - - /** - * Recurse through the given rocket component. - * - * @param root the root component; all children will be printed recursively - */ - public void writeToDocument (final RocketComponent root) { - fitPrintComponents(); - } - - /** - * Iterate through the components to print fitting them onto pages as best possible. - */ - private void fitPrintComponents() { - final Dimension pageSize = getPageSize(); - double wPage = pageSize.getWidth(); - double hPage = pageSize.getHeight(); - int marginX = (int)(PrintUnit.POINTS_PER_INCH * 0.3f); - int marginY = (int)(PrintUnit.POINTS_PER_INCH * 0.3f); - PdfContentByte cb = writer.getDirectContent(); - - Collections.sort(componentToPrint); - - while (componentToPrint.size() > 0) { - int pageY = marginY; - Boolean anyAddedToRow; - - Graphics2D g2 = cb.createGraphics(pageSize.width, pageSize.height); - - do { - // Fill the row - int rowX = marginX; - int rowY = pageY; - ListIterator entry = componentToPrint.listIterator(); - anyAddedToRow = false; - - while (entry.hasNext()) { - PrintableComponent component = entry.next(); - java.awt.Dimension dim = component.getSize(); - if ((rowX + dim.width + marginX < wPage) && (rowY + dim.height + marginY < hPage)) { - component.setPrintOffset(rowX, rowY); - rowX += dim.width + marginX; - if (rowY + dim.height + marginY > pageY) { - pageY = rowY + dim.height + marginY; - } - entry.remove(); - component.print(g2); - anyAddedToRow = true; - } - } - pageY += marginY; - } while (anyAddedToRow); - - g2.dispose(); - document.newPage(); - } - } - - /** - * Get the dimensions of the paper page. - * - * @return an internal Dimension - */ - protected Dimension getPageSize () { - return new Dimension(document.getPageSize().getWidth(), - document.getPageSize().getHeight()); - } - - /** - * Convenience class to model a dimension. - */ - class Dimension { - /** Width, in points. */ - public float width; - /** Height, in points. */ - public float height; - - /** - * Constructor. - * @param w width - * @param h height - */ - public Dimension (float w, float h) { - width = w; - height = h; - } - - /** - * Get the width. - * - * @return the width - */ - public float getWidth () { - return width; - } - - /** - * Get the height. - * - * @return the height - */ - public float getHeight () { - return height; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/print/visitor/PartsDetailVisitorStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/PartsDetailVisitorStrategy.java deleted file mode 100644 index c155d0cd..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/PartsDetailVisitorStrategy.java +++ /dev/null @@ -1,753 +0,0 @@ -/* - * PartsDetailVisitorStrategy.java - */ -package net.sf.openrocket.gui.print.visitor; - -import java.util.List; -import java.util.Set; - -import javax.swing.ImageIcon; - -import net.sf.openrocket.gui.main.ComponentIcons; -import net.sf.openrocket.gui.print.ITextHelper; -import net.sf.openrocket.gui.print.PrintUtilities; -import net.sf.openrocket.gui.print.PrintableFinSet; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.BodyComponent; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.Coaxial; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RadiusRingComponent; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.ShockCord; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; - -import com.itextpdf.text.Chunk; -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Element; -import com.itextpdf.text.Font; -import com.itextpdf.text.Image; -import com.itextpdf.text.Paragraph; -import com.itextpdf.text.Phrase; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; -import com.itextpdf.text.pdf.draw.VerticalPositionMark; - -/** - * A visitor strategy for creating documentation about parts details. - */ -public class PartsDetailVisitorStrategy { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The number of columns in the table. - */ - private static final int TABLE_COLUMNS = 7; - - /** - * The parts detail is represented as an iText table. - */ - PdfPTable grid; - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * The stages selected. - */ - protected Set stages; - - /** - * State variable to track the level of hierarchy. - */ - protected int level = 0; - - private static final String LINES = "Lines: "; - private static final String MASS = "Mass: "; - private static final String LEN = "Len: "; - private static final String THICK = "Thick: "; - private static final String INNER = "in "; - private static final String DIAMETER = "Dia"; - private static final String OUTER = "out"; - private static final String WIDTH = "Width"; - private static final String LENGTH = "Length"; - private static final String SHROUD_LINES = "Shroud Lines"; - private static final String AFT_DIAMETER = "Aft Dia: "; - private static final String FORE_DIAMETER = "Fore Dia: "; - private static final String PARTS_DETAIL = "Parts Detail"; - - /** - * Construct a strategy for visiting a parts hierarchy for the purposes of collecting details on those parts. - * - * @param doc The iText document - * @param theWriter The direct iText writer - * @param theStagesToVisit The stages to be visited by this strategy - */ - public PartsDetailVisitorStrategy (Document doc, PdfWriter theWriter, Set theStagesToVisit) { - document = doc; - writer = theWriter; - stages = theStagesToVisit; - PrintUtilities.addText(doc, PrintUtilities.BIG_BOLD, PARTS_DETAIL); - } - - /** - * Print the parts detail. - * - * @param root the root component - */ - public void writeToDocument (final RocketComponent root) { - goDeep(root.getChildren()); - } - - /** - * Recurse through the given rocket component. - * - * @param theRc an array of rocket components; all children will be visited recursively - */ - protected void goDeep (final List theRc) { - level++; - for (RocketComponent rocketComponent : theRc) { - handle(rocketComponent); - } - level--; - } - - /** - * Add a line to the detail report based upon the type of the component. - * - * @param component the component to print the detail for - */ - private void handle (RocketComponent component) { - //This ugly if-then-else construct is not object oriented. Originally it was an elegant, and very OO savy, design - //using the Visitor pattern. Unfortunately, it was misunderstood and was removed. - if (component instanceof Stage) { - try { - if (grid != null) { - document.add(grid); - } - document.add(ITextHelper.createPhrase(component.getName())); - grid = new PdfPTable(TABLE_COLUMNS); - grid.setWidthPercentage(100); - grid.setHorizontalAlignment(Element.ALIGN_LEFT); - } - catch (DocumentException e) { - } - - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof LaunchLug) { - LaunchLug ll = (LaunchLug) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - - grid.addCell(createMaterialCell(ll.getMaterial())); - grid.addCell(createOuterInnerDiaCell(ll)); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - } - else if (component instanceof NoseCone) { - NoseCone nc = (NoseCone) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(nc.getMaterial())); - grid.addCell(ITextHelper.createCell(nc.getType().getName(), PdfPCell.BOTTOM)); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof Transition) { - Transition tran = (Transition) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(tran.getMaterial())); - - Chunk fore = new Chunk(FORE_DIAMETER + toLength(tran.getForeRadius() * 2)); - fore.setFont(PrintUtilities.NORMAL); - Chunk aft = new Chunk(AFT_DIAMETER + toLength(tran.getAftRadius() * 2)); - aft.setFont(PrintUtilities.NORMAL); - final PdfPCell cell = ITextHelper.createCell(); - cell.addElement(fore); - cell.addElement(aft); - grid.addCell(cell); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof BodyTube) { - BodyTube bt = (BodyTube) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(bt.getMaterial())); - grid.addCell(createOuterInnerDiaCell(bt)); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof FinSet) { - handleFins((FinSet) component); - } - else if (component instanceof BodyComponent) { - grid.addCell(component.getName()); - grid.completeRow(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof ExternalComponent) { - ExternalComponent ext = (ExternalComponent) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - - grid.addCell(createMaterialCell(ext.getMaterial())); - grid.addCell(ITextHelper.createCell()); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof InnerTube) { - InnerTube it = (InnerTube) component; - grid.addCell(iconToImage(component)); - final PdfPCell pCell = createNameCell(component.getName(), true, component.getPresetComponent()); - grid.addCell(pCell); - grid.addCell(createMaterialCell(it.getMaterial())); - grid.addCell(createOuterInnerDiaCell(it)); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof RadiusRingComponent) { - RadiusRingComponent rrc = (RadiusRingComponent) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(rrc.getMaterial())); - if (component instanceof Bulkhead) { - grid.addCell(createDiaCell(rrc.getOuterRadius()*2)); - } - else { - grid.addCell(createOuterInnerDiaCell(rrc)); - } - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof RingComponent) { - RingComponent ring = (RingComponent) component; - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(ring.getMaterial())); - grid.addCell(createOuterInnerDiaCell(ring)); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof ShockCord) { - ShockCord ring = (ShockCord) component; - PdfPCell cell = ITextHelper.createCell(); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setPaddingBottom(12f); - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(ring.getMaterial())); - grid.addCell(cell); - grid.addCell(createLengthCell(ring.getCordLength())); - grid.addCell(createMassCell(component.getMass())); - } - else if (component instanceof Parachute) { - Parachute chute = (Parachute) component; - PdfPCell cell = ITextHelper.createCell(); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setPaddingBottom(12f); - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(chute.getMaterial())); -// if (chute.hasSpillHole()) { -// grid.addCell(createOuterInnerDiaCell(chute.getDiameter()/2, chute.getSpillHoleDiameter()/2)); -// } -// else { - grid.addCell(createDiaCell(chute.getDiameter())); -// } - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - - grid.addCell(iconToImage(null)); - grid.addCell(createNameCell(SHROUD_LINES, true, component.getPresetComponent())); - grid.addCell(createMaterialCell(chute.getLineMaterial())); - grid.addCell(createLinesCell(chute.getLineCount())); - grid.addCell(createLengthCell(chute.getLineLength())); - grid.addCell(cell); - } - else if (component instanceof Streamer) { - Streamer ring = (Streamer) component; - PdfPCell cell = ITextHelper.createCell(); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setPaddingBottom(12f); - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(ring.getMaterial())); - grid.addCell(createStrip(ring)); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - } - else if (component instanceof RecoveryDevice) { - RecoveryDevice device = (RecoveryDevice) component; - PdfPCell cell = ITextHelper.createCell(); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setPaddingBottom(12f); - grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); - grid.addCell(createMaterialCell(device.getMaterial())); - grid.addCell(cell); - grid.addCell(createLengthCell(component.getLength())); - grid.addCell(createMassCell(component.getMass())); - } - else if (component instanceof MassObject) { - PdfPCell cell = ITextHelper.createCell(); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setPaddingBottom(12f); - - grid.addCell(iconToImage(component)); - final PdfPCell nameCell = createNameCell(component.getName(), true, component.getPresetComponent()); - nameCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - nameCell.setPaddingBottom(12f); - grid.addCell(nameCell); - grid.addCell(cell); - grid.addCell(createDiaCell(((MassObject) component).getRadius() * 2)); - grid.addCell(cell); - grid.addCell(createMassCell(component.getMass())); - } - } - - /** - * Close the strategy by adding the last grid to the document. - */ - public void close () { - try { - if (grid != null) { - document.add(grid); - } - } - catch (DocumentException e) { - log.error("Could not write last cell to document.", e); - } - } - - /** - * Create a cell to document an outer 'diameter'. This is used for components that have no inner diameter, such as - * a solid parachute or bulkhead. - * - * @param diameter the diameter in default length units - * - * @return a formatted cell containing the diameter - */ - private PdfPCell createDiaCell (final double diameter) { - PdfPCell result = new PdfPCell(); - Phrase p = new Phrase(); - p.setLeading(12f); - result.setVerticalAlignment(Element.ALIGN_TOP); - result.setBorder(Rectangle.BOTTOM); - Chunk c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(DIAMETER); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.SMALL); - c.append(OUTER); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(" " + toLength(diameter)); - p.add(c); - result.addElement(p); - return result; - } - - /** - * Create a PDF cell for a streamer. - * - * @param component a component that is a Coaxial - * @return the PDF cell that has the streamer documented - */ - private PdfPCell createStrip (final Streamer component) { - PdfPCell result = new PdfPCell(); - Phrase p = new Phrase(); - p.setLeading(12f); - result.setVerticalAlignment(Element.ALIGN_TOP); - result.setBorder(Rectangle.BOTTOM); - Chunk c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(LENGTH); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(" " + toLength(component.getStripLength())); - p.add(c); - result.addElement(p); - - Phrase pw = new Phrase(); - pw.setLeading(14f); - c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(WIDTH); - pw.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(" " + toLength(component.getStripWidth())); - pw.add(c); - result.addElement(pw); - - return result; - } - - /** - * Create a PDF cell that documents both an outer and an inner diameter of a component. - * - * @param component a component that is a Coaxial - * - * @return the PDF cell that has the outer and inner diameters documented - */ - private PdfPCell createOuterInnerDiaCell (final Coaxial component) { - return createOuterInnerDiaCell(component, INNER); - } - - /** - * Create a PDF cell that documents both an outer and an inner diameter of a component. - * - * @param component a component that is a Coaxial - * @param innerLabel the label to use for the inner label subscript - * - * @return the PDF cell that has the outer and inner diameters documented - */ - private PdfPCell createOuterInnerDiaCell (final Coaxial component, final String innerLabel) { - return createOuterInnerDiaCell(component.getOuterRadius(), component.getInnerRadius(), innerLabel); - } - - /** - * Create a PDF cell that documents both an outer and an inner diameter of a component. - * - * @param outerRadius the outer radius - * @param innerRadius the inner radius - * @param innerLabel the label to use for the inner label subscript - * - * @return the PDF cell that has the outer and inner diameters documented - */ - private PdfPCell createOuterInnerDiaCell (final double outerRadius, final double innerRadius, final String innerLabel) { - - PdfPCell result = new PdfPCell(); - Phrase p = new Phrase(); - p.setLeading(12f); - result.setVerticalAlignment(Element.ALIGN_TOP); - result.setBorder(Rectangle.BOTTOM); - Chunk c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(DIAMETER); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.SMALL); - c.append(OUTER); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(" " + toLength(outerRadius * 2)); - p.add(c); - createInnerDiaCell(innerRadius, result, innerLabel); - result.addElement(p); - return result; - } - - /** - * Add inner diameter data to a cell. - * - * @param innerRadius the inner radius - * @param cell the PDF cell to add the inner diameter data to - * @param innerLabel the label to use for the inner label subscript - */ - private void createInnerDiaCell (final double innerRadius, PdfPCell cell, final String innerLabel) { - Phrase p = new Phrase(); - p.setLeading(14f); - Chunk c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(DIAMETER); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.SMALL); - c.append(innerLabel); - p.add(c); - - c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(" " + toLength(innerRadius * 2)); - p.add(c); - cell.addElement(p); - } - - /** - * Add PDF cells for a fin set. - * - * @param theFinSet the fin set - */ - private void handleFins (FinSet theFinSet) { - - Image img = null; - java.awt.Image awtImage = new PrintableFinSet(theFinSet).createImage(); - - try { - img = Image.getInstance(writer, awtImage, 0.25f); - } - catch (Exception e) { - log.error("Could not write image to document.", e); - } - - grid.addCell(iconToImage(theFinSet)); - grid.addCell(createNameCell(theFinSet.getName() + " (" + theFinSet.getFinCount() + ")", true)); - grid.addCell(createMaterialCell(theFinSet.getMaterial())); - grid.addCell(ITextHelper.createCell(THICK + toLength(theFinSet.getThickness()), PdfPCell.BOTTOM)); - final PdfPCell pCell = new PdfPCell(); - pCell.setBorder(Rectangle.BOTTOM); - pCell.addElement(img); - - grid.addCell(ITextHelper.createCell()); - grid.addCell(createMassCell(theFinSet.getMass())); - - List rc = theFinSet.getChildren(); - goDeep(rc); - } - - /** - * Create a length formatted cell. - * - * @param length the length, in default length units - * - * @return a PdfPCell that is formatted with the length - */ - protected PdfPCell createLengthCell (double length) { - return ITextHelper.createCell(LEN + toLength(length), PdfPCell.BOTTOM); - } - - /** - * Create a mass formatted cell. - * - * @param mass the mass, in default mass units - * - * @return a PdfPCell that is formatted with the mass - */ - protected PdfPCell createMassCell (double mass) { - return ITextHelper.createCell(MASS + toMass(mass), PdfPCell.BOTTOM); - } - - /** - * Create a (shroud) line count formatted cell. - * - * @param count the number of shroud lines - * - * @return a PdfPCell that is formatted with the line count - */ - protected PdfPCell createLinesCell (int count) { - return ITextHelper.createCell(LINES + count, PdfPCell.BOTTOM); - } - - /** - * Create a cell formatted for a name (or any string for that matter). - * - * @param v the string to format into a PDF cell - * @param withIndent if true, then an indention is made scaled to the level of the part in the parent hierarchy - * - * @return a PdfPCell that is formatted with the string v - */ - protected PdfPCell createNameCell (String v, boolean withIndent) { - return createNameCell(v, withIndent, null); - } - - /** - * Create a cell formatted for a name (or any string for that matter). - * - * @param v the string to format into a PDF cell - * @param withIndent if true, then an indention is made scaled to the level of the part in the parent hierarchy - * @param preset the component's preset, if it has one - * - * @return a PdfPCell that is formatted with the string v - */ - protected PdfPCell createNameCell (String v, boolean withIndent, ComponentPreset preset) { - PdfPCell result = new PdfPCell(); - result.setColspan(2); - result.setBorder(Rectangle.BOTTOM); - Paragraph para = new Paragraph(); - para.setLeading(12f, 0); - Chunk c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - Chunk tab1 = - new Chunk(new VerticalPositionMark(), (level - 2) * 10, true); - - if (withIndent) { - para.add(new Chunk(tab1)); - } - c.append(v); - para.add(c); - - //Add the preset's manufacturer and part no in a subscript font. - if (preset != null) { - para.add(Chunk.NEWLINE); - c = new Chunk(); - if (withIndent) { - para.add(new Chunk(tab1)); - } - c.setFont(PrintUtilities.SMALL); - StringBuffer sb = new StringBuffer(); - sb.append(preset.getManufacturer()).append(" ").append(preset.getPartNo()); - c.append(sb.toString()); - para.add(c); - } - result.addElement(para); - return result; - } - - /** - * Create a cell that describes a material. - * - * @param material the material - * - * @return a PdfPCell that is formatted with a description of the material - */ - protected PdfPCell createMaterialCell (Material material) { - PdfPCell cell = ITextHelper.createCell(); - cell.setLeading(13f, 0); - - Chunk c = new Chunk(); - c.setFont(PrintUtilities.NORMAL); - c.append(toMaterialName(material)); - cell.addElement(c); - Chunk density = new Chunk(); - density.setFont(PrintUtilities.SMALL); - density.append(toMaterialDensity(material)); - cell.addElement(density); - return cell; - } - - /** - * Get the icon of the particular type of rocket component and conver it to an image in a PDF cell. - * - * @param visitable the rocket component to create a cell with it's image - * - * @return a PdfPCell that is just an image that can be put into a PDF - */ - protected PdfPCell iconToImage (final RocketComponent visitable) { - if (visitable != null) { - final ImageIcon icon = (ImageIcon) ComponentIcons.getLargeIcon(visitable.getClass()); - try { - if (icon != null) { - Image im = Image.getInstance(icon.getImage(), null); - if (im != null) { - im.scaleToFit(icon.getIconWidth() * 0.6f, icon.getIconHeight() * 0.6f); - PdfPCell cell = new PdfPCell(im); - cell.setFixedHeight(icon.getIconHeight() * 0.6f); - cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setBorder(PdfPCell.NO_BORDER); - return cell; - } - } - } - catch (Exception e) { - } - } - PdfPCell cell = new PdfPCell(); - cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); - cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); - cell.setBorder(PdfPCell.NO_BORDER); - return cell; - } - - /** - * Format the length as a displayable string. - * - * @param length the length (assumed to be in default length units) - * - * @return a string representation of the length with unit abbreviation - */ - protected String toLength (double length) { - final Unit defaultUnit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - return defaultUnit.toStringUnit(length); - } - - /** - * Format the mass as a displayable string. - * - * @param mass the mass (assumed to be in default mass units) - * - * @return a string representation of the mass with mass abbreviation - */ - protected String toMass (double mass) { - final Unit defaultUnit = UnitGroup.UNITS_MASS.getDefaultUnit(); - return defaultUnit.toStringUnit(mass); - } - - /** - * Get a displayable string of the material's name. - * - * @param material the material to output - * - * @return the material name - */ - protected String toMaterialName (Material material) { - return material.getName(); - } - - /** - * Format the material density as a displayable string. - * - * @param material the material to output - * - * @return a string representation of the material density - */ - protected String toMaterialDensity (Material material) { - return " (" + material.getType().getUnitGroup().getDefaultUnit().toStringUnit(material.getDensity()) + ")"; - } - -} diff --git a/core/src/net/sf/openrocket/gui/print/visitor/PartsListVisitorStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/PartsListVisitorStrategy.java deleted file mode 100644 index e8ecc0ba..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/PartsListVisitorStrategy.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * PartsListVisitorStrategy.java - */ -package net.sf.openrocket.gui.print.visitor; - -import com.itextpdf.text.Document; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.rocketcomponent.*; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A visitor strategy for creating documentation about a parts list. - */ -public class PartsListVisitorStrategy { - - /** - * Accumulator for parts data. - */ - private Map crap = new HashMap(); - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * The stages selected. - */ - protected Set stages; - - - /** - * Construct a strategy for visiting a parts hierarchy for the purposes of collecting details on those parts. - * - * @param doc The iText document - * @param theWriter The direct iText writer - * @param theStagesToVisit The stages to be visited by this strategy - */ - public PartsListVisitorStrategy (Document doc, PdfWriter theWriter, Set theStagesToVisit) { - document = doc; - writer = theWriter; - stages = theStagesToVisit; - } - - - /** - * Print the parts detail. - * - * @param root the root component - */ - public void doVisit (final RocketComponent root) { - goDeep(root.getChildren()); - } - - /** - * Recurse through the given rocket component. - * - * @param theRc an array of rocket components; all children will be visited recursively - */ - protected void goDeep (final List theRc) { - for (RocketComponent rocketComponent : theRc) { - doIt(rocketComponent); - } - } - - /** - * {@inheritDoc} - */ - private void doIt (final RocketComponent component) { - if (component instanceof InnerTube) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof LaunchLug) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - } - - else if (component instanceof NoseCone) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof Transition) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof RadiusRingComponent) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof RingComponent) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof BodyTube) { - final PartsAccumulator key = new PartsAccumulator(component); - PartsAccumulator pa = crap.get(key); - if (pa == null) { - pa = key; - crap.put(pa, pa); - } - pa.increment(); - List rc = component.getChildren(); - goDeep(rc); - } - else if (component instanceof TrapezoidFinSet) { - } - else if (component instanceof EllipticalFinSet) { - } - else if (component instanceof FreeformFinSet) { - } - } - - - /** - * {@inheritDoc} - */ - public void close () { - for (PartsAccumulator partsAccumulator : crap.keySet()) { - System.err.println(partsAccumulator.component.getComponentName() + " " + partsAccumulator.quantity); - } - } - -} - -class PartsAccumulator { - - int quantity = 0; - - RocketComponent component; - - PartsAccumulator (RocketComponent theComponent) { - component = theComponent; - } - - void increment () { - quantity++; - } - - int quantity () { - return quantity; - } - - @Override - public boolean equals (final Object o1) { - if (this == o1) { - return true; - } - - RocketComponent that; - if (o1 instanceof net.sf.openrocket.gui.print.visitor.PartsAccumulator) { - that = ((net.sf.openrocket.gui.print.visitor.PartsAccumulator) o1).component; - } - else if (o1 instanceof RocketComponent) { - that = (RocketComponent) o1; - } - else { - return false; - } - - if (this.component.getClass().equals(that.getClass())) { - //If - if (that.getLength() == this.component.getLength()) { - if (that.getMass() == this.component.getMass()) { - return true; - } - } - if (this.component instanceof Coaxial && - that instanceof Coaxial) { - Coaxial cThis = (Coaxial) this.component; - Coaxial cThat = (Coaxial) that; - if (cThis.getInnerRadius() == cThat.getInnerRadius() && - cThis.getOuterRadius() == cThat.getOuterRadius()) { - return true; - } - } - return false; - } - return false; - } - - @Override - public int hashCode () { - return component.getComponentName().hashCode(); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java deleted file mode 100644 index b6f1ee04..00000000 --- a/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java +++ /dev/null @@ -1,214 +0,0 @@ -package net.sf.openrocket.gui.print.visitor; - -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Rectangle; -import com.itextpdf.text.pdf.PdfWriter; -import net.sf.openrocket.gui.print.AbstractPrintable; -import net.sf.openrocket.gui.print.ITextHelper; -import net.sf.openrocket.gui.print.PrintUnit; -import net.sf.openrocket.gui.print.PrintableNoseCone; -import net.sf.openrocket.gui.print.PrintableTransition; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.startup.Application; - -import java.awt.image.BufferedImage; -import java.util.List; -import java.util.Set; - -/** - * A strategy for drawing transition/shroud/nose cone templates. - */ -public class TransitionStrategy { - - /** - * The logger. - */ - private static final LogHelper log = Application.getLogger(); - - /** - * The iText document. - */ - protected Document document; - - /** - * The direct iText writer. - */ - protected PdfWriter writer; - - /** - * The stages selected. - */ - protected Set stages; - - /** - * Strategy for fitting multiple components onto a page. - */ - protected PageFitPrintStrategy pageFitPrint; - - /** - * Constructor. - * - * @param doc The iText document - * @param theWriter The direct iText writer - * @param theStagesToVisit The stages to be visited by this strategy - */ - public TransitionStrategy(Document doc, PdfWriter theWriter, Set theStagesToVisit, PageFitPrintStrategy pageFit) { - document = doc; - writer = theWriter; - stages = theStagesToVisit; - pageFitPrint = pageFit; - } - - /** - * Recurse through the given rocket component. - * - * @param root the root component; all children will be visited recursively - * @param noseCones nose cones are a special form of a transition; if true, then print nose cones - * - * @return true if a transition/nosecone was rendered - */ - public boolean writeToDocument(final RocketComponent root, boolean noseCones) { - List rc = root.getChildren(); - return goDeep(rc, noseCones); - } - - - /** - * Recurse through the given rocket component. - * - * @param theRc an array of rocket components; all children will be visited recursively - * @param noseCones nose cones are a special form of a transition; if true, then print nose cones - * - * @return true if a transition/nosecone was rendered - */ - protected boolean goDeep(final List theRc, boolean noseCones) { - for (RocketComponent rocketComponent : theRc) { - if (rocketComponent instanceof NoseCone) { - if (noseCones) { - return render((Transition) rocketComponent); - } - } - else if (rocketComponent instanceof Transition && !noseCones) { - return render((Transition) rocketComponent); - } - else if (rocketComponent.getChildCount() > 0) { - return goDeep(rocketComponent.getChildren(), noseCones); - } - } - return false; - } - - /** - * The core behavior of this visitor. - * - * @param component the object to extract info about; a graphical image of the transition shape is drawn to the - * document - * - * @return true, always - */ - private boolean render(final Transition component) { - try { - AbstractPrintable pfs; - if (component instanceof NoseCone) { - pfs = new PrintableNoseCone((NoseCone) component); - } - else { - pfs = new PrintableTransition(component); - } - - java.awt.Dimension size = pfs.getSize(); - final Dimension pageSize = getPageSize(); - if (fitsOnOnePage(pageSize, size.getWidth(), size.getHeight())) { - pageFitPrint.addComponent(pfs); - } - else { - int off = (int) (PrintUnit.POINTS_PER_INCH * 0.3f); - pfs.setPrintOffset(off, off); - BufferedImage image = (BufferedImage) pfs.createImage(); - ITextHelper.renderImageAcrossPages(new Rectangle(pageSize.getWidth(), pageSize.getHeight()), - document, writer, image); - document.newPage(); - } - } - catch (DocumentException e) { - log.error("Could not render the transition.", e); - } - return true; - } - - /** - * Determine if the image will fit on the given page. - * - * @param pageSize the page size - * @param wImage the width of the thing to be printed - * @param hImage the height of the thing to be printed - * - * @return true if the thing to be printed will fit on a single page - */ - private boolean fitsOnOnePage(Dimension pageSize, double wImage, double hImage) { - double wPage = pageSize.getWidth(); - double hPage = pageSize.getHeight(); - - int wRatio = (int) Math.ceil(wImage / wPage); - int hRatio = (int) Math.ceil(hImage / hPage); - - return wRatio <= 1.0d && hRatio <= 1.0d; - } - - /** - * Get the dimensions of the paper page. - * - * @return an internal Dimension - */ - protected Dimension getPageSize() { - return new Dimension(document.getPageSize().getWidth(), - document.getPageSize().getHeight()); - } - - /** - * Convenience class to model a dimension. - */ - class Dimension { - /** - * Width, in points. - */ - public float width; - /** - * Height, in points. - */ - public float height; - - /** - * Constructor. - * - * @param w width - * @param h height - */ - public Dimension(float w, float h) { - width = w; - height = h; - } - - /** - * Get the width. - * - * @return the width - */ - public float getWidth() { - return width; - } - - /** - * Get the height. - * - * @return the height - */ - public float getHeight() { - return height; - } - } -} diff --git a/core/src/net/sf/openrocket/gui/rocketfigure/BodyTubeShapes.java b/core/src/net/sf/openrocket/gui/rocketfigure/BodyTubeShapes.java deleted file mode 100644 index aa299490..00000000 --- a/core/src/net/sf/openrocket/gui/rocketfigure/BodyTubeShapes.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.sf.openrocket.gui.rocketfigure; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Transformation; - -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Rectangle2D; - - -public class BodyTubeShapes extends RocketComponentShapes { - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - net.sf.openrocket.rocketcomponent.BodyTube tube = (net.sf.openrocket.rocketcomponent.BodyTube)component; - - double length = tube.getLength(); - double radius = tube.getOuterRadius(); - Coordinate[] start = transformation.transform(tube.toAbsolute(new Coordinate(0,0,0))); - - Shape[] s = new Shape[start.length]; - for (int i=0; i < start.length; i++) { - s[i] = new Rectangle2D.Double(start[i].x*S,(start[i].y-radius)*S, - length*S,2*radius*S); - } - return s; - } - - - public static Shape[] getShapesBack(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - net.sf.openrocket.rocketcomponent.BodyTube tube = (net.sf.openrocket.rocketcomponent.BodyTube)component; - - double or = tube.getOuterRadius(); - - Coordinate[] start = transformation.transform(tube.toAbsolute(new Coordinate(0,0,0))); - - Shape[] s = new Shape[start.length]; - for (int i=0; i < start.length; i++) { - s[i] = new Ellipse2D.Double((start[i].z-or)*S,(start[i].y-or)*S,2*or*S,2*or*S); - } - return s; - } - - -} diff --git a/core/src/net/sf/openrocket/gui/rocketfigure/FinSetShapes.java b/core/src/net/sf/openrocket/gui/rocketfigure/FinSetShapes.java deleted file mode 100644 index 0eb856f5..00000000 --- a/core/src/net/sf/openrocket/gui/rocketfigure/FinSetShapes.java +++ /dev/null @@ -1,297 +0,0 @@ -package net.sf.openrocket.gui.rocketfigure; - -import java.awt.Shape; -import java.awt.geom.Path2D; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Transformation; - - -public class FinSetShapes extends RocketComponentShapes { - - // TODO: LOW: Clustering is ignored (FinSet cannot currently be clustered) - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - net.sf.openrocket.rocketcomponent.FinSet finset = (net.sf.openrocket.rocketcomponent.FinSet)component; - - - int fins = finset.getFinCount(); - Transformation cantRotation = finset.getCantRotation(); - Transformation baseRotation = finset.getBaseRotationTransformation(); - Transformation finRotation = finset.getFinRotationTransformation(); - - Coordinate finPoints[] = finset.getFinPointsWithTab(); - - - // TODO: MEDIUM: sloping radius - double radius = finset.getBodyRadius(); - - // Translate & rotate the coordinates - for (int i=0; i 0; maxIndex--) { - if (points[maxIndex-1].y < points[maxIndex].y) - break; - } - - transformPoints(points,cantRotation); - transformPoints(points,new Transformation(0,radius,0)); - transformPoints(points,baseRotation); - - - sidePoints = new Coordinate[points.length]; - backPoints = new Coordinate[2*(points.length-maxIndex)]; - double sign; - if (finset.getCantAngle() > 0) { - sign = 1.0; - } else { - sign = -1.0; - } - - // Calculate points for the side panel - for (i=0; i < points.length; i++) { - sidePoints[i] = points[i].add(0,0,sign*thickness/2); - } - - // Calculate points for the back portion - i=0; - for (int j=points.length-1; j >= maxIndex; j--, i++) { - backPoints[i] = points[j].add(0,0,sign*thickness/2); - } - for (int j=maxIndex; j <= points.length-1; j++, i++) { - backPoints[i] = points[j].add(0,0,-sign*thickness/2); - } - - // Generate shapes - Shape[] s; - if (thickness > 0.0005) { - - s = new Shape[fins*2]; - for (int fin=0; fin= 0.0012) && (ir > 0)) { - // Draw outer and inner - s = new Shape[start.length*2]; - for (int i=0; i < start.length; i++) { - s[2*i] = new Rectangle2D.Double(start[i].x*S,(start[i].y-or)*S, - length*S,2*or*S); - s[2*i+1] = new Rectangle2D.Double(start[i].x*S,(start[i].y-ir)*S, - length*S,2*ir*S); - } - } else { - // Draw only outer - s = new Shape[start.length]; - for (int i=0; i < start.length; i++) { - s[i] = new Rectangle2D.Double(start[i].x*S,(start[i].y-or)*S, - length*S,2*or*S); - } - } - return s; - } - - - public static Shape[] getShapesBack(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - net.sf.openrocket.rocketcomponent.RingComponent tube = (net.sf.openrocket.rocketcomponent.RingComponent)component; - Shape[] s; - - double or = tube.getOuterRadius(); - double ir = tube.getInnerRadius(); - - - Coordinate[] start = transformation.transform(tube.toAbsolute(new Coordinate(0,0,0))); - - if ((ir < or) && (ir > 0)) { - // Draw inner and outer - s = new Shape[start.length*2]; - for (int i=0; i < start.length; i++) { - s[2*i] = new Ellipse2D.Double((start[i].z-or)*S, (start[i].y-or)*S, - 2*or*S, 2*or*S); - s[2*i+1] = new Ellipse2D.Double((start[i].z-ir)*S, (start[i].y-ir)*S, - 2*ir*S, 2*ir*S); - } - } else { - // Draw only outer - s = new Shape[start.length]; - for (int i=0; i < start.length; i++) { - s[i] = new Ellipse2D.Double((start[i].z-or)*S,(start[i].y-or)*S,2*or*S,2*or*S); - } - } - return s; - } - -} diff --git a/core/src/net/sf/openrocket/gui/rocketfigure/RocketComponentShapes.java b/core/src/net/sf/openrocket/gui/rocketfigure/RocketComponentShapes.java deleted file mode 100644 index 43096273..00000000 --- a/core/src/net/sf/openrocket/gui/rocketfigure/RocketComponentShapes.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.gui.rocketfigure; - - -import java.awt.Shape; - -import net.sf.openrocket.gui.scalefigure.RocketFigure; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Transformation; - - -/** - * A catch-all, no-operation drawing component. - */ -public class RocketComponentShapes { - - protected static final double S = RocketFigure.EXTRA_SCALE; - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation t) { - // no-op - Application.getExceptionHandler().handleErrorCondition("ERROR: RocketComponent.getShapesSide called with " - + component); - return new Shape[0]; - } - - public static Shape[] getShapesBack(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation t) { - // no-op - Application.getExceptionHandler().handleErrorCondition("ERROR: RocketComponent.getShapesBack called with " - +component); - return new Shape[0]; - } - - -} diff --git a/core/src/net/sf/openrocket/gui/rocketfigure/SymmetricComponentShapes.java b/core/src/net/sf/openrocket/gui/rocketfigure/SymmetricComponentShapes.java deleted file mode 100644 index 791057c7..00000000 --- a/core/src/net/sf/openrocket/gui/rocketfigure/SymmetricComponentShapes.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.sf.openrocket.gui.rocketfigure; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Transformation; - -import java.awt.*; -import java.awt.geom.Path2D; -import java.util.ArrayList; - - -public class SymmetricComponentShapes extends RocketComponentShapes { - private static final int MINPOINTS = 91; - private static final double ACCEPTABLE_ANGLE = Math.cos(7.0 * Math.PI / 180.0); - - // TODO: HIGH: adaptiveness sucks, remove it. - - // TODO: LOW: Uses only first component of cluster (not currently clusterable) - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - return getShapesSide(component, transformation, S); - } - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation, final double scaleFactor) { - net.sf.openrocket.rocketcomponent.SymmetricComponent c = (net.sf.openrocket.rocketcomponent.SymmetricComponent) component; - int i; - - final double delta = 0.0000001; - double x; - - ArrayList points = new ArrayList(); - x = delta; - points.add(new Coordinate(x, c.getRadius(x), 0)); - for (i = 1; i < MINPOINTS - 1; i++) { - x = c.getLength() * i / (MINPOINTS - 1); - points.add(new Coordinate(x, c.getRadius(x), 0)); - //System.out.println("Starting with x="+x); - } - x = c.getLength() - delta; - points.add(new Coordinate(x, c.getRadius(x), 0)); - - - i = 0; - while (i < points.size() - 2) { - if (angleAcceptable(points.get(i), points.get(i + 1), points.get(i + 2)) || - points.get(i + 1).x - points.get(i).x < 0.001) { // 1mm - i++; - continue; - } - - // Split the longer of the areas - int n; - if (points.get(i + 2).x - points.get(i + 1).x > points.get(i + 1).x - points.get(i).x) - n = i + 1; - else - n = i; - - x = (points.get(n).x + points.get(n + 1).x) / 2; - points.add(n + 1, new Coordinate(x, c.getRadius(x), 0)); - } - - - //System.out.println("Final points: "+points.size()); - - final int len = points.size(); - - for (i = 0; i < len; i++) { - points.set(i, c.toAbsolute(points.get(i))[0]); - } - - /* Show points: - Shape[] s = new Shape[len+1]; - final double d=0.001; - for (i=0; i= 0; i--) { - path.lineTo(points.get(i).x * scaleFactor, points.get(i).y * scaleFactor); - } - for (i = 0; i < len; i++) { - path.lineTo(points.get(i).x * scaleFactor, -points.get(i).y * scaleFactor); - } - path.lineTo(points.get(len - 1).x * scaleFactor, points.get(len - 1).y * scaleFactor); - path.closePath(); - - //s[len] = path; - //return s; - return new Shape[] { path }; - } - - private static boolean angleAcceptable(Coordinate v1, Coordinate v2, Coordinate v3) { - return (cosAngle(v1, v2, v3) > ACCEPTABLE_ANGLE); - } - - /* - * cosAngle = v1.v2 / |v1|*|v2| = v1.v2 / sqrt(v1.v1*v2.v2) - */ - private static double cosAngle(Coordinate v1, Coordinate v2, Coordinate v3) { - double cos; - double len; - cos = Coordinate.dot(v1.sub(v2), v2.sub(v3)); - len = MathUtil.safeSqrt(v1.sub(v2).length2() * v2.sub(v3).length2()); - return cos / len; - } -} diff --git a/core/src/net/sf/openrocket/gui/rocketfigure/TransitionShapes.java b/core/src/net/sf/openrocket/gui/rocketfigure/TransitionShapes.java deleted file mode 100644 index 2312c1bd..00000000 --- a/core/src/net/sf/openrocket/gui/rocketfigure/TransitionShapes.java +++ /dev/null @@ -1,101 +0,0 @@ -package net.sf.openrocket.gui.rocketfigure; - -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Transformation; - -import java.awt.*; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; - - -public class TransitionShapes extends RocketComponentShapes { - - // TODO: LOW: Uses only first component of cluster (not currently clusterable). - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - return getShapesSide(component, transformation, S); - } - - public static Shape[] getShapesSide(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation, final double scaleFactor) { - net.sf.openrocket.rocketcomponent.Transition transition = (net.sf.openrocket.rocketcomponent.Transition)component; - - Shape[] mainShapes; - - // Simpler shape for conical transition, others use the method from SymmetricComponent - if (transition.getType() == Transition.Shape.CONICAL) { - double length = transition.getLength(); - double r1 = transition.getForeRadius(); - double r2 = transition.getAftRadius(); - Coordinate start = transformation.transform(transition. - toAbsolute(Coordinate.NUL)[0]); - - Path2D.Float path = new Path2D.Float(); - path.moveTo(start.x* scaleFactor, r1* scaleFactor); - path.lineTo((start.x+length)* scaleFactor, r2* scaleFactor); - path.lineTo((start.x+length)* scaleFactor, -r2* scaleFactor); - path.lineTo(start.x* scaleFactor, -r1* scaleFactor); - path.closePath(); - - mainShapes = new Shape[] { path }; - } else { - mainShapes = SymmetricComponentShapes.getShapesSide(component, transformation, scaleFactor); - } - - Rectangle2D.Double shoulder1=null, shoulder2=null; - int arrayLength = mainShapes.length; - - if (transition.getForeShoulderLength() > 0.0005) { - Coordinate start = transformation.transform(transition. - toAbsolute(Coordinate.NUL)[0]); - double r = transition.getForeShoulderRadius(); - double l = transition.getForeShoulderLength(); - shoulder1 = new Rectangle2D.Double((start.x-l)* scaleFactor, -r* scaleFactor, l* scaleFactor, 2*r* scaleFactor); - arrayLength++; - } - if (transition.getAftShoulderLength() > 0.0005) { - Coordinate start = transformation.transform(transition. - toAbsolute(new Coordinate(transition.getLength()))[0]); - double r = transition.getAftShoulderRadius(); - double l = transition.getAftShoulderLength(); - shoulder2 = new Rectangle2D.Double(start.x* scaleFactor, -r* scaleFactor, l* scaleFactor, 2*r* scaleFactor); - arrayLength++; - } - if (shoulder1==null && shoulder2==null) - return mainShapes; - - Shape[] shapes = new Shape[arrayLength]; - int i; - - for (i=0; i < mainShapes.length; i++) { - shapes[i] = mainShapes[i]; - } - if (shoulder1 != null) { - shapes[i] = shoulder1; - i++; - } - if (shoulder2 != null) { - shapes[i] = shoulder2; - } - return shapes; - } - - - public static Shape[] getShapesBack(net.sf.openrocket.rocketcomponent.RocketComponent component, - Transformation transformation) { - net.sf.openrocket.rocketcomponent.Transition transition = (net.sf.openrocket.rocketcomponent.Transition)component; - - double r1 = transition.getForeRadius(); - double r2 = transition.getAftRadius(); - - Shape[] s = new Shape[2]; - s[0] = new Ellipse2D.Double(-r1*S,-r1*S,2*r1*S,2*r1*S); - s[1] = new Ellipse2D.Double(-r2*S,-r2*S,2*r2*S,2*r2*S); - return s; - } - - -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/AbstractScaleFigure.java b/core/src/net/sf/openrocket/gui/scalefigure/AbstractScaleFigure.java deleted file mode 100644 index 5e37831c..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/AbstractScaleFigure.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - -import java.awt.Color; -import java.awt.Dimension; -import java.util.EventListener; -import java.util.EventObject; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.JPanel; - -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.util.StateChangeListener; - - -public abstract class AbstractScaleFigure extends JPanel implements ScaleFigure { - - // Number of pixels to leave at edges when fitting figure - private static final int DEFAULT_BORDER_PIXELS_WIDTH = 30; - private static final int DEFAULT_BORDER_PIXELS_HEIGHT = 20; - - - protected final double dpi; - - protected double scale = 1.0; - protected double scaling = 1.0; - - protected int borderPixelsWidth = DEFAULT_BORDER_PIXELS_WIDTH; - protected int borderPixelsHeight = DEFAULT_BORDER_PIXELS_HEIGHT; - - protected final List listeners = new LinkedList(); - - - public AbstractScaleFigure() { - this.dpi = GUIUtil.getDPI(); - this.scaling = 1.0; - this.scale = dpi / 0.0254 * scaling; - - setBackground(Color.WHITE); - setOpaque(true); - } - - - - public abstract void updateFigure(); - - public abstract double getFigureWidth(); - - public abstract double getFigureHeight(); - - - @Override - public double getScaling() { - return scaling; - } - - @Override - public double getAbsoluteScale() { - return scale; - } - - @Override - public void setScaling(double scaling) { - if (Double.isInfinite(scaling) || Double.isNaN(scaling)) - scaling = 1.0; - if (scaling < 0.001) - scaling = 0.001; - if (scaling > 1000) - scaling = 1000; - if (Math.abs(this.scaling - scaling) < 0.01) - return; - this.scaling = scaling; - this.scale = dpi / 0.0254 * scaling; - updateFigure(); - } - - @Override - public void setScaling(Dimension bounds) { - double zh = 1, zv = 1; - int w = bounds.width - 2 * borderPixelsWidth - 20; - int h = bounds.height - 2 * borderPixelsHeight - 20; - - if (w < 10) - w = 10; - if (h < 10) - h = 10; - - zh = (w) / getFigureWidth(); - zv = (h) / getFigureHeight(); - - double s = Math.min(zh, zv) / dpi * 0.0254 - 0.001; - - // Restrict to 100% - if (s > 1.0) { - s = 1.0; - } - - setScaling(s); - } - - - @Override - public Dimension getBorderPixels() { - return new Dimension(borderPixelsWidth, borderPixelsHeight); - } - - @Override - public void setBorderPixels(int width, int height) { - this.borderPixelsWidth = width; - this.borderPixelsHeight = height; - } - - - @Override - public void addChangeListener(EventListener listener) { - listeners.add(0, listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - listeners.remove(listener); - } - - private EventObject changeEvent = null; - - protected void fireChangeEvent() { - if (changeEvent == null) - changeEvent = new EventObject(this); - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] list = listeners.toArray(new EventListener[0]); - for (EventListener l : list) { - if (l instanceof StateChangeListener) { - ((StateChangeListener) l).stateChanged(changeEvent); - } - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java b/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java deleted file mode 100644 index cd5b9490..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java +++ /dev/null @@ -1,344 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Line2D; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.Path2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.unit.Tick; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -// TODO: MEDIUM: the figure jumps and bugs when using automatic fitting - -public class FinPointFigure extends AbstractScaleFigure { - - private static final int BOX_SIZE = 4; - - private final FreeformFinSet finset; - private int modID = -1; - - private double minX, maxX, maxY; - private double figureWidth = 0; - private double figureHeight = 0; - private double translateX = 0; - private double translateY = 0; - - private AffineTransform transform; - private Rectangle2D.Double[] handles = null; - - - public FinPointFigure(FreeformFinSet finset) { - this.finset = finset; - } - - - @Override - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g; - - if (modID != finset.getRocket().getAerodynamicModID()) { - modID = finset.getRocket().getAerodynamicModID(); - calculateDimensions(); - } - - - double tx, ty; - // Calculate translation for figure centering - if (figureWidth * scale + 2 * borderPixelsWidth < getWidth()) { - - // Figure fits in the viewport - tx = (getWidth() - figureWidth * scale) / 2 - minX * scale; - - } else { - - // Figure does not fit in viewport - tx = borderPixelsWidth - minX * scale; - - } - - - if (figureHeight * scale + 2 * borderPixelsHeight < getHeight()) { - ty = getHeight() - borderPixelsHeight; - } else { - ty = borderPixelsHeight + figureHeight * scale; - } - - if (Math.abs(translateX - tx) > 1 || Math.abs(translateY - ty) > 1) { - // Origin has changed, fire event - translateX = tx; - translateY = ty; - fireChangeEvent(); - } - - - if (Math.abs(translateX - tx) > 1 || Math.abs(translateY - ty) > 1) { - // Origin has changed, fire event - translateX = tx; - translateY = ty; - fireChangeEvent(); - } - - - // Calculate and store the transformation used - transform = new AffineTransform(); - transform.translate(translateX, translateY); - transform.scale(scale / EXTRA_SCALE, -scale / EXTRA_SCALE); - - // TODO: HIGH: border Y-scale upwards - - g2.transform(transform); - - // Set rendering hints appropriately - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - g2.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - - - Rectangle visible = g2.getClipBounds(); - double x0 = ((double) visible.x - 3) / EXTRA_SCALE; - double x1 = ((double) visible.x + visible.width + 4) / EXTRA_SCALE; - double y0 = ((double) visible.y - 3) / EXTRA_SCALE; - double y1 = ((double) visible.y + visible.height + 4) / EXTRA_SCALE; - - - // Background grid - - g2.setStroke(new BasicStroke((float) (1.0 * EXTRA_SCALE / scale), - BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); - g2.setColor(new Color(0, 0, 255, 30)); - - Unit unit; - if (this.getParent() != null && - this.getParent().getParent() instanceof ScaleScrollPane) { - unit = ((ScaleScrollPane) this.getParent().getParent()).getCurrentUnit(); - } else { - unit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - } - - // vertical - Tick[] ticks = unit.getTicks(x0, x1, - ScaleScrollPane.MINOR_TICKS / scale, - ScaleScrollPane.MAJOR_TICKS / scale); - Line2D.Double line = new Line2D.Double(); - for (Tick t : ticks) { - if (t.major) { - line.setLine(t.value * EXTRA_SCALE, y0 * EXTRA_SCALE, - t.value * EXTRA_SCALE, y1 * EXTRA_SCALE); - g2.draw(line); - } - } - - // horizontal - ticks = unit.getTicks(y0, y1, - ScaleScrollPane.MINOR_TICKS / scale, - ScaleScrollPane.MAJOR_TICKS / scale); - for (Tick t : ticks) { - if (t.major) { - line.setLine(x0 * EXTRA_SCALE, t.value * EXTRA_SCALE, - x1 * EXTRA_SCALE, t.value * EXTRA_SCALE); - g2.draw(line); - } - } - - - - - - // Base rocket line - g2.setStroke(new BasicStroke((float) (3.0 * EXTRA_SCALE / scale), - BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); - g2.setColor(Color.GRAY); - - g2.drawLine((int) (x0 * EXTRA_SCALE), 0, (int) (x1 * EXTRA_SCALE), 0); - - - // Fin shape - Coordinate[] points = finset.getFinPoints(); - Path2D.Double shape = new Path2D.Double(); - shape.moveTo(0, 0); - for (int i = 1; i < points.length; i++) { - shape.lineTo(points[i].x * EXTRA_SCALE, points[i].y * EXTRA_SCALE); - } - - g2.setStroke(new BasicStroke((float) (1.0 * EXTRA_SCALE / scale), - BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); - g2.setColor(Color.BLACK); - g2.draw(shape); - - - // Fin point boxes - g2.setColor(new Color(150, 0, 0)); - double s = BOX_SIZE * EXTRA_SCALE / scale; - handles = new Rectangle2D.Double[points.length]; - for (int i = 0; i < points.length; i++) { - Coordinate c = points[i]; - handles[i] = new Rectangle2D.Double(c.x * EXTRA_SCALE - s, c.y * EXTRA_SCALE - s, 2 * s, 2 * s); - g2.draw(handles[i]); - } - - } - - - - public int getIndexByPoint(double x, double y) { - if (handles == null) - return -1; - - // Calculate point in shapes' coordinates - Point2D.Double p = new Point2D.Double(x, y); - try { - transform.inverseTransform(p, p); - } catch (NoninvertibleTransformException e) { - return -1; - } - - for (int i = 0; i < handles.length; i++) { - if (handles[i].contains(p)) - return i; - } - return -1; - } - - - public int getSegmentByPoint(double x, double y) { - if (handles == null) - return -1; - - // Calculate point in shapes' coordinates - Point2D.Double p = new Point2D.Double(x, y); - try { - transform.inverseTransform(p, p); - } catch (NoninvertibleTransformException e) { - return -1; - } - - double x0 = p.x / EXTRA_SCALE; - double y0 = p.y / EXTRA_SCALE; - double delta = BOX_SIZE / scale; - - //System.out.println("Point: " + x0 + "," + y0); - //System.out.println("delta: " + (BOX_SIZE / scale)); - - Coordinate[] points = finset.getFinPoints(); - for (int i = 1; i < points.length; i++) { - double x1 = points[i - 1].x; - double y1 = points[i - 1].y; - double x2 = points[i].x; - double y2 = points[i].y; - - // System.out.println("point1:"+x1+","+y1+" point2:"+x2+","+y2); - - double u = Math.abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / - MathUtil.hypot(x2 - x1, y2 - y1); - //System.out.println("Distance of segment " + i + " is " + u); - if (u < delta) - return i; - } - - return -1; - } - - - public Point2D.Double convertPoint(double x, double y) { - Point2D.Double p = new Point2D.Double(x, y); - try { - transform.inverseTransform(p, p); - } catch (NoninvertibleTransformException e) { - assert (false) : "Should not occur"; - return new Point2D.Double(0, 0); - } - - p.setLocation(p.x / EXTRA_SCALE, p.y / EXTRA_SCALE); - return p; - } - - - - @Override - public Dimension getOrigin() { - if (modID != finset.getRocket().getAerodynamicModID()) { - modID = finset.getRocket().getAerodynamicModID(); - calculateDimensions(); - } - return new Dimension((int) translateX, (int) translateY); - } - - @Override - public double getFigureWidth() { - if (modID != finset.getRocket().getAerodynamicModID()) { - modID = finset.getRocket().getAerodynamicModID(); - calculateDimensions(); - } - return figureWidth; - } - - @Override - public double getFigureHeight() { - if (modID != finset.getRocket().getAerodynamicModID()) { - modID = finset.getRocket().getAerodynamicModID(); - calculateDimensions(); - } - return figureHeight; - } - - - private void calculateDimensions() { - minX = 0; - maxX = 0; - maxY = 0; - - for (Coordinate c : finset.getFinPoints()) { - if (c.x < minX) - minX = c.x; - if (c.x > maxX) - maxX = c.x; - if (c.y > maxY) - maxY = c.y; - } - - if (maxX < 0.01) - maxX = 0.01; - - figureWidth = maxX - minX; - figureHeight = maxY; - - - Dimension d = new Dimension((int) (figureWidth * scale + 2 * borderPixelsWidth), - (int) (figureHeight * scale + 2 * borderPixelsHeight)); - - if (!d.equals(getPreferredSize()) || !d.equals(getMinimumSize())) { - setPreferredSize(d); - setMinimumSize(d); - revalidate(); - } - } - - - - @Override - public void updateFigure() { - repaint(); - } - - - -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java b/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java deleted file mode 100644 index bd63d8ba..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java +++ /dev/null @@ -1,561 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Ellipse2D; -import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashSet; - -import net.sf.openrocket.gui.figureelements.FigureElement; -import net.sf.openrocket.gui.util.ColorConversion; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.LineStyle; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.Transformation; - -/** - * A ScaleFigure that draws a complete rocket. Extra information can - * be added to the figure by the methods {@link #addRelativeExtra(FigureElement)}, - * {@link #clearRelativeExtra()}. - * - * @author Sampo Niskanen - */ -public class RocketFigure extends AbstractScaleFigure { - private static final long serialVersionUID = 1L; - - private static final String ROCKET_FIGURE_PACKAGE = "net.sf.openrocket.gui.rocketfigure"; - private static final String ROCKET_FIGURE_SUFFIX = "Shapes"; - - public static final int TYPE_SIDE = 1; - public static final int TYPE_BACK = 2; - - // Width for drawing normal and selected components - public static final double NORMAL_WIDTH = 1.0; - public static final double SELECTED_WIDTH = 2.0; - - - private Configuration configuration; - private RocketComponent[] selection = new RocketComponent[0]; - - private int type = TYPE_SIDE; - - private double rotation; - private Transformation transformation; - - private double translateX, translateY; - - - - /* - * figureComponents contains the corresponding RocketComponents of the figureShapes - */ - private final ArrayList figureShapes = new ArrayList(); - private final ArrayList figureComponents = - new ArrayList(); - - private double minX = 0, maxX = 0, maxR = 0; - // Figure width and height in SI-units and pixels - private double figureWidth = 0, figureHeight = 0; - protected int figureWidthPx = 0, figureHeightPx = 0; - - private AffineTransform g2transformation = null; - - private final ArrayList relativeExtra = new ArrayList(); - private final ArrayList absoluteExtra = new ArrayList(); - - - /** - * Creates a new rocket figure. - */ - public RocketFigure(Configuration configuration) { - super(); - - this.configuration = configuration; - - this.rotation = 0.0; - this.transformation = Transformation.rotate_x(0.0); - - updateFigure(); - } - - - /** - * Set the configuration displayed by the figure. It may use the same or different rocket. - * - * @param configuration the configuration to display. - */ - public void setConfiguration(Configuration configuration) { - this.configuration = configuration; - updateFigure(); - } - - - @Override - public Dimension getOrigin() { - return new Dimension((int) translateX, (int) translateY); - } - - @Override - public double getFigureHeight() { - return figureHeight; - } - - @Override - public double getFigureWidth() { - return figureWidth; - } - - - public RocketComponent[] getSelection() { - return selection; - } - - public void setSelection(RocketComponent[] selection) { - if (selection == null) { - this.selection = new RocketComponent[0]; - } else { - this.selection = selection; - } - updateFigure(); - } - - - public double getRotation() { - return rotation; - } - - public Transformation getRotateTransformation() { - return transformation; - } - - public void setRotation(double rot) { - if (MathUtil.equals(rotation, rot)) - return; - this.rotation = rot; - this.transformation = Transformation.rotate_x(rotation); - updateFigure(); - } - - - public int getType() { - return type; - } - - public void setType(int type) { - if (type != TYPE_BACK && type != TYPE_SIDE) { - throw new IllegalArgumentException("Illegal type: " + type); - } - if (this.type == type) - return; - this.type = type; - updateFigure(); - } - - - - - - /** - * Updates the figure shapes and figure size. - */ - @Override - public void updateFigure() { - figureShapes.clear(); - figureComponents.clear(); - - calculateSize(); - - // Get shapes for all active components - for (RocketComponent c : configuration) { - Shape[] s = getShapes(c); - for (int i = 0; i < s.length; i++) { - figureShapes.add(s[i]); - figureComponents.add(c); - } - } - - repaint(); - fireChangeEvent(); - } - - - public void addRelativeExtra(FigureElement p) { - relativeExtra.add(p); - } - - public void removeRelativeExtra(FigureElement p) { - relativeExtra.remove(p); - } - - public void clearRelativeExtra() { - relativeExtra.clear(); - } - - - public void addAbsoluteExtra(FigureElement p) { - absoluteExtra.add(p); - } - - public void removeAbsoluteExtra(FigureElement p) { - absoluteExtra.remove(p); - } - - public void clearAbsoluteExtra() { - absoluteExtra.clear(); - } - - - /** - * Paints the rocket on to the Graphics element. - *

- * Warning: If paintComponent is used outside the normal Swing usage, some Swing - * dependent parameters may be left wrong (mainly transformation). If it is used, - * the RocketFigure should be repainted immediately afterwards. - */ - @Override - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g; - - - AffineTransform baseTransform = g2.getTransform(); - - // Update figure shapes if necessary - if (figureShapes == null) - updateFigure(); - - - double tx, ty; - // Calculate translation for figure centering - if (figureWidthPx + 2 * borderPixelsWidth < getWidth()) { - - // Figure fits in the viewport - if (type == TYPE_BACK) - tx = getWidth() / 2; - else - tx = (getWidth() - figureWidthPx) / 2 - minX * scale; - - } else { - - // Figure does not fit in viewport - if (type == TYPE_BACK) - tx = borderPixelsWidth + figureWidthPx / 2; - else - tx = borderPixelsWidth - minX * scale; - - } - - ty = computeTy(figureHeightPx); - - if (Math.abs(translateX - tx) > 1 || Math.abs(translateY - ty) > 1) { - // Origin has changed, fire event - translateX = tx; - translateY = ty; - fireChangeEvent(); - } - - - // Calculate and store the transformation used - // (inverse is used in detecting clicks on objects) - g2transformation = new AffineTransform(); - g2transformation.translate(translateX, translateY); - // Mirror position Y-axis upwards - g2transformation.scale(scale / EXTRA_SCALE, -scale / EXTRA_SCALE); - - g2.transform(g2transformation); - - // Set rendering hints appropriately - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - g2.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - - - // Draw all shapes - - for (int i = 0; i < figureShapes.size(); i++) { - RocketComponent c = figureComponents.get(i); - Shape s = figureShapes.get(i); - boolean selected = false; - - // Check if component is in the selection - for (int j = 0; j < selection.length; j++) { - if (c == selection[j]) { - selected = true; - break; - } - } - - // Set component color and line style - net.sf.openrocket.util.Color color = c.getColor(); - if (color == null) { - color = Application.getPreferences().getDefaultColor(c.getClass()); - } - g2.setColor(ColorConversion.toAwtColor(color)); - - LineStyle style = c.getLineStyle(); - if (style == null) - style = Application.getPreferences().getDefaultLineStyle(c.getClass()); - - float[] dashes = style.getDashes(); - for (int j = 0; j < dashes.length; j++) { - dashes[j] *= EXTRA_SCALE / scale; - } - - if (selected) { - g2.setStroke(new BasicStroke((float) (SELECTED_WIDTH * EXTRA_SCALE / scale), - BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dashes, 0)); - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_PURE); - } else { - g2.setStroke(new BasicStroke((float) (NORMAL_WIDTH * EXTRA_SCALE / scale), - BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, dashes, 0)); - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - } - g2.draw(s); - - } - - g2.setStroke(new BasicStroke((float) (NORMAL_WIDTH * EXTRA_SCALE / scale), - BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - - - // Draw motors - String motorID = configuration.getMotorConfigurationID(); - Color fillColor = ((SwingPreferences)Application.getPreferences()).getMotorFillColor(); - Color borderColor = ((SwingPreferences)Application.getPreferences()).getMotorBorderColor(); - Iterator iterator = configuration.motorIterator(); - while (iterator.hasNext()) { - MotorMount mount = iterator.next(); - Motor motor = mount.getMotor(motorID); - double length = motor.getLength(); - double radius = motor.getDiameter() / 2; - - Coordinate[] position = ((RocketComponent) mount).toAbsolute( - new Coordinate(((RocketComponent) mount).getLength() + - mount.getMotorOverhang() - length)); - - for (int i = 0; i < position.length; i++) { - position[i] = transformation.transform(position[i]); - } - - for (Coordinate coord : position) { - Shape s; - if (type == TYPE_SIDE) { - s = new Rectangle2D.Double(EXTRA_SCALE * coord.x, - EXTRA_SCALE * (coord.y - radius), EXTRA_SCALE * length, - EXTRA_SCALE * 2 * radius); - } else { - s = new Ellipse2D.Double(EXTRA_SCALE * (coord.z - radius), - EXTRA_SCALE * (coord.y - radius), EXTRA_SCALE * 2 * radius, - EXTRA_SCALE * 2 * radius); - } - g2.setColor(fillColor); - g2.fill(s); - g2.setColor(borderColor); - g2.draw(s); - } - } - - - - // Draw relative extras - for (FigureElement e : relativeExtra) { - e.paint(g2, scale / EXTRA_SCALE); - } - - // Draw absolute extras - g2.setTransform(baseTransform); - Rectangle rect = this.getVisibleRect(); - - for (FigureElement e : absoluteExtra) { - e.paint(g2, 1.0, rect); - } - - } - - protected double computeTy(int heightPx) { - final double ty; - if (heightPx + 2 * borderPixelsHeight < getHeight()) { - ty = getHeight() / 2; - } else { - ty = borderPixelsHeight + heightPx / 2; - } - return ty; - } - - - public RocketComponent[] getComponentsByPoint(double x, double y) { - // Calculate point in shapes' coordinates - Point2D.Double p = new Point2D.Double(x, y); - try { - g2transformation.inverseTransform(p, p); - } catch (NoninvertibleTransformException e) { - return new RocketComponent[0]; - } - - LinkedHashSet l = new LinkedHashSet(); - - for (int i = 0; i < figureShapes.size(); i++) { - if (figureShapes.get(i).contains(p)) - l.add(figureComponents.get(i)); - } - return l.toArray(new RocketComponent[0]); - } - - - - /** - * Gets the shapes required to draw the component. - * - * @param component - * @param params - * @return - */ - private Shape[] getShapes(RocketComponent component) { - Reflection.Method m; - - // Find the appropriate method - switch (type) { - case TYPE_SIDE: - m = Reflection.findMethod(ROCKET_FIGURE_PACKAGE, component, ROCKET_FIGURE_SUFFIX, "getShapesSide", - RocketComponent.class, Transformation.class); - break; - - case TYPE_BACK: - m = Reflection.findMethod(ROCKET_FIGURE_PACKAGE, component, ROCKET_FIGURE_SUFFIX, "getShapesBack", - RocketComponent.class, Transformation.class); - break; - - default: - throw new BugException("Unknown figure type = " + type); - } - - if (m == null) { - Application.getExceptionHandler().handleErrorCondition("ERROR: Rocket figure paint method not found for " - + component); - return new Shape[0]; - } - - return (Shape[]) m.invokeStatic(component, transformation); - } - - - - /** - * Gets the bounds of the figure, i.e. the maximum extents in the selected dimensions. - * The bounds are stored in the variables minX, maxX and maxR. - */ - private void calculateFigureBounds() { - Collection bounds = configuration.getBounds(); - - if (bounds.isEmpty()) { - minX = 0; - maxX = 0; - maxR = 0; - return; - } - - minX = Double.MAX_VALUE; - maxX = Double.MIN_VALUE; - maxR = 0; - for (Coordinate c : bounds) { - double x = c.x, r = MathUtil.hypot(c.y, c.z); - if (x < minX) - minX = x; - if (x > maxX) - maxX = x; - if (r > maxR) - maxR = r; - } - } - - - public double getBestZoom(Rectangle2D bounds) { - double zh = 1, zv = 1; - if (bounds.getWidth() > 0.0001) - zh = (getWidth() - 2 * borderPixelsWidth) / bounds.getWidth(); - if (bounds.getHeight() > 0.0001) - zv = (getHeight() - 2 * borderPixelsHeight) / bounds.getHeight(); - return Math.min(zh, zv); - } - - - - /** - * Calculates the necessary size of the figure and set the PreferredSize - * property accordingly. - */ - private void calculateSize() { - calculateFigureBounds(); - - switch (type) { - case TYPE_SIDE: - figureWidth = maxX - minX; - figureHeight = 2 * maxR; - break; - - case TYPE_BACK: - figureWidth = 2 * maxR; - figureHeight = 2 * maxR; - break; - - default: - assert (false) : "Should not occur, type=" + type; - figureWidth = 0; - figureHeight = 0; - } - - figureWidthPx = (int) (figureWidth * scale); - figureHeightPx = (int) (figureHeight * scale); - - Dimension d = new Dimension(figureWidthPx + 2 * borderPixelsWidth, - figureHeightPx + 2 * borderPixelsHeight); - - if (!d.equals(getPreferredSize()) || !d.equals(getMinimumSize())) { - setPreferredSize(d); - setMinimumSize(d); - revalidate(); - } - } - - public Rectangle2D getDimensions() { - switch (type) { - case TYPE_SIDE: - return new Rectangle2D.Double(minX, -maxR, maxX - minX, 2 * maxR); - - case TYPE_BACK: - return new Rectangle2D.Double(-maxR, -maxR, 2 * maxR, 2 * maxR); - - default: - throw new BugException("Illegal figure type = " + type); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java b/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java deleted file mode 100644 index 2cef7080..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java +++ /dev/null @@ -1,859 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - - -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.InputEvent; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EventListener; -import java.util.EventObject; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ButtonGroup; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.JToggleButton; -import javax.swing.JViewport; -import javax.swing.SwingUtilities; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.adaptors.MotorConfigurationModel; -import net.sf.openrocket.gui.components.BasicSlider; -import net.sf.openrocket.gui.components.StageSelector; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.gui.configdialog.ComponentConfigDialog; -import net.sf.openrocket.gui.figure3d.RocketFigure3d; -import net.sf.openrocket.gui.figureelements.CGCaret; -import net.sf.openrocket.gui.figureelements.CPCaret; -import net.sf.openrocket.gui.figureelements.Caret; -import net.sf.openrocket.gui.figureelements.RocketInfo; -import net.sf.openrocket.gui.main.SimulationWorker; -import net.sf.openrocket.gui.main.componenttree.ComponentTreeModel; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.simulation.customexpression.CustomExpressionSimulationListener; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener; -import net.sf.openrocket.simulation.listeners.system.InterruptListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.StateChangeListener; - -/** - * A JPanel that contains a RocketFigure and buttons to manipulate the figure. - * - * @author Sampo Niskanen - * @author Bill Kuker - */ -public class RocketPanel extends JPanel implements TreeSelectionListener, ChangeSource { - private static final long serialVersionUID = 1L; - - private static final Translator trans = Application.getTranslator(); - - private boolean is3d; - private final RocketFigure figure; - private final RocketFigure3d figure3d; - - - private final ScaleScrollPane scrollPane; - - private final JPanel figureHolder; - - private JLabel infoMessage; - - private TreeSelectionModel selectionModel = null; - - private BasicSlider rotationSlider; - ScaleSelector scaleSelector; - - - /* Calculation of CP and CG */ - private AerodynamicCalculator aerodynamicCalculator; - private MassCalculator massCalculator; - - - private final OpenRocketDocument document; - private final Configuration configuration; - - private Caret extraCP = null; - private Caret extraCG = null; - private RocketInfo extraText = null; - - - private double cpAOA = Double.NaN; - private double cpTheta = Double.NaN; - private double cpMach = Double.NaN; - private double cpRoll = Double.NaN; - - // The functional ID of the rocket that was simulated - private int flightDataFunctionalID = -1; - private String flightDataMotorID = null; - - - private SimulationWorker backgroundSimulationWorker = null; - - private List listeners = new ArrayList(); - - - /** - * The executor service used for running the background simulations. - * This uses a fixed-sized thread pool for all background simulations - * with all threads in daemon mode and with minimum priority. - */ - private static final Executor backgroundSimulationExecutor; - static { - backgroundSimulationExecutor = Executors.newFixedThreadPool(SwingPreferences.getMaxThreadCount(), - new ThreadFactory() { - private ThreadFactory factory = Executors.defaultThreadFactory(); - - @Override - public Thread newThread(Runnable r) { - Thread t = factory.newThread(r); - t.setDaemon(true); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } - }); - } - - - public RocketPanel(OpenRocketDocument document) { - - this.document = document; - configuration = document.getDefaultConfiguration(); - - // TODO: FUTURE: calculator selection - aerodynamicCalculator = new BarrowmanCalculator(); - massCalculator = new BasicMassCalculator(); - - // Create figure and custom scroll pane - figure = new RocketFigure(configuration); - figure3d = new RocketFigure3d(configuration); - - figureHolder = new JPanel(new BorderLayout()); - - scrollPane = new ScaleScrollPane(figure) { - private static final long serialVersionUID = 1L; - - @Override - public void mouseClicked(MouseEvent event) { - handleMouseClick(event); - } - }; - scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); - scrollPane.setFitting(true); - - createPanel(); - - is3d = true; - go2D(); - - configuration.addChangeListener(new StateChangeListener() { - @Override - public void stateChanged(EventObject e) { - // System.out.println("Configuration changed, calling updateFigure"); - updateExtras(); - updateFigures(); - } - }); - - figure3d.addComponentSelectionListener(new RocketFigure3d.ComponentSelectionListener() { - @Override - public void componentClicked(RocketComponent clicked[], MouseEvent event) { - handleComponentClick(clicked, event); - } - }); - } - - private void updateFigures() { - if (!is3d) - figure.updateFigure(); - else - figure3d.updateFigure(); - } - - private void go3D() { - if (is3d) - return; - is3d = true; - figureHolder.remove(scrollPane); - figureHolder.add(figure3d, BorderLayout.CENTER); - rotationSlider.setEnabled(false); - scaleSelector.setEnabled(false); - - revalidate(); - figureHolder.revalidate(); - - figure3d.repaint(); - } - - private void go2D() { - if (!is3d) - return; - is3d = false; - figureHolder.remove(figure3d); - figureHolder.add(scrollPane, BorderLayout.CENTER); - rotationSlider.setEnabled(true); - scaleSelector.setEnabled(true); - revalidate(); - figureHolder.revalidate(); - figure.repaint(); - } - - /** - * Creates the layout and components of the panel. - */ - private void createPanel() { - setLayout(new MigLayout("", "[shrink][grow]", "[shrink][shrink][grow][shrink]")); - - setPreferredSize(new Dimension(800, 300)); - - - //// Create toolbar - - ButtonGroup bg = new ButtonGroup(); - - // Side/back buttons - FigureTypeAction action = new FigureTypeAction(RocketFigure.TYPE_SIDE); - //// Side view - action.putValue(Action.NAME, trans.get("RocketPanel.FigTypeAct.Sideview")); - //// Side view - action.putValue(Action.SHORT_DESCRIPTION, trans.get("RocketPanel.FigTypeAct.ttip.Sideview")); - JToggleButton toggle = new JToggleButton(action); - bg.add(toggle); - add(toggle, "spanx, split"); - - action = new FigureTypeAction(RocketFigure.TYPE_BACK); - //// Back view - action.putValue(Action.NAME, trans.get("RocketPanel.FigTypeAct.Backview")); - //// Back view - action.putValue(Action.SHORT_DESCRIPTION, trans.get("RocketPanel.FigTypeAct.ttip.Backview")); - toggle = new JToggleButton(action); - bg.add(toggle); - add(toggle, "gap rel"); - - //// 3d Toggle - final JToggleButton toggle3d = new JToggleButton(new AbstractAction("3D") { - private static final long serialVersionUID = 1L; - { - putValue(Action.NAME, "3D");//TODO - putValue(Action.SHORT_DESCRIPTION, "3D"); //TODO - } - @Override - public void actionPerformed(ActionEvent e) { - if ( ((JToggleButton)e.getSource()).isSelected() ){ - go3D(); - } else { - go2D(); - } - } - }); - bg.add(toggle3d); - toggle3d.setEnabled(RocketFigure3d.is3dEnabled()); - add(toggle3d, "gap rel"); - - // Zoom level selector - scaleSelector = new ScaleSelector(scrollPane); - add(scaleSelector); - - - - // Stage selector - StageSelector stageSelector = new StageSelector(configuration); - add(stageSelector, ""); - - - - // Motor configuration selector - //// Motor configuration: - JLabel label = new JLabel(trans.get("RocketPanel.lbl.Motorcfg")); - label.setHorizontalAlignment(JLabel.RIGHT); - add(label, "growx, right"); - add(new JComboBox(new MotorConfigurationModel(configuration)), "wrap"); - - - - - - // Create slider and scroll pane - - DoubleModel theta = new DoubleModel(figure, "Rotation", - UnitGroup.UNITS_ANGLE, 0, 2 * Math.PI); - UnitSelector us = new UnitSelector(theta, true); - us.setHorizontalAlignment(JLabel.CENTER); - add(us, "alignx 50%, growx"); - - // Add the rocket figure - add(figureHolder, "grow, spany 2, wmin 300lp, hmin 100lp, wrap"); - - - // Add rotation slider - // Minimum size to fit "360deg" - JLabel l = new JLabel("360" + Chars.DEGREE); - Dimension d = l.getPreferredSize(); - - add(rotationSlider = new BasicSlider(theta.getSliderModel(0, 2 * Math.PI), JSlider.VERTICAL, true), - "ax 50%, wrap, width " + (d.width + 6) + "px:null:null, growy"); - - - //// Click to select    Shift+click to select other    Double-click to edit    Click+drag to move - infoMessage = new JLabel(trans.get("RocketPanel.lbl.infoMessage")); - infoMessage.setFont(new Font("Sans Serif", Font.PLAIN, 9)); - add(infoMessage, "skip, span, gapleft 25, wrap"); - - - addExtras(); - } - - - - public RocketFigure getFigure() { - return figure; - } - - public AerodynamicCalculator getAerodynamicCalculator() { - return aerodynamicCalculator; - } - - public Configuration getConfiguration() { - return configuration; - } - - /** - * Get the center of pressure figure element. - * - * @return center of pressure info - */ - public Caret getExtraCP() { - return extraCP; - } - - /** - * Get the center of gravity figure element. - * - * @return center of gravity info - */ - public Caret getExtraCG() { - return extraCG; - } - - /** - * Get the extra text figure element. - * - * @return extra text that contains info about the rocket design - */ - public RocketInfo getExtraText() { - return extraText; - } - - public void setSelectionModel(TreeSelectionModel m) { - if (selectionModel != null) { - selectionModel.removeTreeSelectionListener(this); - } - selectionModel = m; - selectionModel.addTreeSelectionListener(this); - valueChanged((TreeSelectionEvent) null); // updates FigureParameters - } - - - - /** - * Return the angle of attack used in CP calculation. NaN signifies the default value - * of zero. - * @return the angle of attack used, or NaN. - */ - public double getCPAOA() { - return cpAOA; - } - - /** - * Set the angle of attack to be used in CP calculation. A value of NaN signifies that - * the default AOA (zero) should be used. - * @param aoa the angle of attack to use, or NaN - */ - public void setCPAOA(double aoa) { - if (MathUtil.equals(aoa, cpAOA) || - (Double.isNaN(aoa) && Double.isNaN(cpAOA))) - return; - cpAOA = aoa; - updateExtras(); - updateFigures(); - fireChangeEvent(); - } - - public double getCPTheta() { - return cpTheta; - } - - public void setCPTheta(double theta) { - if (MathUtil.equals(theta, cpTheta) || - (Double.isNaN(theta) && Double.isNaN(cpTheta))) - return; - cpTheta = theta; - if (!Double.isNaN(theta)) - figure.setRotation(theta); - updateExtras(); - updateFigures(); - fireChangeEvent(); - } - - public double getCPMach() { - return cpMach; - } - - public void setCPMach(double mach) { - if (MathUtil.equals(mach, cpMach) || - (Double.isNaN(mach) && Double.isNaN(cpMach))) - return; - cpMach = mach; - updateExtras(); - updateFigures(); - fireChangeEvent(); - } - - public double getCPRoll() { - return cpRoll; - } - - public void setCPRoll(double roll) { - if (MathUtil.equals(roll, cpRoll) || - (Double.isNaN(roll) && Double.isNaN(cpRoll))) - return; - cpRoll = roll; - updateExtras(); - updateFigures(); - fireChangeEvent(); - } - - - - @Override - public void addChangeListener(EventListener listener) { - listeners.add(0, listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - listeners.remove(listener); - } - - protected void fireChangeEvent() { - EventObject e = new EventObject(this); - for (EventListener l : listeners) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(e); - } - } - } - - - - - /** - * Handle clicking on figure shapes. The functioning is the following: - * - * Get the components clicked. - * If no component is clicked, do nothing. - * If the currently selected component is in the set, keep it, - * unless the selector specified is pressed. If it is pressed, cycle to - * the next component. Otherwise select the first component in the list. - */ - public static final int CYCLE_SELECTION_MODIFIER = InputEvent.SHIFT_DOWN_MASK; - - private void handleMouseClick(MouseEvent event) { - if (event.getButton() != MouseEvent.BUTTON1) - return; - Point p0 = event.getPoint(); - Point p1 = scrollPane.getViewport().getViewPosition(); - int x = p0.x + p1.x; - int y = p0.y + p1.y; - - RocketComponent[] clicked = figure.getComponentsByPoint(x, y); - - handleComponentClick(clicked, event); - } - - private void handleComponentClick(RocketComponent[] clicked, MouseEvent event){ - - // If no component is clicked, do nothing - if (clicked.length == 0) - return; - - // Check whether the currently selected component is in the clicked components. - TreePath path = selectionModel.getSelectionPath(); - if (path != null) { - RocketComponent current = (RocketComponent) path.getLastPathComponent(); - path = null; - for (int i = 0; i < clicked.length; i++) { - if (clicked[i] == current) { - if (event.isShiftDown() && (event.getClickCount() == 1)) { - path = ComponentTreeModel.makeTreePath(clicked[(i + 1) % clicked.length]); - } else { - path = ComponentTreeModel.makeTreePath(clicked[i]); - } - break; - } - } - } - - // Currently selected component not clicked - if (path == null) { - if (event.isShiftDown() && event.getClickCount() == 1 && clicked.length > 1) { - path = ComponentTreeModel.makeTreePath(clicked[1]); - } else { - path = ComponentTreeModel.makeTreePath(clicked[0]); - } - } - - // Set selection and check for double-click - selectionModel.setSelectionPath(path); - if (event.getClickCount() == 2) { - RocketComponent component = (RocketComponent) path.getLastPathComponent(); - - ComponentConfigDialog.showDialog(SwingUtilities.getWindowAncestor(this), - document, component); - } - } - - - - - /** - * Updates the extra data included in the figure. Currently this includes - * the CP and CG carets. - */ - private WarningSet warnings = new WarningSet(); - - private void updateExtras() { - Coordinate cp, cg; - double cpx, cgx; - - // TODO: MEDIUM: User-definable conditions - FlightConditions conditions = new FlightConditions(configuration); - warnings.clear(); - - if (!Double.isNaN(cpMach)) { - conditions.setMach(cpMach); - extraText.setMach(cpMach); - } else { - conditions.setMach(Application.getPreferences().getDefaultMach()); - extraText.setMach(Application.getPreferences().getDefaultMach()); - } - - if (!Double.isNaN(cpAOA)) { - conditions.setAOA(cpAOA); - } else { - conditions.setAOA(0); - } - extraText.setAOA(cpAOA); - - if (!Double.isNaN(cpRoll)) { - conditions.setRollRate(cpRoll); - } else { - conditions.setRollRate(0); - } - - if (!Double.isNaN(cpTheta)) { - conditions.setTheta(cpTheta); - cp = aerodynamicCalculator.getCP(configuration, conditions, warnings); - } else { - cp = aerodynamicCalculator.getWorstCP(configuration, conditions, warnings); - } - extraText.setTheta(cpTheta); - - - cg = massCalculator.getCG(configuration, MassCalcType.LAUNCH_MASS); - // System.out.println("CG computed as "+cg+ " CP as "+cp); - - if (cp.weight > 0.000001) - cpx = cp.x; - else - cpx = Double.NaN; - - if (cg.weight > 0.000001) - cgx = cg.x; - else - cgx = Double.NaN; - - figure3d.setCG(cg); - figure3d.setCP(cp); - - // Length bound is assumed to be tight - double length = 0, diameter = 0; - Collection bounds = configuration.getBounds(); - if (!bounds.isEmpty()) { - double minX = Double.POSITIVE_INFINITY, maxX = Double.NEGATIVE_INFINITY; - for (Coordinate c : bounds) { - if (c.x < minX) - minX = c.x; - if (c.x > maxX) - maxX = c.x; - } - length = maxX - minX; - } - - for (RocketComponent c : configuration) { - if (c instanceof SymmetricComponent) { - double d1 = ((SymmetricComponent) c).getForeRadius() * 2; - double d2 = ((SymmetricComponent) c).getAftRadius() * 2; - diameter = MathUtil.max(diameter, d1, d2); - } - } - - extraText.setCG(cgx); - extraText.setCP(cpx); - extraText.setLength(length); - extraText.setDiameter(diameter); - extraText.setMass(cg.weight); - extraText.setWarnings(warnings); - - - if (figure.getType() == RocketFigure.TYPE_SIDE && length > 0) { - - // TODO: LOW: Y-coordinate and rotation - extraCP.setPosition(cpx * RocketFigure.EXTRA_SCALE, 0); - extraCG.setPosition(cgx * RocketFigure.EXTRA_SCALE, 0); - - } else { - - extraCP.setPosition(Double.NaN, Double.NaN); - extraCG.setPosition(Double.NaN, Double.NaN); - - } - - - //////// Flight simulation in background - - // Check whether to compute or not - if (!((SwingPreferences) Application.getPreferences()).computeFlightInBackground()) { - extraText.setFlightData(null); - extraText.setCalculatingData(false); - stopBackgroundSimulation(); - return; - } - - // Check whether data is already up to date - if (flightDataFunctionalID == configuration.getRocket().getFunctionalModID() && - flightDataMotorID == configuration.getMotorConfigurationID()) { - return; - } - - flightDataFunctionalID = configuration.getRocket().getFunctionalModID(); - flightDataMotorID = configuration.getMotorConfigurationID(); - - // Stop previous computation (if any) - stopBackgroundSimulation(); - - // Check that configuration has motors - if (!configuration.hasMotors()) { - extraText.setFlightData(FlightData.NaN_DATA); - extraText.setCalculatingData(false); - return; - } - - // Start calculation process - extraText.setCalculatingData(true); - - Rocket duplicate = (Rocket) configuration.getRocket().copy(); - Simulation simulation = ((SwingPreferences)Application.getPreferences()).getBackgroundSimulation(duplicate); - simulation.getOptions().setMotorConfigurationID( - configuration.getMotorConfigurationID()); - - backgroundSimulationWorker = new BackgroundSimulationWorker(document, simulation); - backgroundSimulationExecutor.execute(backgroundSimulationWorker); - } - - /** - * Cancels the current background simulation worker, if any. - */ - private void stopBackgroundSimulation() { - if (backgroundSimulationWorker != null) { - backgroundSimulationWorker.cancel(true); - backgroundSimulationWorker = null; - } - } - - - /** - * A SimulationWorker that simulates the rocket flight in the background and - * sets the results to the extra text when finished. The worker can be cancelled - * if necessary. - */ - private class BackgroundSimulationWorker extends SimulationWorker { - - private final CustomExpressionSimulationListener exprListener; - - public BackgroundSimulationWorker(OpenRocketDocument doc, Simulation sim) { - super(sim); - List exprs = doc.getCustomExpressions(); - exprListener = new CustomExpressionSimulationListener(exprs); - } - - @Override - protected FlightData doInBackground() { - - // Pause a little while to allow faster UI reaction - try { - Thread.sleep(300); - } catch (InterruptedException ignore) { - } - if (isCancelled() || backgroundSimulationWorker != this) - return null; - - return super.doInBackground(); - } - - @Override - protected void simulationDone() { - // Do nothing if cancelled - if (isCancelled() || backgroundSimulationWorker != this) - return; - - backgroundSimulationWorker = null; - extraText.setFlightData(simulation.getSimulatedData()); - extraText.setCalculatingData(false); - figure.repaint(); - figure3d.repaint(); - } - - @Override - protected SimulationListener[] getExtraListeners() { - return new SimulationListener[] { - InterruptListener.INSTANCE, - ApogeeEndListener.INSTANCE, - exprListener}; - - } - - @Override - protected void simulationInterrupted(Throwable t) { - // Do nothing on cancel, set N/A data otherwise - if (isCancelled() || backgroundSimulationWorker != this) // Double-check - return; - - backgroundSimulationWorker = null; - extraText.setFlightData(FlightData.NaN_DATA); - extraText.setCalculatingData(false); - figure.repaint(); - figure3d.repaint(); - } - } - - - - /** - * Adds the extra data to the figure. Currently this includes the CP and CG carets. - */ - private void addExtras() { - extraCG = new CGCaret(0, 0); - extraCP = new CPCaret(0, 0); - extraText = new RocketInfo(configuration); - updateExtras(); - - figure.clearRelativeExtra(); - figure.addRelativeExtra(extraCP); - figure.addRelativeExtra(extraCG); - figure.addAbsoluteExtra(extraText); - - - figure3d.clearRelativeExtra(); - //figure3d.addRelativeExtra(extraCP); - //figure3d.addRelativeExtra(extraCG); - figure3d.addAbsoluteExtra(extraText); - - } - - - /** - * Updates the selection in the FigureParameters and repaints the figure. - * Ignores the event itself. - */ - @Override - public void valueChanged(TreeSelectionEvent e) { - TreePath[] paths = selectionModel.getSelectionPaths(); - if (paths == null) { - figure.setSelection(null); - return; - } - - RocketComponent[] components = new RocketComponent[paths.length]; - for (int i = 0; i < paths.length; i++) - components[i] = (RocketComponent) paths[i].getLastPathComponent(); - figure.setSelection(components); - - figure3d.setSelection(components); - } - - - - /** - * An Action that shows whether the figure type is the type - * given in the constructor. - * - * @author Sampo Niskanen - */ - private class FigureTypeAction extends AbstractAction implements StateChangeListener { - private static final long serialVersionUID = 1L; - private final int type; - - public FigureTypeAction(int type) { - this.type = type; - stateChanged(null); - figure.addChangeListener(this); - } - - @Override - public void actionPerformed(ActionEvent e) { - boolean state = (Boolean) getValue(Action.SELECTED_KEY); - if (state == true) { - // This view has been selected - figure.setType(type); - go2D(); - updateExtras(); - } - stateChanged(null); - } - - @Override - public void stateChanged(EventObject e) { - putValue(Action.SELECTED_KEY, figure.getType() == type && !is3d); - } - } - -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/ScaleFigure.java b/core/src/net/sf/openrocket/gui/scalefigure/ScaleFigure.java deleted file mode 100644 index 48440fe3..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/ScaleFigure.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - -import java.awt.Dimension; - -import net.sf.openrocket.util.ChangeSource; - - -public interface ScaleFigure extends ChangeSource { - - /** - * Extra scaling applied to the figure. The f***ing Java JRE doesn't know - * how to draw shapes when using very large scaling factors, so this must - * be manually applied to every single shape used. - *

- * The scaling factor used is divided by this value, and every coordinate used - * in the figures must be multiplied by this factor. - */ - public static final double EXTRA_SCALE = 1000; - - /** - * Shorthand for {@link #EXTRA_SCALE}. - */ - public static final double S = EXTRA_SCALE; - - - /** - * Set the scale level of the figure. A scale value of 1.0 indicates an original - * size when using the current DPI level. - * - * @param scale the scale level. - */ - public void setScaling(double scale); - - - /** - * Set the scale level so that the figure fits into the given bounds. - * - * @param bounds the bounds of the figure. - */ - public void setScaling(Dimension bounds); - - - /** - * Return the scale level of the figure. A scale value of 1.0 indicates an original - * size when using the current DPI level. - * - * @return the current scale level. - */ - public double getScaling(); - - - /** - * Return the scale of the figure on px/m. - * - * @return the current scale value. - */ - public double getAbsoluteScale(); - - - /** - * Return the pixel coordinates of the figure origin. - * - * @return the pixel coordinates of the figure origin. - */ - public Dimension getOrigin(); - - - /** - * Get the amount of blank space left around the figure. - * - * @return the amount of horizontal and vertical space left on both sides of the figure. - */ - public Dimension getBorderPixels(); - - /** - * Set the amount of blank space left around the figure. - * - * @param width the amount of horizontal space left on both sides of the figure. - * @param height the amount of vertical space left on both sides of the figure. - */ - public void setBorderPixels(int width, int height); -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/ScaleScrollPane.java b/core/src/net/sf/openrocket/gui/scalefigure/ScaleScrollPane.java deleted file mode 100644 index a45dd51a..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/ScaleScrollPane.java +++ /dev/null @@ -1,394 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.util.EventObject; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; - -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.gui.components.UnitSelector; -import net.sf.openrocket.unit.Tick; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.StateChangeListener; - - - -/** - * A scroll pane that holds a {@link ScaleFigure} and includes rulers that show - * natural units. The figure can be moved by dragging on the figure. - *

- * This class implements both MouseListener and - * MouseMotionListener. If subclasses require extra functionality - * (e.g. checking for clicks) then these methods may be overridden, and only unhandled - * events passed to this class. - * - * @author Sampo Niskanen - */ -public class ScaleScrollPane extends JScrollPane - implements MouseListener, MouseMotionListener { - - public static final int RULER_SIZE = 20; - public static final int MINOR_TICKS = 3; - public static final int MAJOR_TICKS = 30; - - - private JComponent component; - private ScaleFigure figure; - - private DoubleModel rulerUnit; - private Ruler horizontalRuler; - private Ruler verticalRuler; - - private final boolean allowFit; - - private boolean fit = false; - - - /** - * Create a scale scroll pane that allows fitting. - * - * @param component the component to contain (must implement ScaleFigure) - */ - public ScaleScrollPane(JComponent component) { - this(component, true); - } - - /** - * Create a scale scroll pane. - * - * @param component the component to contain (must implement ScaleFigure) - * @param allowFit whether automatic fitting of the figure is allowed - */ - public ScaleScrollPane(JComponent component, boolean allowFit) { - super(component); - - if (!(component instanceof ScaleFigure)) { - throw new IllegalArgumentException("component must implement ScaleFigure"); - } - - this.component = component; - this.figure = (ScaleFigure) component; - this.allowFit = allowFit; - - - rulerUnit = new DoubleModel(0.0, UnitGroup.UNITS_LENGTH); - rulerUnit.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - ScaleScrollPane.this.component.repaint(); - } - }); - horizontalRuler = new Ruler(Ruler.HORIZONTAL); - verticalRuler = new Ruler(Ruler.VERTICAL); - this.setColumnHeaderView(horizontalRuler); - this.setRowHeaderView(verticalRuler); - - UnitSelector selector = new UnitSelector(rulerUnit); - selector.setFont(new Font("SansSerif", Font.PLAIN, 8)); - this.setCorner(JScrollPane.UPPER_LEFT_CORNER, selector); - this.setCorner(JScrollPane.UPPER_RIGHT_CORNER, new JPanel()); - this.setCorner(JScrollPane.LOWER_LEFT_CORNER, new JPanel()); - this.setCorner(JScrollPane.LOWER_RIGHT_CORNER, new JPanel()); - - this.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); - - - viewport.addMouseListener(this); - viewport.addMouseMotionListener(this); - - figure.addChangeListener(new StateChangeListener() { - @Override - public void stateChanged(EventObject e) { - horizontalRuler.updateSize(); - verticalRuler.updateSize(); - if (fit) { - setFitting(true); - } - } - }); - - viewport.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - if (fit) { - setFitting(true); - } - } - }); - - } - - public ScaleFigure getFigure() { - return figure; - } - - - /** - * Return whether automatic fitting of the figure is allowed. - */ - public boolean isFittingAllowed() { - return allowFit; - } - - /** - * Return whether the figure is currently automatically fitted within the component bounds. - */ - public boolean isFitting() { - return fit; - } - - /** - * Set whether the figure is automatically fitted within the component bounds. - * - * @throws BugException if automatic fitting is disallowed and fit is true - */ - public void setFitting(boolean fit) { - if (fit && !allowFit) { - throw new BugException("Attempting to fit figure not allowing fit."); - } - this.fit = fit; - if (fit) { - setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); - validate(); - Dimension view = viewport.getExtentSize(); - figure.setScaling(view); - } else { - setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); - } - } - - - - public double getScaling() { - return figure.getScaling(); - } - - public double getScale() { - return figure.getAbsoluteScale(); - } - - public void setScaling(double scale) { - if (fit) { - setFitting(false); - } - figure.setScaling(scale); - horizontalRuler.repaint(); - verticalRuler.repaint(); - } - - - public Unit getCurrentUnit() { - return rulerUnit.getCurrentUnit(); - } - - - //////////////// Mouse handlers //////////////// - - - private int dragStartX = 0; - private int dragStartY = 0; - private Rectangle dragRectangle = null; - - @Override - public void mousePressed(MouseEvent e) { - dragStartX = e.getX(); - dragStartY = e.getY(); - dragRectangle = viewport.getViewRect(); - } - - @Override - public void mouseReleased(MouseEvent e) { - dragRectangle = null; - } - - @Override - public void mouseDragged(MouseEvent e) { - if (dragRectangle == null) { - return; - } - - dragRectangle.setLocation(dragStartX - e.getX(), dragStartY - e.getY()); - - dragStartX = e.getX(); - dragStartY = e.getY(); - - viewport.scrollRectToVisible(dragRectangle); - } - - @Override - public void mouseClicked(MouseEvent e) { - } - - @Override - public void mouseEntered(MouseEvent e) { - } - - @Override - public void mouseExited(MouseEvent e) { - } - - @Override - public void mouseMoved(MouseEvent e) { - } - - - - //////////////// The view port rulers //////////////// - - - private class Ruler extends JComponent { - public static final int HORIZONTAL = 0; - public static final int VERTICAL = 1; - - private final int orientation; - - public Ruler(int orientation) { - this.orientation = orientation; - updateSize(); - - rulerUnit.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - Ruler.this.repaint(); - } - }); - } - - - public void updateSize() { - Dimension d = component.getPreferredSize(); - if (orientation == HORIZONTAL) { - setPreferredSize(new Dimension(d.width + 10, RULER_SIZE)); - } else { - setPreferredSize(new Dimension(RULER_SIZE, d.height + 10)); - } - revalidate(); - repaint(); - } - - private double fromPx(int px) { - Dimension origin = figure.getOrigin(); - if (orientation == HORIZONTAL) { - px -= origin.width; - } else { - // px = -(px - origin.height); - px -= origin.height; - } - return px / figure.getAbsoluteScale(); - } - - private int toPx(double l) { - Dimension origin = figure.getOrigin(); - int px = (int) (l * figure.getAbsoluteScale() + 0.5); - if (orientation == HORIZONTAL) { - px += origin.width; - } else { - px = px + origin.height; - // px += origin.height; - } - return px; - } - - - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g; - - Rectangle area = g2.getClipBounds(); - - // Fill area with background color - g2.setColor(getBackground()); - g2.fillRect(area.x, area.y, area.width, area.height + 100); - - - int startpx, endpx; - if (orientation == HORIZONTAL) { - startpx = area.x; - endpx = area.x + area.width; - } else { - startpx = area.y; - endpx = area.y + area.height; - } - - Unit unit = rulerUnit.getCurrentUnit(); - double start, end, minor, major; - start = fromPx(startpx); - end = fromPx(endpx); - minor = MINOR_TICKS / figure.getAbsoluteScale(); - major = MAJOR_TICKS / figure.getAbsoluteScale(); - - Tick[] ticks = unit.getTicks(start, end, minor, major); - - - // Set color & hints - g2.setColor(Color.BLACK); - g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - RenderingHints.VALUE_STROKE_NORMALIZE); - g2.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - for (Tick t : ticks) { - int position = toPx(t.value); - drawTick(g2, position, t); - } - } - - private void drawTick(Graphics g, int position, Tick t) { - int length; - String str = null; - if (t.major) { - length = RULER_SIZE / 2; - } else { - if (t.notable) - length = RULER_SIZE / 3; - else - length = RULER_SIZE / 6; - } - - // Set font - if (t.major) { - str = rulerUnit.getCurrentUnit().toString(t.value); - if (t.notable) - g.setFont(new Font("SansSerif", Font.BOLD, 9)); - else - g.setFont(new Font("SansSerif", Font.PLAIN, 9)); - } - - // Draw tick & text - if (orientation == HORIZONTAL) { - g.drawLine(position, RULER_SIZE - length, position, RULER_SIZE); - if (str != null) - g.drawString(str, position, RULER_SIZE - length - 1); - } else { - g.drawLine(RULER_SIZE - length, position, RULER_SIZE, position); - if (str != null) - g.drawString(str, 1, position - 1); - } - } - } -} diff --git a/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java b/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java deleted file mode 100644 index fba7aaa7..00000000 --- a/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java +++ /dev/null @@ -1,168 +0,0 @@ -package net.sf.openrocket.gui.scalefigure; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.text.DecimalFormat; -import java.util.Arrays; -import java.util.EventObject; -import java.util.Locale; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JPanel; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.gui.util.Icons; -import net.sf.openrocket.util.StateChangeListener; - -public class ScaleSelector extends JPanel { - - // Ready zoom settings - private static final DecimalFormat PERCENT_FORMAT = new DecimalFormat("0.#%"); - - private static final double[] ZOOM_LEVELS = { 0.15, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0 }; - private static final String ZOOM_FIT = "Fit"; - private static final String[] ZOOM_SETTINGS; - static { - ZOOM_SETTINGS = new String[ZOOM_LEVELS.length + 1]; - for (int i = 0; i < ZOOM_LEVELS.length; i++) - ZOOM_SETTINGS[i] = PERCENT_FORMAT.format(ZOOM_LEVELS[i]); - ZOOM_SETTINGS[ZOOM_SETTINGS.length - 1] = ZOOM_FIT; - } - - - private final ScaleScrollPane scrollPane; - private JComboBox zoomSelector; - - - public ScaleSelector(ScaleScrollPane scroll) { - super(new MigLayout()); - - this.scrollPane = scroll; - - // Zoom out button - JButton button = new JButton(Icons.ZOOM_OUT); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - double scale = scrollPane.getScaling(); - scale = getPreviousScale(scale); - scrollPane.setScaling(scale); - } - }); - add(button, "gap"); - - // Zoom level selector - String[] settings = ZOOM_SETTINGS; - if (!scrollPane.isFittingAllowed()) { - settings = Arrays.copyOf(settings, settings.length - 1); - } - - zoomSelector = new JComboBox(settings); - zoomSelector.setEditable(true); - setZoomText(); - zoomSelector.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - String text = (String) zoomSelector.getSelectedItem(); - text = text.replaceAll("%", "").trim(); - - if (text.toLowerCase(Locale.getDefault()).startsWith(ZOOM_FIT.toLowerCase(Locale.getDefault())) && - scrollPane.isFittingAllowed()) { - scrollPane.setFitting(true); - setZoomText(); - return; - } - - double n = Double.parseDouble(text); - n /= 100; - if (n <= 0.005) - n = 0.005; - - scrollPane.setScaling(n); - setZoomText(); - } catch (NumberFormatException ignore) { - } finally { - setZoomText(); - } - } - }); - scrollPane.getFigure().addChangeListener(new StateChangeListener() { - @Override - public void stateChanged(EventObject e) { - setZoomText(); - } - }); - add(zoomSelector, "gap rel"); - - - // Zoom in button - button = new JButton(Icons.ZOOM_IN); - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - double scale = scrollPane.getScaling(); - scale = getNextScale(scale); - scrollPane.setScaling(scale); - } - }); - add(button, "gapleft rel"); - - } - - - - private void setZoomText() { - String text; - double zoom = scrollPane.getScaling(); - text = PERCENT_FORMAT.format(zoom); - if (scrollPane.isFitting()) { - text = "Fit (" + text + ")"; - } - if (!text.equals(zoomSelector.getSelectedItem())) - zoomSelector.setSelectedItem(text); - } - - - - private double getPreviousScale(double scale) { - int i; - for (i = 0; i < ZOOM_LEVELS.length - 1; i++) { - if (scale > ZOOM_LEVELS[i] + 0.05 && scale < ZOOM_LEVELS[i + 1] + 0.05) - return ZOOM_LEVELS[i]; - } - if (scale > ZOOM_LEVELS[ZOOM_LEVELS.length / 2]) { - // scale is large, drop to next lowest full 100% - scale = Math.ceil(scale - 1.05); - return Math.max(scale, ZOOM_LEVELS[i]); - } - // scale is small - return scale / 1.5; - } - - - private double getNextScale(double scale) { - int i; - for (i = 0; i < ZOOM_LEVELS.length - 1; i++) { - if (scale > ZOOM_LEVELS[i] - 0.05 && scale < ZOOM_LEVELS[i + 1] - 0.05) - return ZOOM_LEVELS[i + 1]; - } - if (scale > ZOOM_LEVELS[ZOOM_LEVELS.length / 2]) { - // scale is large, give next full 100% - scale = Math.floor(scale + 1.05); - return scale; - } - return scale * 1.5; - } - - @Override - public void setEnabled(boolean b){ - for ( Component c : getComponents() ){ - c.setEnabled(b); - } - super.setEnabled(b); - } - -} diff --git a/core/src/net/sf/openrocket/gui/util/ColorConversion.java b/core/src/net/sf/openrocket/gui/util/ColorConversion.java deleted file mode 100644 index e9a2eae4..00000000 --- a/core/src/net/sf/openrocket/gui/util/ColorConversion.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.sf.openrocket.gui.util; - -public class ColorConversion { - - public static java.awt.Color toAwtColor( net.sf.openrocket.util.Color c ) { - if ( c == null ) { - return null; - } - return new java.awt.Color(c.getRed(),c.getGreen(),c.getBlue(),c.getAlpha()); - } - - public static net.sf.openrocket.util.Color fromAwtColor( java.awt.Color c ) { - if ( c == null ) { - return null; - } - return new net.sf.openrocket.util.Color( c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); - } -} diff --git a/core/src/net/sf/openrocket/gui/util/ConcurrentProgressMonitor.java b/core/src/net/sf/openrocket/gui/util/ConcurrentProgressMonitor.java deleted file mode 100644 index b6aa6ea3..00000000 --- a/core/src/net/sf/openrocket/gui/util/ConcurrentProgressMonitor.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.awt.Component; - -import javax.swing.ProgressMonitor; -import javax.swing.SwingUtilities; - - -/** - * A thread-safe ProgressMonitor. This class may be instantiated - * and the method {@link #setProgress(int)} called safely from any thread. - *

- * Why the FSCK&!#&% isn't the default API version thread-safe?!?! - * - * @author Sampo Niskanen - */ -public class ConcurrentProgressMonitor extends ProgressMonitor { - - public ConcurrentProgressMonitor(Component parentComponent, Object message, - String note, int min, int max) { - super(parentComponent, message, note, min, max); - } - - @Override - public void setProgress(final int nv) { - - if (SwingUtilities.isEventDispatchThread()) { - super.setProgress(nv); - } else { - - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - ConcurrentProgressMonitor.super.setProgress(nv); - } - - }); - } - } - - - @Override - public void close() { - if (SwingUtilities.isEventDispatchThread()) { - super.close(); - } else { - - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - ConcurrentProgressMonitor.super.close(); - } - - }); - } - } - - -} diff --git a/core/src/net/sf/openrocket/gui/util/ConcurrentProgressMonitorInputStream.java b/core/src/net/sf/openrocket/gui/util/ConcurrentProgressMonitorInputStream.java deleted file mode 100644 index ccc0d799..00000000 --- a/core/src/net/sf/openrocket/gui/util/ConcurrentProgressMonitorInputStream.java +++ /dev/null @@ -1,144 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.awt.Component; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; - - - -/** - * A functional equivalent of ProgressMonitorInputStream which - * uses {@link ConcurrentProgressMonitor} and leaves the progress dialog open - * to be manually closed later on. - */ - -public class ConcurrentProgressMonitorInputStream extends FilterInputStream { - private ConcurrentProgressMonitor monitor; - private int nread = 0; - private int size = 0; - - - /** - * Constructs an object to monitor the progress of an input stream. - * - * @param message Descriptive text to be placed in the dialog box - * if one is popped up. - * @param parentComponent The component triggering the operation - * being monitored. - * @param in The input stream to be monitored. - */ - public ConcurrentProgressMonitorInputStream(Component parentComponent, - Object message, InputStream in) { - super(in); - try { - size = in.available(); - } catch (IOException ioe) { - size = 0; - } - monitor = new ConcurrentProgressMonitor(parentComponent, message, null, 0, - size + 1); - } - - - /** - * Get the ProgressMonitor object being used by this stream. Normally - * this isn't needed unless you want to do something like change the - * descriptive text partway through reading the file. - * @return the ProgressMonitor object used by this object - */ - public ConcurrentProgressMonitor getProgressMonitor() { - return monitor; - } - - - /** - * Overrides FilterInputStream.read - * to update the progress monitor after the read. - */ - @Override - public int read() throws IOException { - int c = in.read(); - if (c >= 0) - monitor.setProgress(++nread); - if (monitor.isCanceled()) { - InterruptedIOException exc = new InterruptedIOException("progress"); - exc.bytesTransferred = nread; - throw exc; - } - return c; - } - - - /** - * Overrides FilterInputStream.read - * to update the progress monitor after the read. - */ - @Override - public int read(byte b[]) throws IOException { - int nr = in.read(b); - if (nr > 0) - monitor.setProgress(nread += nr); - if (monitor.isCanceled()) { - InterruptedIOException exc = new InterruptedIOException("progress"); - exc.bytesTransferred = nread; - throw exc; - } - return nr; - } - - - /** - * Overrides FilterInputStream.read - * to update the progress monitor after the read. - */ - @Override - public int read(byte b[], int off, int len) throws IOException { - int nr = in.read(b, off, len); - if (nr > 0) - monitor.setProgress(nread += nr); - if (monitor.isCanceled()) { - InterruptedIOException exc = new InterruptedIOException("progress"); - exc.bytesTransferred = nread; - throw exc; - } - return nr; - } - - - /** - * Overrides FilterInputStream.skip - * to update the progress monitor after the skip. - */ - @Override - public long skip(long n) throws IOException { - long nr = in.skip(n); - if (nr > 0) - monitor.setProgress(nread += nr); - return nr; - } - - - /** - * Overrides FilterInputStream.close - * to close the progress monitor as well as the stream. - */ - @Override - public void close() throws IOException { - in.close(); - monitor.close(); - } - - - /** - * Overrides FilterInputStream.reset - * to reset the progress monitor as well as the stream. - */ - @Override - public synchronized void reset() throws IOException { - in.reset(); - nread = size - in.available(); - monitor.setProgress(nread); - } -} diff --git a/core/src/net/sf/openrocket/gui/util/CustomFinImporter.java b/core/src/net/sf/openrocket/gui/util/CustomFinImporter.java deleted file mode 100644 index ae2f7bf4..00000000 --- a/core/src/net/sf/openrocket/gui/util/CustomFinImporter.java +++ /dev/null @@ -1,278 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.ListIterator; - -import javax.imageio.ImageIO; - -import net.sf.openrocket.l10n.LocalizedIOException; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.Coordinate; - -public class CustomFinImporter { - - private enum FacingDirections { - UP, DOWN, LEFT, RIGHT - } - - private int startX; - private FacingDirections facing; - private int currentX, currentY; - - - - public List getPoints(File file) throws IOException { - ArrayList points = new ArrayList(); - - BufferedImage pic = ImageIO.read(file); - - // Set initial values for parsing - startX = -1; - facing = FacingDirections.UP; - - if (!validateImage(pic)) { - throw new LocalizedIOException("CustomFinImport.badFinImage"); - } - - // Load the fin - points.add(Coordinate.NUL); - loadFin(pic, points); - - // Optimize the loaded fin - int count; - do { - count = points.size(); - optimizePoints(points); - } while (count != points.size()); - - return points; - } - - - private boolean validateImage(BufferedImage pic) { - int height = pic.getHeight(); - int width = pic.getWidth(); - boolean bottomEdgeFound = false; - - for (int x = 0; x < width; ++x) { - for (int y = 0; y < height; ++y) { - int pixel = pic.getRGB(x, y) & 0x00FFFFFF; // Clear alpha, we don't care about it - // Convert to black & white - int red = (pixel & 0x00FF0000) >> 16; - int green = (pixel & 0x0000FF00) >> 8; - int blue = (pixel & 0x000000FF); - pixel = (int)(0.299*red + 0.587*green + 0.114*blue); - if (pixel > 200) - pixel = 0xFFFFFF; // White - else - pixel = 0; // Black - pic.setRGB(x, y, pixel); - if (y == height - 1) { - if (pixel == 0) { - bottomEdgeFound = true; - if (startX == -1) - startX = x; - } - } - } - } - return bottomEdgeFound; - } - - private void loadFin(BufferedImage pic, ArrayList points) { - int height = pic.getHeight(); - Boolean offBottom = false; - - currentX = startX; - currentY = height - 1; - - do { - if (checkLeftIsFin(pic, currentX, currentY)) - rotateLeft(); - else if (checkForwardIsFin(pic, currentX, currentY)) { - // Do nothing - } else if (checkRightIsFin(pic, currentX, currentY)) - rotateRight(); - else { - turnAround(); - } - - moveForward(pic); - if (currentY < height - 1) - offBottom = true; - if (pixelIsFin(pic, currentX, currentY)) { - double x = (currentX - startX) * 0.001; - double y = (height - currentY - 1) * 0.001; - points.add(new Coordinate(x, y)); - } - } while ((!offBottom) || (currentY < height - 1 && currentY >= 0)); - } - - private boolean pixelIsFin(BufferedImage pic, int x, int y) { - int height = pic.getHeight(); - int width = pic.getWidth(); - - if ((x >= 0) && (x < width) && (y >= 0) && (y < height)) { - int pixel = pic.getRGB(x, y) & 0x00FFFFFF; // Clear alpha, we don't care about it - - if (pixel == 0) // black is fin - return true; - } - return false; - } - - private boolean checkLeftIsFin(BufferedImage pic, int x, int y) { - if (facing == FacingDirections.DOWN) - return pixelIsFin(pic, x + 1, y); - else if (facing == FacingDirections.UP) - return pixelIsFin(pic, x - 1, y); - else if (facing == FacingDirections.LEFT) - return pixelIsFin(pic, x, y + 1); - else if (facing == FacingDirections.RIGHT) - return pixelIsFin(pic, x, y - 1); - else - return false; - } - - private boolean checkRightIsFin(BufferedImage pic, int x, int y) { - if (facing == FacingDirections.DOWN) - return pixelIsFin(pic, x - 1, y); - else if (facing == FacingDirections.UP) - return pixelIsFin(pic, x + 1, y); - else if (facing == FacingDirections.LEFT) - return pixelIsFin(pic, x, y - 1); - else if (facing == FacingDirections.RIGHT) - return pixelIsFin(pic, x, y + 1); - else - return false; - } - - private boolean checkForwardIsFin(BufferedImage pic, int x, int y) { - if (facing == FacingDirections.DOWN) - return pixelIsFin(pic, x, y + 1); - else if (facing == FacingDirections.UP) - return pixelIsFin(pic, x, y - 1); - else if (facing == FacingDirections.LEFT) - return pixelIsFin(pic, x - 1, y); - else if (facing == FacingDirections.RIGHT) - return pixelIsFin(pic, x + 1, y); - else - return false; - } - - private void rotateLeft() { - if (facing == FacingDirections.UP) - facing = FacingDirections.LEFT; - else if (facing == FacingDirections.RIGHT) - facing = FacingDirections.UP; - else if (facing == FacingDirections.DOWN) - facing = FacingDirections.RIGHT; - else if (facing == FacingDirections.LEFT) - facing = FacingDirections.DOWN; - } - - private void rotateRight() { - if (facing == FacingDirections.UP) - facing = FacingDirections.RIGHT; - else if (facing == FacingDirections.RIGHT) - facing = FacingDirections.DOWN; - else if (facing == FacingDirections.DOWN) - facing = FacingDirections.LEFT; - else if (facing == FacingDirections.LEFT) - facing = FacingDirections.UP; - } - - private void moveForward(BufferedImage pic) { - if (facing == FacingDirections.UP) { - if (currentY > 0) - currentY--; - } else if (facing == FacingDirections.RIGHT) { - if (currentX < pic.getWidth() - 1) - currentX++; - } else if (facing == FacingDirections.DOWN) { - if (currentY < pic.getHeight() - 1) - currentY++; - } else if (facing == FacingDirections.LEFT) { - if (currentX > 0) - currentX--; - } - } - - private void turnAround() { - if (facing == FacingDirections.UP) - facing = FacingDirections.DOWN; - else if (facing == FacingDirections.DOWN) - facing = FacingDirections.UP; - else if (facing == FacingDirections.RIGHT) - facing = FacingDirections.LEFT; - else if (facing == FacingDirections.LEFT) - facing = FacingDirections.RIGHT; - } - - private void optimizePoints(ArrayList points) { - int startIx; - ListIterator start, entry, entry2; - Coordinate startPoint, endPoint, testPoint; - Boolean removedSection; - - startIx = 0; - start = points.listIterator(); - startPoint = start.next(); - while ((start.hasNext()) && (startPoint != points.get(points.size() - 1))) { - removedSection = false; - entry = points.listIterator(points.size()); - endPoint = entry.previous(); - for (; endPoint != startPoint; endPoint = entry.previous()) { - entry2 = points.listIterator(start.nextIndex()); - testPoint = entry2.next(); - for (; testPoint != endPoint; testPoint = entry2.next()) { - if (pointDistanceFromLine(startPoint, endPoint, testPoint) > 0.0008) { - break; - } - } - if ((testPoint == endPoint) && (endPoint != startPoint)) { - // Entire segment was within distance, it's a strait line. - // Remove all but the first and last point - entry2 = points.listIterator(start.nextIndex()); - int nextIx = entry2.nextIndex(); - Coordinate check = entry2.next(); - while ((entry2.nextIndex() != points.size()) && (check != endPoint)) { - entry2.remove(); - nextIx = entry2.nextIndex(); - check = entry2.next(); - } - startIx = nextIx; - start = points.listIterator(startIx); - startPoint = start.next(); - removedSection = true; - break; - } - } - if ((!removedSection) && (endPoint == startPoint)) { - startIx = start.nextIndex(); - if (start.hasNext()) - startPoint = start.next(); - } - } - } - - private double pointDistanceFromLine(Coordinate startPoint, Coordinate endPoint, Coordinate testPoint) { - Coordinate pt = closestPointOnSegment(startPoint, endPoint, testPoint); - - return testPoint.sub(pt).length(); - } - - private Coordinate closestPointOnSegment(Coordinate a, Coordinate b, Coordinate p) { - Coordinate D = b.sub(a); - double numer = p.sub(a).dot(D); - if (numer <= 0.0f) - return a; - double denom = D.dot(D); - if (numer >= denom) - return b; - return a.add(D.multiply(numer / denom)); - } -} diff --git a/core/src/net/sf/openrocket/gui/util/FileHelper.java b/core/src/net/sf/openrocket/gui/util/FileHelper.java deleted file mode 100644 index 7fcdc2a4..00000000 --- a/core/src/net/sf/openrocket/gui/util/FileHelper.java +++ /dev/null @@ -1,174 +0,0 @@ -package net.sf.openrocket.gui.util; - -import net.sf.openrocket.l10n.L10N; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -import javax.imageio.ImageIO; -import javax.swing.*; -import javax.swing.filechooser.FileFilter; -import java.awt.*; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Locale; - -/** - * Helper methods related to user-initiated file manipulation. - *

- * These methods log the necessary information to the debug log. -* - * @author Sampo Niskanen - */ -public final class FileHelper { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - // TODO: HIGH: Rename translation keys - - /** File filter for any rocket designs (*.ork, *.rkt) */ - public static final FileFilter ALL_DESIGNS_FILTER = - new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter1"), - ".ork", ".ork.gz", ".rkt", ".rkt.gz"); - - /** File filter for OpenRocket designs (*.ork) */ - public static final FileFilter OPENROCKET_DESIGN_FILTER = - new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter2"), ".ork", ".ork.gz"); - - /** File filter for RockSim designs (*.rkt) */ - public static final FileFilter ROCKSIM_DESIGN_FILTER = - new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter3"), ".rkt", ".rkt.gz"); - - /** File filter for OpenRocket components and presets (*.orc) */ - public static final FileFilter OPEN_ROCKET_COMPONENT_FILTER = - new SimpleFileFilter(trans.get("BasicFrame.SimpleFileFilter4"), ".orc", ".orc.gz"); - - /** File filter for PDF files (*.pdf) */ - public static final FileFilter PDF_FILTER = - new SimpleFileFilter(trans.get("filetypes.pdf"), ".pdf"); - - /** File filter for CSV files (*.csv) */ - public static final FileFilter CSV_FILE_FILTER = - new SimpleFileFilter(trans.get("SimExpPan.desc"), ".csv"); - - - - - private FileHelper() { - // Prevent instantiation - } - - - public static FileFilter getImageFileFilter() { - String[] extensions = ImageIO.getReaderFileSuffixes(); - for (int i = 0; i < extensions.length; i++) { - extensions[i] = extensions[i].toLowerCase(Locale.ENGLISH); - } - Arrays.sort(extensions); - - StringBuilder sb = new StringBuilder(); - sb.append(trans.get("filetypes.images")); - sb.append(" ("); - for (int i = 0; i < extensions.length; i++) { - sb.append("*.").append(extensions[i]); - if (i < extensions.length - 1) { - sb.append("; "); - } - } - sb.append(")"); - - return new SimpleFileFilter(sb.toString(), extensions); - } - - - /** - * Ensure that the provided file has a file extension. If the file does not have - * any extension, append the provided extension to it. - * - * @param original the original file - * @param extension the extension to append if none exists (without preceding dot) - * @return the resulting file - */ - public static File ensureExtension(File original, String extension) { - - if (original.getName().indexOf('.') < 0) { - log.debug(1, "File name does not contain extension, adding '" + extension + "'"); - String name = original.getAbsolutePath(); - name = name + "." + extension; - return new File(name); - } - - return original; - } - - /** - * Ensure that the provided file has the given file extension. This differs from ensureExtension in that this - * method guarantees that the file will have the extension, whereas ensureExtension only treats the extension - * as a default. - * - * @param original the original file - * @param extension the extension to guarantee (without preceding dot) - * @return the resulting file - */ - public static File forceExtension(File original, String extension) { - - if (!original.getName().toLowerCase(Locale.ENGLISH).endsWith(extension.toLowerCase(Locale.ENGLISH))) { - log.debug(1, "File name does not contain extension, adding '" + extension + "'"); - String name = original.getAbsolutePath(); - if (extension.startsWith(".")) { - name = name + extension; - } - else { - name = name + "." + extension; - } - return new File(name); - } - - return original; - } - - - /** - * Confirm that it is allowed to write to a file. If the file exists, - * a confirmation dialog will be presented to the user to ensure overwriting is ok. - * - * @param file the file that is going to be written. - * @param parent the parent component for the dialog. - * @return true to write, false to abort. - */ - public static boolean confirmWrite(File file, Component parent) { - if (file.exists()) { - log.info(1, "File " + file + " exists, confirming overwrite from user"); - int result = JOptionPane.showConfirmDialog(parent, - L10N.replace(trans.get("error.fileExists.desc"), "{filename}", file.getName()), - trans.get("error.fileExists.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (result != JOptionPane.YES_OPTION) { - log.user(1, "User decided not to overwrite the file"); - return false; - } - log.user(1, "User decided to overwrite the file"); - } - return true; - } - - - /** - * Display an error message to the user that writing a file failed. - * - * @param e the I/O exception that caused the error. - * @param parent the parent component for the dialog. - */ - public static void errorWriting(IOException e, Component parent) { - - log.warn(1, "Error writing to file", e); - JOptionPane.showMessageDialog(parent, - new Object[] { - trans.get("error.writing.desc"), - e.getLocalizedMessage() - }, trans.get("error.writing.title"), JOptionPane.ERROR_MESSAGE); - - } - -} diff --git a/core/src/net/sf/openrocket/gui/util/GUIUtil.java b/core/src/net/sf/openrocket/gui/util/GUIUtil.java deleted file mode 100644 index 4ac68dce..00000000 --- a/core/src/net/sf/openrocket/gui/util/GUIUtil.java +++ /dev/null @@ -1,608 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Image; -import java.awt.KeyboardFocusManager; -import java.awt.Point; -import java.awt.Toolkit; -import java.awt.Window; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.FocusListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.imageio.ImageIO; -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.Action; -import javax.swing.BoundedRangeModel; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultBoundedRangeModel; -import javax.swing.DefaultComboBoxModel; -import javax.swing.DefaultListSelectionModel; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JRootPane; -import javax.swing.JSlider; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.JTree; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.LookAndFeel; -import javax.swing.RootPaneContainer; -import javax.swing.SpinnerModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.border.TitledBorder; -import javax.swing.event.ChangeListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableColumnModel; -import javax.swing.table.DefaultTableModel; -import javax.swing.table.TableColumnModel; -import javax.swing.table.TableModel; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreeSelectionModel; - -import net.sf.openrocket.gui.Resettable; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Invalidatable; -import net.sf.openrocket.util.MemoryManagement; - -public class GUIUtil { - private static final LogHelper log = Application.getLogger(); - - private static final KeyStroke ESCAPE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); - private static final String CLOSE_ACTION_KEY = "escape:WINDOW_CLOSING"; - - private static final List images = new ArrayList(); - static { - loadImage("pix/icon/icon-256.png"); - loadImage("pix/icon/icon-064.png"); - loadImage("pix/icon/icon-048.png"); - loadImage("pix/icon/icon-032.png"); - loadImage("pix/icon/icon-016.png"); - } - - private static void loadImage(String file) { - InputStream is; - - is = ClassLoader.getSystemResourceAsStream(file); - if (is == null) - return; - - try { - Image image = ImageIO.read(is); - images.add(image); - } catch (IOException ignore) { - ignore.printStackTrace(); - } - } - - /** - * Return the DPI setting of the monitor. This is either the setting provided - * by the system or a user-specified DPI setting. - * - * @return the DPI setting to use. - */ - public static double getDPI() { - int dpi = Application.getPreferences().getInt("DPI", 0); // Tenths of a dpi - - if (dpi < 10) { - dpi = Toolkit.getDefaultToolkit().getScreenResolution() * 10; - } - if (dpi < 10) - dpi = 960; - - return (dpi) / 10.0; - } - - - - - /** - * Set suitable options for a single-use disposable dialog. This includes - * setting ESC to close the dialog, adding the appropriate window icons and - * setting the location based on the platform. If defaultButton is provided, - * it is set to the default button action. - *

- * The default button must be already attached to the dialog. - * - * @param dialog the dialog. - * @param defaultButton the default button of the dialog, or null. - */ - public static void setDisposableDialogOptions(JDialog dialog, JButton defaultButton) { - installEscapeCloseOperation(dialog); - setWindowIcons(dialog); - addModelNullingListener(dialog); - dialog.setLocationByPlatform(true); - dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - dialog.pack(); - if (defaultButton != null) { - setDefaultButton(defaultButton); - } - } - - - - /** - * Add the correct action to close a JDialog when the ESC key is pressed. - * The dialog is closed by sending is a WINDOW_CLOSING event. - * - * @param dialog the dialog for which to install the action. - */ - public static void installEscapeCloseOperation(final JDialog dialog) { - Action dispatchClosing = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - log.user("Closing dialog " + dialog); - dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING)); - } - }; - JRootPane root = dialog.getRootPane(); - root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESCAPE, CLOSE_ACTION_KEY); - root.getActionMap().put(CLOSE_ACTION_KEY, dispatchClosing); - } - - - /** - * Set the given button as the default button of the frame/dialog it is in. The button - * must be first attached to the window component hierarchy. - * - * @param button the button to set as the default button. - */ - public static void setDefaultButton(JButton button) { - Window w = SwingUtilities.windowForComponent(button); - if (w == null) { - throw new IllegalArgumentException("Attach button to a window first."); - } - if (!(w instanceof RootPaneContainer)) { - throw new IllegalArgumentException("Button not attached to RootPaneContainer, w=" + w); - } - ((RootPaneContainer) w).getRootPane().setDefaultButton(button); - } - - - - /** - * Change the behavior of a component so that TAB and Shift-TAB cycles the focus of - * the components. This is necessary for e.g. JTextArea. - * - * @param c the component to modify - */ - public static void setTabToFocusing(Component c) { - Set strokes = new HashSet(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB"))); - c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes); - strokes = new HashSet(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB"))); - c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes); - } - - - - /** - * Set the OpenRocket icons to the window icons. - * - * @param window the window to set. - */ - public static void setWindowIcons(Window window) { - window.setIconImages(images); - } - - /** - * Add a listener to the provided window that will call {@link #setNullModels(Component)} - * on the window once it is closed. This method may only be used on single-use - * windows and dialogs, that will never be shown again once closed! - * - * @param window the window to add the listener to. - */ - public static void addModelNullingListener(final Window window) { - window.addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent e) { - log.debug("Clearing all models of window " + window); - setNullModels(window); - MemoryManagement.collectable(window); - } - }); - } - - - - /** - * Set the best available look-and-feel into use. - */ - public static void setBestLAF() { - /* - * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used - * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few - * other alternatives. - */ - try { - // Set system L&F - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - - // Check whether we have an ugly L&F - LookAndFeel laf = UIManager.getLookAndFeel(); - if (laf == null || - laf.getName().matches(".*[mM][oO][tT][iI][fF].*") || - laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) { - - // Search for better LAF - UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels(); - String lafNames[] = { - ".*[gG][tT][kK].*", - ".*[wW][iI][nN].*", - ".*[mM][aA][cC].*", - ".*[aA][qQ][uU][aA].*", - ".*[nN][iI][mM][bB].*" - }; - - lf: for (String lafName : lafNames) { - for (UIManager.LookAndFeelInfo l : info) { - if (l.getName().matches(lafName)) { - UIManager.setLookAndFeel(l.getClassName()); - break lf; - } - } - } - } - } catch (Exception e) { - log.warn("Error setting LAF: " + e); - } - } - - - /** - * Changes the size of the font of the specified component by the given amount. - * - * @param component the component for which to change the font - * @param size the change in the font size - */ - public static void changeFontSize(JComponent component, float size) { - Font font = component.getFont(); - font = font.deriveFont(font.getSize2D() + size); - component.setFont(font); - } - - - - /** - * Automatically remember the size of a window. This stores the window size in the user - * preferences when resizing/maximizing the window and sets the state on the first call. - */ - public static void rememberWindowSize(final Window window) { - window.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - log.debug("Storing size of " + window.getClass().getName() + ": " + window.getSize()); - ((SwingPreferences) Application.getPreferences()).setWindowSize(window.getClass(), window.getSize()); - if (window instanceof JFrame) { - if ((((JFrame) window).getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH) { - log.debug("Storing maximized state of " + window.getClass().getName()); - ((SwingPreferences) Application.getPreferences()).setWindowMaximized(window.getClass()); - } - } - } - }); - - if (((SwingPreferences) Application.getPreferences()).isWindowMaximized(window.getClass())) { - if (window instanceof JFrame) { - ((JFrame) window).setExtendedState(JFrame.MAXIMIZED_BOTH); - } - } else { - Dimension dim = ((SwingPreferences) Application.getPreferences()).getWindowSize(window.getClass()); - if (dim != null) { - window.setSize(dim); - } - } - } - - - /** - * Automatically remember the position of a window. The position is stored in the user preferences - * every time the window is moved and set from there when first calling this method. - */ - public static void rememberWindowPosition(final Window window) { - window.addComponentListener(new ComponentAdapter() { - @Override - public void componentMoved(ComponentEvent e) { - ((SwingPreferences) Application.getPreferences()).setWindowPosition(window.getClass(), window.getLocation()); - } - }); - - // Set window position according to preferences, and set prefs when moving - Point position = ((SwingPreferences) Application.getPreferences()).getWindowPosition(window.getClass()); - if (position != null) { - window.setLocationByPlatform(false); - window.setLocation(position); - } - } - - - public static void setAutomaticColumnTableWidths(JTable table, int max) { - int columns = table.getColumnCount(); - int widths[] = new int[columns]; - Arrays.fill(widths, 1); - - for (int row = 0; row < table.getRowCount(); row++) { - for (int col = 0; col < columns; col++) { - Object value = table.getValueAt(row, col); - //System.out.println("row=" + row + " col=" + col + " : " + value); - widths[col] = Math.max(widths[col], value == null ? 0 : value.toString().length()); - } - } - - - for (int col = 0; col < columns; col++) { - System.err.println("Setting column " + col + " to width " + widths[col]); - table.getColumnModel().getColumn(col).setPreferredWidth(Math.min(widths[col], max) * 100); - } - } - - /** - * Changes the style of the font of the specified border. - * - * @param border the component for which to change the font - * @param style the change in the font style - */ - public static void changeFontStyle(TitledBorder border, int style) { - /* - * The fix of JRE bug #4129681 causes a TitledBorder occasionally to - * return a null font. We try to work around the issue by detecting it - * and reverting to the font of a JLabel instead. - */ - Font font = border.getTitleFont(); - if (font == null) { - log.warn("JRE bug workaround : Border font is null, reverting to JLabel font"); - font = new JLabel().getFont(); - if (font == null) { - log.warn("JRE bug workaround : JLabel font is null, not modifying font"); - return; - } - } - font = font.deriveFont(style); - if (font == null) { - throw new BugException("Derived font is null"); - } - border.setTitleFont(font); - } - - - - /** - * Traverses recursively the component tree, and sets all applicable component - * models to null, so as to remove the listener connections. After calling this - * method the component hierarchy should no longed be used. - *

- * All components that use custom models should be added to this method, as - * there exists no standard way of removing the model from a component. - * - * @param c the component (null is ok) - */ - public static void setNullModels(Component c) { - if (c == null) - return; - - // Remove various listeners - for (ComponentListener l : c.getComponentListeners()) { - c.removeComponentListener(l); - } - for (FocusListener l : c.getFocusListeners()) { - c.removeFocusListener(l); - } - for (MouseListener l : c.getMouseListeners()) { - c.removeMouseListener(l); - } - for (PropertyChangeListener l : c.getPropertyChangeListeners()) { - c.removePropertyChangeListener(l); - } - for (PropertyChangeListener l : c.getPropertyChangeListeners("model")) { - c.removePropertyChangeListener("model", l); - } - for (PropertyChangeListener l : c.getPropertyChangeListeners("action")) { - c.removePropertyChangeListener("action", l); - } - - // Remove models for known components - // Why the FSCK must this be so hard?!?!? - - if (c instanceof JSpinner) { - - JSpinner spinner = (JSpinner) c; - for (ChangeListener l : spinner.getChangeListeners()) { - spinner.removeChangeListener(l); - } - SpinnerModel model = spinner.getModel(); - spinner.setModel(new SpinnerNumberModel()); - if (model instanceof Invalidatable) { - ((Invalidatable) model).invalidate(); - } - - } else if (c instanceof JSlider) { - - JSlider slider = (JSlider) c; - for (ChangeListener l : slider.getChangeListeners()) { - slider.removeChangeListener(l); - } - BoundedRangeModel model = slider.getModel(); - slider.setModel(new DefaultBoundedRangeModel()); - if (model instanceof Invalidatable) { - ((Invalidatable) model).invalidate(); - } - - } else if (c instanceof JComboBox) { - - JComboBox combo = (JComboBox) c; - for (ActionListener l : combo.getActionListeners()) { - combo.removeActionListener(l); - } - ComboBoxModel model = combo.getModel(); - combo.setModel(new DefaultComboBoxModel()); - if (model instanceof Invalidatable) { - ((Invalidatable) model).invalidate(); - } - - } else if (c instanceof AbstractButton) { - - AbstractButton button = (AbstractButton) c; - for (ActionListener l : button.getActionListeners()) { - button.removeActionListener(l); - } - Action model = button.getAction(); - button.setAction(new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - } - }); - if (model instanceof Invalidatable) { - ((Invalidatable) model).invalidate(); - } - - } else if (c instanceof JTable) { - - JTable table = (JTable) c; - TableModel model1 = table.getModel(); - table.setModel(new DefaultTableModel()); - if (model1 instanceof Invalidatable) { - ((Invalidatable) model1).invalidate(); - } - - TableColumnModel model2 = table.getColumnModel(); - table.setColumnModel(new DefaultTableColumnModel()); - if (model2 instanceof Invalidatable) { - ((Invalidatable) model2).invalidate(); - } - - ListSelectionModel model3 = table.getSelectionModel(); - table.setSelectionModel(new DefaultListSelectionModel()); - if (model3 instanceof Invalidatable) { - ((Invalidatable) model3).invalidate(); - } - - } else if (c instanceof JTree) { - - JTree tree = (JTree) c; - TreeModel model1 = tree.getModel(); - tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode())); - if (model1 instanceof Invalidatable) { - ((Invalidatable) model1).invalidate(); - } - - TreeSelectionModel model2 = tree.getSelectionModel(); - tree.setSelectionModel(new DefaultTreeSelectionModel()); - if (model2 instanceof Invalidatable) { - ((Invalidatable) model2).invalidate(); - } - - } else if (c instanceof Resettable) { - - ((Resettable) c).resetModel(); - - } - - // Recurse the component - if (c instanceof Container) { - Component[] cs = ((Container) c).getComponents(); - for (Component sub : cs) - setNullModels(sub); - } - - } - - - - /** - * A mouse listener that toggles the state of a boolean value in a table model - * when clicked on another column of the table. - *

- * NOTE: If the table model does not extend AbstractTableModel, the model must - * fire a change event (which in normal table usage is not necessary). - * - * @author Sampo Niskanen - */ - public static class BooleanTableClickListener extends MouseAdapter { - - private final JTable table; - private final int clickColumn; - private final int booleanColumn; - - - public BooleanTableClickListener(JTable table) { - this(table, 1, 0); - } - - - public BooleanTableClickListener(JTable table, int clickColumn, int booleanColumn) { - this.table = table; - this.clickColumn = clickColumn; - this.booleanColumn = booleanColumn; - } - - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() != MouseEvent.BUTTON1) - return; - - Point p = e.getPoint(); - int col = table.columnAtPoint(p); - if (col < 0) - return; - col = table.convertColumnIndexToModel(col); - if (col != clickColumn) - return; - - int row = table.rowAtPoint(p); - if (row < 0) - return; - row = table.convertRowIndexToModel(row); - if (row < 0) - return; - - TableModel model = table.getModel(); - Object value = model.getValueAt(row, booleanColumn); - - if (!(value instanceof Boolean)) { - throw new IllegalStateException("Table value at row=" + row + " col=" + - booleanColumn + " is not a Boolean, value=" + value); - } - - Boolean b = (Boolean) value; - b = !b; - model.setValueAt(b, row, booleanColumn); - if (model instanceof AbstractTableModel) { - ((AbstractTableModel) model).fireTableCellUpdated(row, booleanColumn); - } - } - - } - -} diff --git a/core/src/net/sf/openrocket/gui/util/Icons.java b/core/src/net/sf/openrocket/gui/util/Icons.java deleted file mode 100644 index 0fa2b67c..00000000 --- a/core/src/net/sf/openrocket/gui/util/Icons.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.net.URL; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.swing.Icon; -import javax.swing.ImageIcon; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - - -public class Icons { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - static { - log.debug("Starting to load icons"); - } - - /** - * Icons used for showing the status of a simulation (up to date, out of date, etc). - */ - public static final Map SIMULATION_STATUS_ICON_MAP; - static { - HashMap map = new HashMap(); - map.put(Simulation.Status.NOT_SIMULATED, loadImageIcon("pix/spheres/gray-16x16.png", "Not simulated")); - map.put(Simulation.Status.UPTODATE, loadImageIcon("pix/spheres/green-16x16.png", "Up to date")); - map.put(Simulation.Status.LOADED, loadImageIcon("pix/spheres/yellow-16x16.png", "Loaded from file")); - map.put(Simulation.Status.OUTDATED, loadImageIcon("pix/spheres/red-16x16.png", "Out-of-date")); - map.put(Simulation.Status.EXTERNAL, loadImageIcon("pix/spheres/blue-16x16.png", "Imported data")); - SIMULATION_STATUS_ICON_MAP = Collections.unmodifiableMap(map); - } - - public static final Icon SIMULATION_LISTENER_OK; - public static final Icon SIMULATION_LISTENER_ERROR; - static { - SIMULATION_LISTENER_OK = SIMULATION_STATUS_ICON_MAP.get(Simulation.Status.UPTODATE); - SIMULATION_LISTENER_ERROR = SIMULATION_STATUS_ICON_MAP.get(Simulation.Status.OUTDATED); - } - - - public static final Icon FILE_NEW = loadImageIcon("pix/icons/document-new.png", "New document"); - public static final Icon FILE_OPEN = loadImageIcon("pix/icons/document-open.png", "Open document"); - public static final Icon FILE_OPEN_EXAMPLE = loadImageIcon("pix/icons/document-open-example.png", "Open example document"); - public static final Icon FILE_SAVE = loadImageIcon("pix/icons/document-save.png", "Save document"); - public static final Icon FILE_SAVE_AS = loadImageIcon("pix/icons/document-save-as.png", "Save document as"); - public static final Icon FILE_PRINT = loadImageIcon("pix/icons/document-print.png", "Print document"); - public static final Icon FILE_CLOSE = loadImageIcon("pix/icons/document-close.png", "Close document"); - public static final Icon FILE_QUIT = loadImageIcon("pix/icons/application-exit.png", "Quit OpenRocket"); - - public static final Icon EDIT_UNDO = loadImageIcon("pix/icons/edit-undo.png", trans.get("Icons.Undo")); - public static final Icon EDIT_REDO = loadImageIcon("pix/icons/edit-redo.png", trans.get("Icons.Redo")); - public static final Icon EDIT_CUT = loadImageIcon("pix/icons/edit-cut.png", "Cut"); - public static final Icon EDIT_COPY = loadImageIcon("pix/icons/edit-copy.png", "Copy"); - public static final Icon EDIT_PASTE = loadImageIcon("pix/icons/edit-paste.png", "Paste"); - public static final Icon EDIT_DELETE = loadImageIcon("pix/icons/edit-delete.png", "Delete"); - public static final Icon EDIT_SCALE = loadImageIcon("pix/icons/edit-scale.png", "Scale"); - - public static final Icon HELP_ABOUT = loadImageIcon("pix/icons/help-about.png", "About"); - public static final Icon HELP_LICENSE = loadImageIcon("pix/icons/help-license.png", "License"); - public static final Icon HELP_BUG_REPORT = loadImageIcon("pix/icons/help-bug.png", "Bug report"); - public static final Icon HELP_DEBUG_LOG = loadImageIcon("pix/icons/help-log.png", "Debug log"); - public static final Icon HELP_TOURS = loadImageIcon("pix/icons/help-tours.png", "Guided tours"); - - public static final Icon ZOOM_IN = loadImageIcon("pix/icons/zoom-in.png", "Zoom in"); - public static final Icon ZOOM_OUT = loadImageIcon("pix/icons/zoom-out.png", "Zoom out"); - - public static final Icon PREFERENCES = loadImageIcon("pix/icons/preferences.png", "Preferences"); - - public static final Icon DELETE = loadImageIcon("pix/icons/delete.png", "Delete"); - public static final Icon EDIT = loadImageIcon("pix/icons/pencil.png", "Edit"); - public static final Icon UP = loadImageIcon("pix/icons/up.png", "Up"); - public static final Icon DOWN = loadImageIcon("pix/icons/down.png", "Down"); - - public static final Icon NOT_FAVORITE = loadImageIcon("pix/icons/star_silver.png", "Not favorite"); - public static final Icon FAVORITE = loadImageIcon("pix/icons/star_gold.png", "Favorite"); - - - static { - log.debug("Icons loaded"); - } - - /** - * Load an ImageIcon from the specified file. The file is obtained as a system - * resource from the normal classpath. If the file cannot be loaded a bug dialog - * is opened and null is returned. - * - * @param file the file to load. - * @param name the description of the icon. - * @return the ImageIcon, or null if could not be loaded (after the user closes the dialog) - */ - public static ImageIcon loadImageIcon(String file, String name) { - if (System.getProperty("openrocket.unittest") != null) { - return new ImageIcon(); - } - - URL url = ClassLoader.getSystemResource(file); - if (url == null) { - Application.getExceptionHandler().handleErrorCondition("Image file " + file + " not found, ignoring."); - return null; - } - return new ImageIcon(url, name); - } -} diff --git a/core/src/net/sf/openrocket/gui/util/OpenFileWorker.java b/core/src/net/sf/openrocket/gui/util/OpenFileWorker.java deleted file mode 100644 index da193c16..00000000 --- a/core/src/net/sf/openrocket/gui/util/OpenFileWorker.java +++ /dev/null @@ -1,175 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; - -import javax.swing.SwingWorker; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.DatabaseMotorFinder; -import net.sf.openrocket.file.RocketLoader; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - - -/** - * A SwingWorker thread that opens a rocket design file. - * - * @author Sampo Niskanen - */ -public class OpenFileWorker extends SwingWorker { - private static final LogHelper log = Application.getLogger(); - - private final File file; - private final InputStream stream; - private final RocketLoader loader; - - public OpenFileWorker(File file, RocketLoader loader) { - this.file = file; - this.stream = null; - this.loader = loader; - } - - - public OpenFileWorker(InputStream stream, RocketLoader loader) { - this.stream = stream; - this.file = null; - this.loader = loader; - } - - public RocketLoader getRocketLoader() { - return loader; - } - - @Override - protected OpenRocketDocument doInBackground() throws Exception { - InputStream is; - - // Get the correct input stream - if (file != null) { - is = new FileInputStream(file); - } else { - is = stream; - } - - // Buffer stream unless already buffered - if (!(is instanceof BufferedInputStream)) { - is = new BufferedInputStream(is); - } - - // Encapsulate in a ProgressInputStream - is = new ProgressInputStream(is); - - try { - return loader.load(is, new DatabaseMotorFinder()); - } finally { - try { - is.close(); - } catch (Exception e) { - Application.getExceptionHandler().handleErrorCondition("Error closing file", e); - } - } - } - - - - - private class ProgressInputStream extends FilterInputStream { - - private final int size; - private int readBytes = 0; - private int progress = -1; - - protected ProgressInputStream(InputStream in) { - super(in); - int s; - try { - s = in.available(); - } catch (IOException e) { - log.info("Exception while estimating available bytes!", e); - s = 0; - } - size = Math.max(s, 1); - } - - - - @Override - public int read() throws IOException { - int c = in.read(); - if (c >= 0) { - readBytes++; - setProgress(); - } - if (isCancelled()) { - throw new InterruptedIOException("OpenFileWorker was cancelled"); - } - return c; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int n = in.read(b, off, len); - if (n > 0) { - readBytes += n; - setProgress(); - } - if (isCancelled()) { - throw new InterruptedIOException("OpenFileWorker was cancelled"); - } - return n; - } - - @Override - public int read(byte[] b) throws IOException { - int n = in.read(b); - if (n > 0) { - readBytes += n; - setProgress(); - } - if (isCancelled()) { - throw new InterruptedIOException("OpenFileWorker was cancelled"); - } - return n; - } - - @Override - public long skip(long n) throws IOException { - long nr = in.skip(n); - if (nr > 0) { - readBytes += nr; - setProgress(); - } - if (isCancelled()) { - throw new InterruptedIOException("OpenFileWorker was cancelled"); - } - return nr; - } - - @Override - public synchronized void reset() throws IOException { - in.reset(); - readBytes = size - in.available(); - setProgress(); - if (isCancelled()) { - throw new InterruptedIOException("OpenFileWorker was cancelled"); - } - } - - - - private void setProgress() { - int p = MathUtil.clamp(readBytes * 100 / size, 0, 100); - if (progress != p) { - progress = p; - OpenFileWorker.this.setProgress(progress); - } - } - } -} diff --git a/core/src/net/sf/openrocket/gui/util/ProgressOutputStream.java b/core/src/net/sf/openrocket/gui/util/ProgressOutputStream.java deleted file mode 100644 index 22935736..00000000 --- a/core/src/net/sf/openrocket/gui/util/ProgressOutputStream.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.io.OutputStream; - -import javax.swing.SwingWorker; - -import net.sf.openrocket.util.MathUtil; - - -public abstract class ProgressOutputStream extends FilterOutputStream { - - private final int totalBytes; - private final SwingWorker worker; - private int writtenBytes = 0; - private int progress = -1; - - public ProgressOutputStream(OutputStream out, int estimate, SwingWorker worker) { - super(out); - this.totalBytes = estimate; - this.worker = worker; - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - out.write(b, off, len); - writtenBytes += len; - setProgress(); - if (worker.isCancelled()) { - throw new InterruptedIOException("SaveFileWorker was cancelled"); - } - } - - @Override - public void write(byte[] b) throws IOException { - out.write(b); - writtenBytes += b.length; - setProgress(); - if (worker.isCancelled()) { - throw new InterruptedIOException("SaveFileWorker was cancelled"); - } - } - - @Override - public void write(int b) throws IOException { - out.write(b); - writtenBytes++; - setProgress(); - if (worker.isCancelled()) { - throw new InterruptedIOException("SaveFileWorker was cancelled"); - } - } - - - private void setProgress() { - int p = MathUtil.clamp(writtenBytes * 100 / totalBytes, 0, 100); - if (progress != p) { - progress = p; - setProgress(progress); - } - } - - /** - * Set the current progress. The value of progress is guaranteed - * to be between 0 and 100, inclusive. - * - * @param progress the current progress in the range 0-100. - */ - protected abstract void setProgress(int progress); - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/gui/util/SaveCSVWorker.java b/core/src/net/sf/openrocket/gui/util/SaveCSVWorker.java deleted file mode 100644 index efa7d13d..00000000 --- a/core/src/net/sf/openrocket/gui/util/SaveCSVWorker.java +++ /dev/null @@ -1,131 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.awt.Window; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import javax.swing.JOptionPane; -import javax.swing.SwingWorker; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.file.CSVExport; -import net.sf.openrocket.gui.dialogs.SwingWorkerDialog; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.util.BugException; - - -public class SaveCSVWorker extends SwingWorker { - - private static final int BYTES_PER_FIELD_PER_POINT = 7; - - private final File file; - private final Simulation simulation; - private final FlightDataBranch branch; - private final FlightDataType[] fields; - private final Unit[] units; - private final String fieldSeparator; - private final String commentStarter; - private final boolean simulationComments; - private final boolean fieldComments; - private final boolean eventComments; - - - public SaveCSVWorker(File file, Simulation simulation, FlightDataBranch branch, - FlightDataType[] fields, Unit[] units, String fieldSeparator, String commentStarter, - boolean simulationComments, boolean fieldComments, boolean eventComments) { - this.file = file; - this.simulation = simulation; - this.branch = branch; - this.fields = fields; - this.units = units; - this.fieldSeparator = fieldSeparator; - this.commentStarter = commentStarter; - this.simulationComments = simulationComments; - this.fieldComments = fieldComments; - this.eventComments = eventComments; - } - - - @Override - protected Void doInBackground() throws Exception { - - int estimate = BYTES_PER_FIELD_PER_POINT * fields.length * branch.getLength(); - estimate = Math.max(estimate, 1000); - - // Create the ProgressOutputStream that provides progress estimates - ProgressOutputStream os = new ProgressOutputStream( - new BufferedOutputStream(new FileOutputStream(file)), - estimate, this) { - - @Override - protected void setProgress(int progress) { - SaveCSVWorker.this.setProgress(progress); - } - - }; - - try { - CSVExport.exportCSV(os, simulation, branch, fields, units, fieldSeparator, - commentStarter, simulationComments, fieldComments, eventComments); - } finally { - try { - os.close(); - } catch (Exception e) { - Application.getExceptionHandler().handleErrorCondition("Error closing file", e); - } - } - return null; - } - - - - /** - * Exports a CSV file using a progress dialog if necessary. - * - * @return true if the save was successful, false otherwise. - */ - public static boolean export(File file, Simulation simulation, FlightDataBranch branch, - FlightDataType[] fields, Unit[] units, String fieldSeparator, String commentStarter, - boolean simulationComments, boolean fieldComments, boolean eventComments, - Window parent) { - - - SaveCSVWorker worker = new SaveCSVWorker(file, simulation, branch, fields, units, - fieldSeparator, commentStarter, simulationComments, fieldComments, - eventComments); - - if (!SwingWorkerDialog.runWorker(parent, "Exporting flight data", - "Writing " + file.getName() + "...", worker)) { - - // User cancelled the save - file.delete(); - return false; - } - - try { - worker.get(); - } catch (ExecutionException e) { - Throwable cause = e.getCause(); - - if (cause instanceof IOException) { - JOptionPane.showMessageDialog(parent, new String[] { - "An I/O error occurred while saving:", - e.getMessage() }, "Saving failed", JOptionPane.ERROR_MESSAGE); - return false; - } else { - throw new BugException("Unknown error when saving file", e); - } - - } catch (InterruptedException e) { - throw new BugException("EDT was interrupted", e); - } - - return true; - } -} diff --git a/core/src/net/sf/openrocket/gui/util/SaveFileWorker.java b/core/src/net/sf/openrocket/gui/util/SaveFileWorker.java deleted file mode 100644 index 1ccc3145..00000000 --- a/core/src/net/sf/openrocket/gui/util/SaveFileWorker.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; - -import javax.swing.SwingWorker; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.startup.Application; - -public class SaveFileWorker extends SwingWorker { - - private final OpenRocketDocument document; - private final File file; - private final RocketSaver saver; - - public SaveFileWorker(OpenRocketDocument document, File file, RocketSaver saver) { - this.document = document; - this.file = file; - this.saver = saver; - } - - - @Override - protected Void doInBackground() throws Exception { - - int estimate = (int)saver.estimateFileSize(document, - document.getDefaultStorageOptions()); - - // Create the ProgressOutputStream that provides progress estimates - ProgressOutputStream os = new ProgressOutputStream( - new BufferedOutputStream(new FileOutputStream(file)), - estimate, this) { - - @Override - protected void setProgress(int progress) { - SaveFileWorker.this.setProgress(progress); - } - - }; - - try { - saver.save(os, document); - } finally { - try { - os.close(); - } catch (Exception e) { - Application.getExceptionHandler().handleErrorCondition("Error closing file", e); - } - } - return null; - } - -} diff --git a/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java b/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java deleted file mode 100644 index e895b929..00000000 --- a/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.io.File; -import java.util.Locale; - -import javax.swing.filechooser.FileFilter; - -/** - * A FileFilter similar to FileNameExtensionFilter except that - * it allows multipart extensions (.ork.gz), and also implements - * the java.io.FileFilter interface. - * - * @author Sampo Niskanen - */ -public class SimpleFileFilter extends FileFilter implements java.io.FileFilter { - - private final String description; - private final boolean acceptDir; - private final String[] extensions; - - - /** - * Create filter that accepts files with the provided extensions that - * accepts directories as well. - * - * @param description the description of this file filter. - * @param extensions an array of extensions that match this filter. - */ - public SimpleFileFilter(String description, String... extensions) { - this(description, true, extensions); - } - - - /** - * Create filter that accepts files with the provided extensions. - * - * @param description the description of this file filter. - * @param acceptDir whether to accept directories - * @param extensions an array of extensions that match this filter. - */ - public SimpleFileFilter(String description, boolean acceptDir, String... extensions) { - this.description = description; - this.acceptDir = acceptDir; - this.extensions = new String[extensions.length]; - for (int i = 0; i < extensions.length; i++) { - String ext = extensions[i].toLowerCase(Locale.ENGLISH); - if (ext.charAt(0) == '.') { - this.extensions[i] = ext; - } else { - this.extensions[i] = '.' + ext; - } - } - } - - - @Override - public boolean accept(File file) { - if (file == null) - return false; - if (file.isDirectory()) - return acceptDir; - - String filename = file.getName(); - filename = filename.toLowerCase(Locale.ENGLISH); - for (String ext : extensions) { - if (filename.endsWith(ext)) - return true; - } - - return false; - } - - @Override - public String getDescription() { - return description; - } - -} diff --git a/core/src/net/sf/openrocket/gui/util/SwingPreferences.java b/core/src/net/sf/openrocket/gui/util/SwingPreferences.java deleted file mode 100644 index 61e6be85..00000000 --- a/core/src/net/sf/openrocket/gui/util/SwingPreferences.java +++ /dev/null @@ -1,584 +0,0 @@ -package net.sf.openrocket.gui.util; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Point; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.prefs.BackingStoreException; -import java.util.prefs.Preferences; - -import net.sf.openrocket.arch.SystemInfo; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.RK4SimulationStepper; -import net.sf.openrocket.simulation.SimulationOptions; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.BuildProperties; - - -public class SwingPreferences extends net.sf.openrocket.startup.Preferences { - private static final LogHelper log = Application.getLogger(); - - private static final String SPLIT_CHARACTER = "|"; - - - private static final List SUPPORTED_LOCALES; - static { - List list = new ArrayList(); - for (String lang : new String[] { "en", "de", "es", "fr", "it", "ru", "cs", "pl" }) { - list.add(new Locale(lang)); - } - SUPPORTED_LOCALES = Collections.unmodifiableList(list); - } - - - /** - * Whether to use the debug-node instead of the normal node. - */ - private static final boolean DEBUG; - static { - DEBUG = (System.getProperty("openrocket.debug.prefs") != null); - } - - /** - * Whether to clear all preferences at application startup. This has an effect only - * if DEBUG is true. - */ - private static final boolean CLEARPREFS = true; - - /** - * The node name to use in the Java preferences storage. - */ - private static final String NODENAME = (DEBUG ? "OpenRocket-debug" : "OpenRocket"); - - private final Preferences PREFNODE; - - - public SwingPreferences() { - Preferences root = Preferences.userRoot(); - if (DEBUG && CLEARPREFS) { - try { - if (root.nodeExists(NODENAME)) { - root.node(NODENAME).removeNode(); - } - } catch (BackingStoreException e) { - throw new BugException("Unable to clear preference node", e); - } - } - PREFNODE = root.node(NODENAME); - } - - - - - ////////////////////// - - - - /** - * Store the current OpenRocket version into the preferences to allow for preferences migration. - */ - private void storeVersion() { - PREFNODE.put("OpenRocketVersion", BuildProperties.getVersion()); - } - - /** - * Return a string preference. - * - * @param key the preference key. - * @param def the default if no preference is stored - * @return the preference value - */ - @Override - public String getString(String key, String def) { - return PREFNODE.get(key, def); - } - - @Override - public String getString(String directory, String key, String defaultValue) { - Preferences p = PREFNODE.node(directory); - return p.get(key, defaultValue); - } - - /** - * Set a string preference. - * - * @param key the preference key - * @param value the value to set, or null to remove the key - */ - @Override - public void putString(String key, String value) { - if (value == null) { - PREFNODE.remove(key); - } else { - PREFNODE.put(key, value); - } - storeVersion(); - } - - @Override - public void putString(String directory, String key, String value) { - Preferences p = PREFNODE.node(directory); - if (value == null) { - p.remove(key); - } else { - p.put(key, value); - } - storeVersion(); - } - - /** - * Return a boolean preference. - * - * @param key the preference key - * @param def the default if no preference is stored - * @return the preference value - */ - @Override - public boolean getBoolean(String key, boolean def) { - return PREFNODE.getBoolean(key, def); - } - - /** - * Set a boolean preference. - * - * @param key the preference key - * @param value the value to set - */ - @Override - public void putBoolean(String key, boolean value) { - PREFNODE.putBoolean(key, value); - storeVersion(); - } - - @Override - public int getInt(String key, int defaultValue) { - return PREFNODE.getInt(key, defaultValue); - } - - @Override - public void putInt(String key, int value) { - PREFNODE.putInt(key, value); - storeVersion(); - } - - @Override - public double getDouble(String key, double defaultValue) { - return PREFNODE.getDouble(key, defaultValue); - } - - @Override - public void putDouble(String key, double value) { - PREFNODE.putDouble(key, value); - storeVersion(); - } - - - - /** - * Return a preferences object for the specified node name. - * - * @param nodeName the node name - * @return the preferences object for that node - */ - public Preferences getNode(String nodeName) { - return PREFNODE.node(nodeName); - } - - - ////////////////// - - - public static List getSupportedLocales() { - return SUPPORTED_LOCALES; - } - - public File getDefaultDirectory() { - String file = getString("defaultDirectory", null); - if (file == null) - return null; - return new File(file); - } - - public void setDefaultDirectory(File dir) { - String d; - if (dir == null) { - d = null; - } else { - d = dir.getAbsolutePath(); - } - putString("defaultDirectory", d); - storeVersion(); - } - - - /** - * Return a list of files/directories to be loaded as custom thrust curves. - *

- * If this property has not been set, the directory "ThrustCurves" in the user - * application directory will be used. The directory will be created if it does not - * exist. - * - * @return a list of files to load as thrust curves. - */ - public List getUserThrustCurveFiles() { - List list = new ArrayList(); - - String files = getString(USER_THRUST_CURVES_KEY, null); - if (files == null) { - // Default to application directory - File tcdir = getDefaultUserThrustCurveFile(); - if (!tcdir.isDirectory()) { - tcdir.mkdirs(); - } - list.add(tcdir); - } else { - for (String file : files.split("\\" + SPLIT_CHARACTER)) { - file = file.trim(); - if (file.length() > 0) { - list.add(new File(file)); - } - } - } - - return list; - } - - public File getDefaultUserThrustCurveFile() { - File appdir = SystemInfo.getUserApplicationDirectory(); - File tcdir = new File(appdir, "ThrustCurves"); - return tcdir; - } - - - /** - * Set the list of files/directories to be loaded as custom thrust curves. - * - * @param files the files to load, or null to reset to default value. - */ - public void setUserThrustCurveFiles(List files) { - if (files == null) { - putString(USER_THRUST_CURVES_KEY, null); - return; - } - - String str = ""; - - for (File file : files) { - if (str.length() > 0) { - str += SPLIT_CHARACTER; - } - str += file.getAbsolutePath(); - } - putString(USER_THRUST_CURVES_KEY, str); - } - - public Color getMotorBorderColor() { - // TODO: MEDIUM: Motor color (settable?) - return new Color(0, 0, 0, 200); - } - - - public Color getMotorFillColor() { - // TODO: MEDIUM: Motor fill color (settable?) - return new Color(0, 0, 0, 100); - } - - - - public static int getMaxThreadCount() { - return Runtime.getRuntime().availableProcessors(); - } - - - - public Point getWindowPosition(Class c) { - int x, y; - String pref = PREFNODE.node("windows").get("position." + c.getCanonicalName(), null); - - if (pref == null) - return null; - - if (pref.indexOf(',') < 0) - return null; - - try { - x = Integer.parseInt(pref.substring(0, pref.indexOf(','))); - y = Integer.parseInt(pref.substring(pref.indexOf(',') + 1)); - } catch (NumberFormatException e) { - return null; - } - return new Point(x, y); - } - - public void setWindowPosition(Class c, Point p) { - PREFNODE.node("windows").put("position." + c.getCanonicalName(), "" + p.x + "," + p.y); - storeVersion(); - } - - - - - public Dimension getWindowSize(Class c) { - int x, y; - String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null); - - if (pref == null) - return null; - - if (pref.indexOf(',') < 0) - return null; - - try { - x = Integer.parseInt(pref.substring(0, pref.indexOf(','))); - y = Integer.parseInt(pref.substring(pref.indexOf(',') + 1)); - } catch (NumberFormatException e) { - return null; - } - return new Dimension(x, y); - } - - - public boolean isWindowMaximized(Class c) { - String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null); - return "max".equals(pref); - } - - public void setWindowSize(Class c, Dimension d) { - PREFNODE.node("windows").put("size." + c.getCanonicalName(), "" + d.width + "," + d.height); - storeVersion(); - } - - public void setWindowMaximized(Class c) { - PREFNODE.node("windows").put("size." + c.getCanonicalName(), "max"); - storeVersion(); - } - - /** - * this class returns a java.awt.Color object for the specified key. - * you can pass (java.awt.Color) null to the second argument to - * disambiguate - */ - public Color getColor(String key, Color defaultValue) { - net.sf.openrocket.util.Color c = super.getColor(key, (net.sf.openrocket.util.Color) null); - if (c == null) { - return defaultValue; - } - return ColorConversion.toAwtColor(c); - } - - /** - * - */ - public void putColor(String key, Color value) { - net.sf.openrocket.util.Color c = ColorConversion.fromAwtColor(value); - super.putColor(key, c); - } - - //// Printing - - - //// Background flight data computation - - public boolean computeFlightInBackground() { - return PREFNODE.getBoolean("backgroundFlight", true); - } - - public Simulation getBackgroundSimulation(Rocket rocket) { - Simulation s = new Simulation(rocket); - SimulationOptions cond = s.getOptions(); - - cond.setTimeStep(RK4SimulationStepper.RECOMMENDED_TIME_STEP * 2); - cond.setWindSpeedAverage(1.0); - cond.setWindSpeedDeviation(0.1); - cond.setLaunchRodLength(5); - return s; - } - - - - ///////// Export variables - - public boolean isExportSelected(FlightDataType type) { - Preferences prefs = PREFNODE.node("exports"); - return prefs.getBoolean(type.getName(), false); - } - - public void setExportSelected(FlightDataType type, boolean selected) { - Preferences prefs = PREFNODE.node("exports"); - prefs.putBoolean(type.getName(), selected); - } - - - - ///////// Default unit storage - - public void loadDefaultUnits() { - Preferences prefs = PREFNODE.node("units"); - try { - - for (String key : prefs.keys()) { - UnitGroup group = UnitGroup.UNITS.get(key); - if (group == null) - continue; - - try { - group.setDefaultUnit(prefs.get(key, null)); - } catch (IllegalArgumentException ignore) { - } - } - - } catch (BackingStoreException e) { - Application.getExceptionHandler().handleErrorCondition(e); - } - } - - public void storeDefaultUnits() { - Preferences prefs = PREFNODE.node("units"); - - for (String key : UnitGroup.UNITS.keySet()) { - UnitGroup group = UnitGroup.UNITS.get(key); - if (group == null || group.getUnitCount() < 2) - continue; - - prefs.put(key, group.getDefaultUnit().getUnit()); - } - } - - - - //// Material storage - - - /** - * Add a user-defined material to the preferences. The preferences are - * first checked for an existing material matching the provided one using - * {@link Material#equals(Object)}. - * - * @param m the material to add. - */ - @Override - public void addUserMaterial(Material m) { - Preferences prefs = PREFNODE.node("userMaterials"); - - - // Check whether material already exists - if (getUserMaterials().contains(m)) { - return; - } - - // Add material using next free key (key is not used when loading) - String mat = m.toStorableString(); - for (int i = 0;; i++) { - String key = "material" + i; - if (prefs.get(key, null) == null) { - prefs.put(key, mat); - return; - } - } - } - - - /** - * Remove a user-defined material from the preferences. The matching is performed - * using {@link Material#equals(Object)}. - * - * @param m the material to remove. - */ - @Override - public void removeUserMaterial(Material m) { - Preferences prefs = PREFNODE.node("userMaterials"); - - try { - - // Iterate through materials and remove all keys with a matching material - for (String key : prefs.keys()) { - String value = prefs.get(key, null); - try { - - Material existing = Material.fromStorableString(value, true); - if (existing.equals(m)) { - prefs.remove(key); - } - - } catch (IllegalArgumentException ignore) { - } - - } - - } catch (BackingStoreException e) { - throw new IllegalStateException("Cannot read preferences!", e); - } - } - - - /** - * Return a set of all user-defined materials in the preferences. The materials - * are created marked as user-defined. - * - * @return a set of all user-defined materials. - */ - @Override - public Set getUserMaterials() { - Preferences prefs = PREFNODE.node("userMaterials"); - - HashSet materials = new HashSet(); - try { - - for (String key : prefs.keys()) { - String value = prefs.get(key, null); - try { - - Material m = Material.fromStorableString(value, true); - materials.add(m); - - } catch (IllegalArgumentException e) { - log.warn("Illegal material string " + value); - } - - } - - } catch (BackingStoreException e) { - throw new IllegalStateException("Cannot read preferences!", e); - } - - return materials; - } - - @Override - public void setComponentFavorite(ComponentPreset preset, ComponentPreset.Type type, boolean favorite) { - Preferences prefs = PREFNODE.node("favoritePresets").node(type.name()); - if (favorite) { - prefs.putBoolean(preset.preferenceKey(), true); - } else { - prefs.remove(preset.preferenceKey()); - } - } - - @Override - public Set getComponentFavorites(ComponentPreset.Type type) { - Preferences prefs = PREFNODE.node("favoritePresets").node(type.name()); - Set collection = new HashSet(); - try { - collection.addAll(Arrays.asList(prefs.keys())); - } catch (BackingStoreException bex) { - - } - return collection; - } - //// Helper methods - -} diff --git a/core/src/net/sf/openrocket/l10n/ClassBasedTranslator.java b/core/src/net/sf/openrocket/l10n/ClassBasedTranslator.java deleted file mode 100644 index 6281b6e8..00000000 --- a/core/src/net/sf/openrocket/l10n/ClassBasedTranslator.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.sf.openrocket.l10n; - -import java.util.MissingResourceException; - -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.util.BugException; - -/** - * A translator that prepends a pre-defined class name in front of a translation key - * and retrieves the translator for that key, and only if that is missing reverts to - * the base key name. The base class name can either be provided to the constructor - * or retrieved from the stack. - * - * @author Sampo Niskanen - */ -public class ClassBasedTranslator implements Translator { - - - private final Translator translator; - private final String className; - - /** - * Construct a translator using a specified class name. - * - * @param translator the translator from which to obtain the translations. - * @param className the base class name to prepend. - */ - public ClassBasedTranslator(Translator translator, String className) { - this.translator = translator; - this.className = className; - } - - /** - * Construct a translator by obtaining the base class name from the stack. - * - * @param translator the translator from which to obtain the translations. - * @param levels the number of levels to move upwards in the stack from the point where this method is called. - */ - public ClassBasedTranslator(Translator translator, int levels) { - this(translator, getStackClass(levels)); - } - - - - @Override - public String get(String key) { - String classKey = className + "." + key; - - try { - return translator.get(classKey); - } catch (MissingResourceException e) { - // Ignore - } - - try { - return translator.get(key); - } catch (MissingResourceException e) { - MissingResourceException mre = new MissingResourceException( - "Neither key '" + classKey + "' nor '" + key + "' could be found", e.getClassName(), key); - mre.initCause(e); - throw mre; - } - } - - - - @Override - public String get(String base, String text) { - return translator.get(base, text); - } - - @Override - public String getBaseText(String base, String translation) { - return translator.getBaseText(base, translation); - } - - - - - private static String getStackClass(int levels) { - TraceException trace = new TraceException(); - StackTraceElement stack[] = trace.getStackTrace(); - final int index = levels + 2; - if (stack.length <= index) { - throw new BugException("Stack trace is too short, length=" + stack.length + ", expected=" + index, trace); - } - - StackTraceElement element = stack[index]; - String cn = element.getClassName(); - int pos = cn.lastIndexOf('.'); - if (pos >= 0) { - cn = cn.substring(pos + 1); - } - return cn; - } - - - - - // For unit testing purposes - String getClassName() { - return className; - } -} diff --git a/core/src/net/sf/openrocket/l10n/DebugTranslator.java b/core/src/net/sf/openrocket/l10n/DebugTranslator.java deleted file mode 100644 index ccf72e58..00000000 --- a/core/src/net/sf/openrocket/l10n/DebugTranslator.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.sf.openrocket.l10n; - -/** - * A translator implementation that returns the logical key in brackets instead - * of an actual translation. The class optionally verifies that the translation - * is actually obtainable from some other translator. - * - * @author Sampo Niskanen - */ -public class DebugTranslator implements Translator { - - private final Translator translator; - - - /** - * Sole constructor. - * - * @param translator the translator to verify the translation exists, or null not to verify. - */ - public DebugTranslator(Translator translator) { - this.translator = translator; - } - - - - @Override - public String get(String key) { - if (translator != null) { - translator.get(key); - } - return "[" + key + "]"; - } - - - - @Override - public String get(String base, String text) { - return "[" + base + ":" + text + "]"; - } - - - - @Override - public String getBaseText(String base, String translation) { - if (translation.startsWith("[" + base + ":") && translation.endsWith("]")) { - return translation.substring(base.length() + 2, translation.length() - 1); - } - return translation; - } - - -} diff --git a/core/src/net/sf/openrocket/l10n/ExceptionSuppressingTranslator.java b/core/src/net/sf/openrocket/l10n/ExceptionSuppressingTranslator.java deleted file mode 100644 index 1287822c..00000000 --- a/core/src/net/sf/openrocket/l10n/ExceptionSuppressingTranslator.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.sf.openrocket.l10n; - -import java.util.Locale; -import java.util.MissingResourceException; - -import net.sf.openrocket.startup.Application; - -/** - * A translator that suppresses MissingResourceExceptions and handles them gracefully. - * For the first missing key this class calls the exception handler, and afterwards - * always returns the key for missing translations. - * - * @author Sampo Niskanen - */ -public class ExceptionSuppressingTranslator implements Translator { - - static boolean errorReported = false; - - private final Translator translator; - - - /** - * Sole constructor. - * - * @param translator the translator to use - */ - public ExceptionSuppressingTranslator(Translator translator) { - this.translator = translator; - } - - - - @Override - public String get(String key) { - try { - return translator.get(key); - } catch (MissingResourceException e) { - handleError(key, e); - } - - return key; - } - - - @Override - public String get(String base, String text) { - return translator.get(base, text); - } - - - @Override - public String getBaseText(String base, String translation) { - return translator.getBaseText(base, translation); - } - - - private static synchronized void handleError(String key, MissingResourceException e) { - if (!errorReported) { - errorReported = true; - Application.getExceptionHandler().handleErrorCondition("Can not find translation for '" + key + "' locale=" + Locale.getDefault(), e); - } - } - - - -} diff --git a/core/src/net/sf/openrocket/l10n/L10N.java b/core/src/net/sf/openrocket/l10n/L10N.java deleted file mode 100644 index 3303292d..00000000 --- a/core/src/net/sf/openrocket/l10n/L10N.java +++ /dev/null @@ -1,403 +0,0 @@ -package net.sf.openrocket.l10n; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Pattern; - -import net.sf.openrocket.util.Chars; - -/** - * Helper methods for localization needs. - * - * @author Sampo Niskanen - */ -public final class L10N { - - /** - * Unicode character normalization map. This is used because Android does - * not support the java.text.Normalize class. - */ - private static final Map NORMALIZATION_MAP; - - private L10N() { - // Prevent instantiation - } - - - /** - * Replace a text token by a replacement value. - *

- * A text token is a string portion that should be surrounded by - * braces, "{text}". - * - * @param original the original string. - * @param token the text token to replace. - * @param replacement the replacement text. - * @return the modified string. - */ - public static String replace(String original, String token, String replacement) { - return Pattern.compile(token, Pattern.LITERAL).matcher(original).replaceAll(replacement); - } - - - /** - * Convert a language code into a Locale. - * - * @param langcode the language code (null ok). - * @return the corresponding locale (or null if the input was null) - */ - public static Locale toLocale(String langcode) { - if (langcode == null) { - return null; - } - - Locale l; - String[] split = langcode.split("[_-]", 3); - if (split.length == 1) { - l = new Locale(split[0]); - } else if (split.length == 2) { - l = new Locale(split[0], split[1]); - } else { - l = new Locale(split[0], split[1], split[2]); - } - return l; - } - - - public static String normalize(String text) { - text = unicodeNormalize(text); - text = text.toLowerCase(); - text = text.replaceAll("\\s+", " "); - text = text.trim(); - - StringBuilder sb = new StringBuilder(text.length()); - for (char c : text.toCharArray()) { - if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { - sb.append(c); - } else if (c == ' ' || c == '/' || c == Chars.FRACTION) { - sb.append('_'); - } - } - text = sb.toString(); - - text = text.replaceAll("^_+", ""); - text = text.replaceAll("_+$", ""); - - return text; - } - - private static String unicodeNormalize(String text) { - StringBuilder sb = new StringBuilder(text.length()); - for (char c : text.toCharArray()) { - String s = NORMALIZATION_MAP.get(c); - if (s != null) { - sb.append(s); - } else { - sb.append(c); - } - } - return sb.toString(); - } - - - static { - /* - * This list is generated using the L10NGenerator utility. - */ - Map m = new HashMap(); - m.put('\u00aa', "a"); - m.put('\u00b2', "2"); - m.put('\u00b3', "3"); - m.put('\u00b9', "1"); - m.put('\u00ba', "o"); - m.put('\u00bc', "1/4"); - m.put('\u00bd', "1/2"); - m.put('\u00be', "3/4"); - m.put('\u00c0', "A"); - m.put('\u00c1', "A"); - m.put('\u00c2', "A"); - m.put('\u00c3', "A"); - m.put('\u00c4', "A"); - m.put('\u00c5', "A"); - m.put('\u00c7', "C"); - m.put('\u00c8', "E"); - m.put('\u00c9', "E"); - m.put('\u00ca', "E"); - m.put('\u00cb', "E"); - m.put('\u00cc', "I"); - m.put('\u00cd', "I"); - m.put('\u00ce', "I"); - m.put('\u00cf', "I"); - m.put('\u00d1', "N"); - m.put('\u00d2', "O"); - m.put('\u00d3', "O"); - m.put('\u00d4', "O"); - m.put('\u00d5', "O"); - m.put('\u00d6', "O"); - m.put('\u00d9', "U"); - m.put('\u00da', "U"); - m.put('\u00db', "U"); - m.put('\u00dc', "U"); - m.put('\u00dd', "Y"); - m.put('\u00e0', "a"); - m.put('\u00e1', "a"); - m.put('\u00e2', "a"); - m.put('\u00e3', "a"); - m.put('\u00e4', "a"); - m.put('\u00e5', "a"); - m.put('\u00e7', "c"); - m.put('\u00e8', "e"); - m.put('\u00e9', "e"); - m.put('\u00ea', "e"); - m.put('\u00eb', "e"); - m.put('\u00ec', "i"); - m.put('\u00ed', "i"); - m.put('\u00ee', "i"); - m.put('\u00ef', "i"); - m.put('\u00f1', "n"); - m.put('\u00f2', "o"); - m.put('\u00f3', "o"); - m.put('\u00f4', "o"); - m.put('\u00f5', "o"); - m.put('\u00f6', "o"); - m.put('\u00f9', "u"); - m.put('\u00fa', "u"); - m.put('\u00fb', "u"); - m.put('\u00fc', "u"); - m.put('\u00fd', "y"); - m.put('\u00ff', "y"); - m.put('\u0100', "A"); - m.put('\u0101', "a"); - m.put('\u0102', "A"); - m.put('\u0103', "a"); - m.put('\u0104', "A"); - m.put('\u0105', "a"); - m.put('\u0106', "C"); - m.put('\u0107', "c"); - m.put('\u0108', "C"); - m.put('\u0109', "c"); - m.put('\u010a', "C"); - m.put('\u010b', "c"); - m.put('\u010c', "C"); - m.put('\u010d', "c"); - m.put('\u010e', "D"); - m.put('\u010f', "d"); - m.put('\u0112', "E"); - m.put('\u0113', "e"); - m.put('\u0114', "E"); - m.put('\u0115', "e"); - m.put('\u0116', "E"); - m.put('\u0117', "e"); - m.put('\u0118', "E"); - m.put('\u0119', "e"); - m.put('\u011a', "E"); - m.put('\u011b', "e"); - m.put('\u011c', "G"); - m.put('\u011d', "g"); - m.put('\u011e', "G"); - m.put('\u011f', "g"); - m.put('\u0120', "G"); - m.put('\u0121', "g"); - m.put('\u0122', "G"); - m.put('\u0123', "g"); - m.put('\u0124', "H"); - m.put('\u0125', "h"); - m.put('\u0128', "I"); - m.put('\u0129', "i"); - m.put('\u012a', "I"); - m.put('\u012b', "i"); - m.put('\u012c', "I"); - m.put('\u012d', "i"); - m.put('\u012e', "I"); - m.put('\u012f', "i"); - m.put('\u0130', "I"); - m.put('\u0132', "IJ"); - m.put('\u0133', "ij"); - m.put('\u0134', "J"); - m.put('\u0135', "j"); - m.put('\u0136', "K"); - m.put('\u0137', "k"); - m.put('\u0139', "L"); - m.put('\u013a', "l"); - m.put('\u013b', "L"); - m.put('\u013c', "l"); - m.put('\u013d', "L"); - m.put('\u013e', "l"); - m.put('\u013f', "L"); - m.put('\u0140', "l"); - m.put('\u0143', "N"); - m.put('\u0144', "n"); - m.put('\u0145', "N"); - m.put('\u0146', "n"); - m.put('\u0147', "N"); - m.put('\u0148', "n"); - m.put('\u0149', "n"); - m.put('\u014c', "O"); - m.put('\u014d', "o"); - m.put('\u014e', "O"); - m.put('\u014f', "o"); - m.put('\u0150', "O"); - m.put('\u0151', "o"); - m.put('\u0154', "R"); - m.put('\u0155', "r"); - m.put('\u0156', "R"); - m.put('\u0157', "r"); - m.put('\u0158', "R"); - m.put('\u0159', "r"); - m.put('\u015a', "S"); - m.put('\u015b', "s"); - m.put('\u015c', "S"); - m.put('\u015d', "s"); - m.put('\u015e', "S"); - m.put('\u015f', "s"); - m.put('\u0160', "S"); - m.put('\u0161', "s"); - m.put('\u0162', "T"); - m.put('\u0163', "t"); - m.put('\u0164', "T"); - m.put('\u0165', "t"); - m.put('\u0168', "U"); - m.put('\u0169', "u"); - m.put('\u016a', "U"); - m.put('\u016b', "u"); - m.put('\u016c', "U"); - m.put('\u016d', "u"); - m.put('\u016e', "U"); - m.put('\u016f', "u"); - m.put('\u0170', "U"); - m.put('\u0171', "u"); - m.put('\u0172', "U"); - m.put('\u0173', "u"); - m.put('\u0174', "W"); - m.put('\u0175', "w"); - m.put('\u0176', "Y"); - m.put('\u0177', "y"); - m.put('\u0178', "Y"); - m.put('\u0179', "Z"); - m.put('\u017a', "z"); - m.put('\u017b', "Z"); - m.put('\u017c', "z"); - m.put('\u017d', "Z"); - m.put('\u017e', "z"); - m.put('\u017f', "s"); - m.put('\u01a0', "O"); - m.put('\u01a1', "o"); - m.put('\u01af', "U"); - m.put('\u01b0', "u"); - m.put('\u01c4', "DZ"); - m.put('\u01c5', "Dz"); - m.put('\u01c6', "dz"); - m.put('\u01c7', "LJ"); - m.put('\u01c8', "Lj"); - m.put('\u01c9', "lj"); - m.put('\u01ca', "NJ"); - m.put('\u01cb', "Nj"); - m.put('\u01cc', "nj"); - m.put('\u01cd', "A"); - m.put('\u01ce', "a"); - m.put('\u01cf', "I"); - m.put('\u01d0', "i"); - m.put('\u01d1', "O"); - m.put('\u01d2', "o"); - m.put('\u01d3', "U"); - m.put('\u01d4', "u"); - m.put('\u01d5', "U"); - m.put('\u01d6', "u"); - m.put('\u01d7', "U"); - m.put('\u01d8', "u"); - m.put('\u01d9', "U"); - m.put('\u01da', "u"); - m.put('\u01db', "U"); - m.put('\u01dc', "u"); - m.put('\u01de', "A"); - m.put('\u01df', "a"); - m.put('\u01e0', "A"); - m.put('\u01e1', "a"); - m.put('\u01e6', "G"); - m.put('\u01e7', "g"); - m.put('\u01e8', "K"); - m.put('\u01e9', "k"); - m.put('\u01ea', "O"); - m.put('\u01eb', "o"); - m.put('\u01ec', "O"); - m.put('\u01ed', "o"); - m.put('\u01f0', "j"); - m.put('\u01f1', "DZ"); - m.put('\u01f2', "Dz"); - m.put('\u01f3', "dz"); - m.put('\u01f4', "G"); - m.put('\u01f5', "g"); - m.put('\u01f8', "N"); - m.put('\u01f9', "n"); - m.put('\u01fa', "A"); - m.put('\u01fb', "a"); - m.put('\u0200', "A"); - m.put('\u0201', "a"); - m.put('\u0202', "A"); - m.put('\u0203', "a"); - m.put('\u0204', "E"); - m.put('\u0205', "e"); - m.put('\u0206', "E"); - m.put('\u0207', "e"); - m.put('\u0208', "I"); - m.put('\u0209', "i"); - m.put('\u020a', "I"); - m.put('\u020b', "i"); - m.put('\u020c', "O"); - m.put('\u020d', "o"); - m.put('\u020e', "O"); - m.put('\u020f', "o"); - m.put('\u0210', "R"); - m.put('\u0211', "r"); - m.put('\u0212', "R"); - m.put('\u0213', "r"); - m.put('\u0214', "U"); - m.put('\u0215', "u"); - m.put('\u0216', "U"); - m.put('\u0217', "u"); - m.put('\u0218', "S"); - m.put('\u0219', "s"); - m.put('\u021a', "T"); - m.put('\u021b', "t"); - m.put('\u021e', "H"); - m.put('\u021f', "h"); - m.put('\u0226', "A"); - m.put('\u0227', "a"); - m.put('\u0228', "E"); - m.put('\u0229', "e"); - m.put('\u022a', "O"); - m.put('\u022b', "o"); - m.put('\u022c', "O"); - m.put('\u022d', "o"); - m.put('\u022e', "O"); - m.put('\u022f', "o"); - m.put('\u0230', "O"); - m.put('\u0231', "o"); - m.put('\u0232', "Y"); - m.put('\u0233', "y"); - m.put('\u2070', "0"); - m.put('\u2071', "i"); - m.put('\u2074', "4"); - m.put('\u2075', "5"); - m.put('\u2076', "6"); - m.put('\u2077', "7"); - m.put('\u2078', "8"); - m.put('\u2079', "9"); - m.put('\u2080', "0"); - m.put('\u2081', "1"); - m.put('\u2082', "2"); - m.put('\u2083', "3"); - m.put('\u2084', "4"); - m.put('\u2085', "5"); - m.put('\u2086', "6"); - m.put('\u2087', "7"); - m.put('\u2088', "8"); - m.put('\u2089', "9"); - m.put('\u2044', "/"); - m.put('\u200b', " "); - m.put('\u00a0', " "); - NORMALIZATION_MAP = Collections.unmodifiableMap(m); - } -} diff --git a/core/src/net/sf/openrocket/l10n/LocalizedIOException.java b/core/src/net/sf/openrocket/l10n/LocalizedIOException.java deleted file mode 100644 index be99bdfb..00000000 --- a/core/src/net/sf/openrocket/l10n/LocalizedIOException.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.l10n; - -import java.io.IOException; - -import net.sf.openrocket.startup.Application; - -public class LocalizedIOException extends IOException { - - private static final Translator trans = Application.getTranslator(); - - private final String key; - - - public LocalizedIOException(String key) { - super(key); - this.key = key; - } - - public LocalizedIOException(String key, Throwable cause) { - super(key, cause); - this.key = key; - } - - @Override - public String getLocalizedMessage() { - return trans.get(key); - } -} diff --git a/core/src/net/sf/openrocket/l10n/ResourceBundleTranslator.java b/core/src/net/sf/openrocket/l10n/ResourceBundleTranslator.java deleted file mode 100644 index d210e01e..00000000 --- a/core/src/net/sf/openrocket/l10n/ResourceBundleTranslator.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.sf.openrocket.l10n; - -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * A translator that obtains translated strings from a resource bundle. - * - * @author Sampo Niskanen - */ -public class ResourceBundleTranslator implements Translator { - - private final ResourceBundle bundle; - private final ResourceBundle english; - - /** - * Create a ResourceBundleTranslator using the default Locale. - * - * @param baseName the base name of the resource bundle - */ - public ResourceBundleTranslator(String baseName) { - this(baseName, Locale.getDefault()); - } - - /** - * Create a ResourceBundleTranslator using the specified Locale. - * - * @param baseName the base name of the resource bundle - * @param locale the locale to use - */ - public ResourceBundleTranslator(String baseName, Locale locale) { - this.bundle = ResourceBundle.getBundle(baseName, locale); - this.english = ResourceBundle.getBundle(baseName, Locale.ROOT); - } - - - /* - * NOTE: This method must be thread-safe! - */ - @Override - public synchronized String get(String key) { - return bundle.getString(key); - } - - @Override - public synchronized String get(String base, String text) { - String key = base + "." + L10N.normalize(text); - try { - return bundle.getString(key); - } catch (MissingResourceException e) { - return text; - } - } - - @Override - public synchronized String getBaseText(String base, String translation) { - String prefix = base + "."; - for (String key : bundle.keySet()) { - if (key.startsWith(prefix)) { - String value = bundle.getString(key); - if (value.equals(translation)) { - return english.getString(key); - } - } - } - return translation; - } -} diff --git a/core/src/net/sf/openrocket/l10n/Translator.java b/core/src/net/sf/openrocket/l10n/Translator.java deleted file mode 100644 index 5211ed73..00000000 --- a/core/src/net/sf/openrocket/l10n/Translator.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.sf.openrocket.l10n; - -import java.util.MissingResourceException; - -/** - * An interface for obtaining translations from logical keys. - *

- * Translator implementations must be thread-safe. - * - * @author Sampo Niskanen - */ -public interface Translator { - - /** - * Retrieve a translated string based on a logical key. This always returns - * some string, potentially falling back to the key itself. - * - * @param key the logical string key. - * @return the translated string. - * @throws MissingResourceException if the translation corresponding to the key is not found. - * @throws NullPointerException if key is null. - */ - public String get(String key); - - - /** - * Retrieve a translated string based on a base key and base (English) version of the text. - * The base text is normalized before using as a key. - *

- * This is meant to be used in very specific cases where the English name is - * used as a key for translation and storage. If a translation is not found, - * the base text is used instead. - * - * @param base the base for the logical key - * @param text the base (English) text to translate - * @return the translated string, or "text" if not found - */ - public String get(String base, String text); - - - /** - * Find the base (English) version of a translated text. - *

- * This is the opposite operation of {@link #get(String, String)}, and - * meant for use in very specific cases when storing the values of - * translated texts. - * - * @param base the base for the logical key - * @param translation the translated string - * @return the base text, or the translation if not found. - */ - public String getBaseText(String base, String translation); - -} diff --git a/core/src/net/sf/openrocket/logging/BufferLogger.java b/core/src/net/sf/openrocket/logging/BufferLogger.java deleted file mode 100644 index eab392b6..00000000 --- a/core/src/net/sf/openrocket/logging/BufferLogger.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.sf.openrocket.logging; - -import java.util.EnumMap; -import java.util.List; - -/** - * A logger implementation that buffers specific levels of log lines. - * The levels that are logged are set using the method - * {@link #setStoreLevel(LogLevel, boolean)}. The stored LogLines can - * be obtained using {@link #getLogs()}. - * - * @author Sampo Niskanen - */ -public class BufferLogger extends LogHelper { - - private final CyclicBuffer buffer; - private final EnumMap storeLevels = - new EnumMap(LogLevel.class); - - - /** - * Create a buffered logger with that logs the specified number of log - * lines. By default all log levels are buffered. - * - * @param length the length of the buffer. - */ - public BufferLogger(int length) { - for (LogLevel l: LogLevel.values()) { - storeLevels.put(l, true); - } - buffer = new CyclicBuffer(length); - } - - - @Override - public void log(LogLine line) { - if (storeLevels.get(line.getLevel())) { - buffer.add(line); - } - } - - /** - * Set whether the specified log level is buffered. - * - * @param level the log level. - * @param store whether to store the level. - */ - public void setStoreLevel(LogLevel level, boolean store) { - storeLevels.put(level, store); - } - - /** - * Get whether the specified log level is buffered. - * - * @param level the log level. - * @return whether the log level is stored. - */ - public boolean getStoreLevel(LogLevel level) { - return storeLevels.get(level); - } - - - /** - * Return all the buffered log lines. - * - * @return a list of all buffered log lines. - */ - public List getLogs() { - return buffer.asList(); - } - - /** - * Return the number of log lines that has been overwritten. - * - * @return the number of log lines missed. - */ - public int getOverwriteCount() { - return buffer.getOverwriteCount(); - } -} diff --git a/core/src/net/sf/openrocket/logging/CyclicBuffer.java b/core/src/net/sf/openrocket/logging/CyclicBuffer.java deleted file mode 100644 index 31328ba2..00000000 --- a/core/src/net/sf/openrocket/logging/CyclicBuffer.java +++ /dev/null @@ -1,176 +0,0 @@ -package net.sf.openrocket.logging; - -import java.util.AbstractQueue; -import java.util.ArrayList; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * A cyclic buffer with a fixed size. When more data is inserted, the newest - * data will overwrite the oldest data. - *

- * Though this class implements the Queue interface, it specifically breaks the - * contract by overwriting (removing) data without specific removal. It also - * currently does not support removing arbitrary elements from the set. - *

- * The methods in this class are synchronized for concurrent modification. - * However, iterating over the set is not thread-safe. To obtain a snapshot - * of the state of the buffer, use {@link #asList()}. - * - * @param the object type that is stored. - * @author Sampo Niskanen - */ -public class CyclicBuffer extends AbstractQueue { - - private final ArrayList buffer; - private final int maxSize; - - private int startPosition = 0; - private int size = 0; - private int overwriteCount = 0; - - private int modCount = 0; - - - /** - * Create a cyclic buffer of the specified size. - * - * @param size the size of the cyclic buffer. - */ - public CyclicBuffer(int size) { - this.buffer = new ArrayList(size); - for (int i=0; i iterator() { - return new CyclicBufferIterator(); - } - - - /** - * Return a snapshot of the current buffered objects in the order they - * were placed in the buffer. The list is independent of the buffer. - * - * @return a list of the buffered objects. - */ - public synchronized List asList() { - ArrayList list = new ArrayList(size); - if (startPosition + size > maxSize) { - list.addAll(buffer.subList(startPosition, maxSize)); - list.addAll(buffer.subList(0, startPosition + size - maxSize)); - } else { - list.addAll(buffer.subList(startPosition, startPosition+size)); - } - return list; - } - - - /** - * Return the number of elements that have been overwritten in the buffer. - * The overwritten elements are the elements that have been added to the - * buffer, have not been explicitly removed but are not present in the list. - * - * @return the number of overwritten elements this far. - */ - public synchronized int getOverwriteCount() { - return overwriteCount; - } - - - private int next(int n) { - return (n+1) % maxSize; - } - - - private class CyclicBufferIterator implements Iterator { - - private int expectedModCount; - private int n = 0; - - public CyclicBufferIterator() { - this.expectedModCount = modCount; - } - - @Override - public boolean hasNext() { - synchronized (CyclicBuffer.this) { - if (expectedModCount != modCount) { - throw new ConcurrentModificationException("expectedModCount="+ - expectedModCount+" modCount=" + modCount); - } - return (n < size); - } - } - - @Override - public E next() { - synchronized (CyclicBuffer.this) { - if (expectedModCount != modCount) { - throw new ConcurrentModificationException("expectedModCount="+ - expectedModCount+" modCount=" + modCount); - } - if (n >= size) { - throw new NoSuchElementException("n="+n+" size="+size); - } - n++; - return buffer.get((startPosition + n-1) % maxSize); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("random remove not supported"); - } - } -} diff --git a/core/src/net/sf/openrocket/logging/DelegatorLogger.java b/core/src/net/sf/openrocket/logging/DelegatorLogger.java deleted file mode 100644 index 8c3a22df..00000000 --- a/core/src/net/sf/openrocket/logging/DelegatorLogger.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.sf.openrocket.logging; - -import java.util.List; - -import net.sf.openrocket.util.ArrayList; - -/** - * A logger implementation that delegates logging to other logger implementations. - * Multiple loggers can be added to the delegator, all of which will receive - * all of the log lines. - * - * @author Sampo Niskanen - */ -public class DelegatorLogger extends LogHelper { - - /** - * List of loggers. This list must not be modified, instead it should be - * replaced every time the list is changed. - */ - private volatile ArrayList loggers = new ArrayList(); - - @Override - public void log(LogLine line) { - // Must create local reference for thread safety - List list = loggers; - for (LogHelper l : list) { - l.log(line); - } - } - - - /** - * Add a logger from the delegation list. - * @param logger the logger to add. - */ - public synchronized void addLogger(LogHelper logger) { - ArrayList newList = loggers.clone(); - newList.add(logger); - this.loggers = newList; - } - - /** - * Remove a logger from the delegation list. - * @param logger the logger to be removed. - */ - public synchronized void removeLogger(LogHelper logger) { - ArrayList newList = loggers.clone(); - newList.remove(logger); - this.loggers = newList; - } - -} diff --git a/core/src/net/sf/openrocket/logging/LogHelper.java b/core/src/net/sf/openrocket/logging/LogHelper.java deleted file mode 100644 index d6b52104..00000000 --- a/core/src/net/sf/openrocket/logging/LogHelper.java +++ /dev/null @@ -1,517 +0,0 @@ -package net.sf.openrocket.logging; - -import net.sf.openrocket.util.BugException; - - -/** - * Base class for all loggers used in OpenRocket. - *

- * This class contains methods for logging at various log levels, and methods - * which take the logging level as a parameter. All methods may take three types - * of parameters: - *

    - *
  • levels number of additional levels of the stack trace to print - * on the log line. This is useful to determine from where - * the current method has been called. Zero if not provided. - *
  • message the String message (may be null). - *
  • cause the exception that caused this log (may be null). - *
- *

- * The logging methods are guaranteed never to throw an exception, and can thus be safely - * used in finally blocks. - * - * @author Sampo Niskanen - */ -public abstract class LogHelper { - /** - * Level from which upward a TraceException is added to the log lines. - */ - private static final LogLevel TRACING_LOG_LEVEL = - LogLevel.fromString(System.getProperty("openrocket.log.tracelevel"), LogLevel.INFO); - - private static final DelegatorLogger delegator = new DelegatorLogger(); - - - - /** - * Get the logger to be used in logging. - * - * @return the logger to be used in all logging. - */ - public static LogHelper getInstance() { - return delegator; - } - - - - /** - * Log a LogLine object. This method needs to be able to cope with multiple threads - * accessing it concurrently (for example by being synchronized). - * - * @param line the LogLine to log. - */ - public abstract void log(LogLine line); - - - /** - * Log using VBOSE level. - * - * @param message the logged message (may be null). - */ - public void verbose(String message) { - try { - log(createLogLine(0, LogLevel.VBOSE, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using VBOSE level. - * - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void verbose(String message, Throwable cause) { - try { - log(createLogLine(0, LogLevel.VBOSE, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using VBOSE level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - */ - public void verbose(int levels, String message) { - try { - log(createLogLine(levels, LogLevel.VBOSE, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using VBOSE level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void verbose(int levels, String message, Throwable cause) { - try { - log(createLogLine(levels, LogLevel.VBOSE, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * Log using DEBUG level. - * - * @param message the logged message (may be null). - */ - public void debug(String message) { - try { - log(createLogLine(0, LogLevel.DEBUG, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using DEBUG level. - * - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void debug(String message, Throwable cause) { - try { - log(createLogLine(0, LogLevel.DEBUG, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using DEBUG level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - */ - public void debug(int levels, String message) { - try { - log(createLogLine(levels, LogLevel.DEBUG, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using DEBUG level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void debug(int levels, String message, Throwable cause) { - try { - log(createLogLine(levels, LogLevel.DEBUG, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * Log using INFO level. - * - * @param message the logged message (may be null). - */ - public void info(String message) { - try { - log(createLogLine(0, LogLevel.INFO, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using INFO level. - * - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void info(String message, Throwable cause) { - try { - log(createLogLine(0, LogLevel.INFO, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using INFO level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - */ - public void info(int levels, String message) { - try { - log(createLogLine(levels, LogLevel.INFO, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using INFO level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void info(int levels, String message, Throwable cause) { - try { - log(createLogLine(levels, LogLevel.INFO, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * Log using USER level. - * - * @param message the logged message (may be null). - */ - public void user(String message) { - try { - log(createLogLine(0, LogLevel.USER, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using USER level. - * - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void user(String message, Throwable cause) { - try { - log(createLogLine(0, LogLevel.USER, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using USER level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - */ - public void user(int levels, String message) { - try { - log(createLogLine(levels, LogLevel.USER, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using USER level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void user(int levels, String message, Throwable cause) { - try { - log(createLogLine(levels, LogLevel.USER, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * Log using WARN level. - * - * @param message the logged message (may be null). - */ - public void warn(String message) { - try { - log(createLogLine(0, LogLevel.WARN, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using WARN level. - * - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void warn(String message, Throwable cause) { - try { - log(createLogLine(0, LogLevel.WARN, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using WARN level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - */ - public void warn(int levels, String message) { - try { - log(createLogLine(levels, LogLevel.WARN, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using WARN level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void warn(int levels, String message, Throwable cause) { - try { - log(createLogLine(levels, LogLevel.WARN, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * Log using ERROR level. - * - * @param message the logged message (may be null). - */ - public void error(String message) { - try { - log(createLogLine(0, LogLevel.ERROR, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using ERROR level. - * - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void error(String message, Throwable cause) { - try { - log(createLogLine(0, LogLevel.ERROR, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using ERROR level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - */ - public void error(int levels, String message) { - try { - log(createLogLine(levels, LogLevel.ERROR, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using ERROR level. - * - * @param levels number of additional levels of stack trace to include. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void error(int levels, String message, Throwable cause) { - try { - log(createLogLine(levels, LogLevel.ERROR, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - /** - * Log using the provided log level. - * - * @param level the logging level. - * @param message the logged message (may be null). - */ - public void log(LogLevel level, String message) { - try { - log(createLogLine(0, level, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using the provided log level. - * - * @param level the logging level. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void log(LogLevel level, String message, Throwable cause) { - try { - log(createLogLine(0, level, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using the provided log level. - * - * @param levels number of additional levels of stack trace to include. - * @param level the logging level. - * @param message the logged message (may be null). - */ - public void log(int levels, LogLevel level, String message) { - try { - log(createLogLine(levels, level, message, null)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Log using the provided log level. - * - * @param levels number of additional levels of stack trace to include. - * @param level the logging level. - * @param message the logged message (may be null). - * @param cause the causing exception (may be null). - */ - public void log(int levels, LogLevel level, String message, Throwable cause) { - try { - log(createLogLine(levels, level, message, cause)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - - /** - * Instantiates, logs and throws a BugException. The message is logged at - * ERROR level. - *

- * This method never returns normally. - * - * @param message the message for the log and exception. - * @throws BugException always. - */ - public void throwBugException(String message) throws BugException { - BugException e = new BugException(message); - log(createLogLine(0, LogLevel.ERROR, message, e)); - throw e; - } - - /** - * Instantiates, logs and throws a BugException. The message is logged at - * ERROR level with the specified cause. - *

- * This method never returns normally. - * - * @param message the message for the log and exception. - * @param cause the causing exception (may be null). - * @throws BugException always. - */ - public void throwBugException(String message, Throwable cause) throws BugException { - BugException e = new BugException(message, cause); - log(createLogLine(0, LogLevel.ERROR, message, cause)); - throw e; - } - - - - - /** - * Create a LogLine object from the provided information. This method must be - * called directly from the called method in order for the trace position - * to be correct! - * - * @param additionalLevels how many additional stack trace levels to include on the line. - * @param level the log level. - * @param message the log message (null ok). - * @param cause the log exception (null ok). - * - * @return a LogLine populated with all necessary fields. - */ - private LogLine createLogLine(int additionalLevels, LogLevel level, String message, - Throwable cause) { - TraceException trace; - if (level.atLeast(TRACING_LOG_LEVEL)) { - trace = new TraceException(2, 2 + additionalLevels); - } else { - trace = null; - } - return new LogLine(level, trace, message, cause); - } -} diff --git a/core/src/net/sf/openrocket/logging/LogLevel.java b/core/src/net/sf/openrocket/logging/LogLevel.java deleted file mode 100644 index a5783856..00000000 --- a/core/src/net/sf/openrocket/logging/LogLevel.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.sf.openrocket.logging; - -import java.util.Locale; - -/** - * The logging level. The natural order of the LogLevel orders the levels - * from highest priority to lowest priority. Comparisons of the relative levels - * should be performed using the methods {@link #atLeast(LogLevel)}, - * {@link #moreThan(LogLevel)} and {@link #compareTo(LogLevel)}. - *

- * A description of the level can be obtained using {@link #toString()}. - * - * @author Sampo Niskanen - */ -public enum LogLevel { - /** - * Level for indicating a bug or error condition noticed in the software or JRE. - * No ERROR level events _should_ occur while running the program. - */ - ERROR, - - /** - * Level for indicating error conditions or atypical events that can occur during - * normal operation (errors while loading files, weird computation results etc). - */ - WARN, - - /** - * Level for logging user actions (adding and modifying components, running - * simulations etc). A user action should be logged as soon as possible on this - * level. The level is separate so that additional INFO messages won't purge - * user actions from a bounded log buffer. - */ - USER, - - /** - * Level for indicating general level actions the software is performing and - * other notable events during execution (dialogs shown, simulations run etc). - */ - INFO, - - /** - * Level for indicating mid-results, outcomes of methods and other debugging - * information. The data logged should be of value when analyzing error - * conditions and what has caused them. Places that are called repeatedly - * during e.g. flight simulation should use the VBOSE level instead. - */ - DEBUG, - - /** - * Level of verbose debug logging to be used in areas which are called repeatedly, - * such as computational methods used in simulations. This level is separated to - * allow filtering out the verbose logs generated during simulations, DnD etc. - * from the normal debug logs. - */ - VBOSE; - - /** The log level with highest priority */ - public static final LogLevel HIGHEST; - /** The log level with lowest priority */ - public static final LogLevel LOWEST; - /** The maximum length of a level textual description */ - public static final int LENGTH; - - static { - int length = 0; - for (LogLevel l : LogLevel.values()) { - length = Math.max(length, l.toString().length()); - } - LENGTH = length; - - LogLevel[] values = LogLevel.values(); - HIGHEST = values[0]; - LOWEST = values[values.length - 1]; - } - - /** - * Return true if this log level is of a priority at least that of - * level. - */ - public boolean atLeast(LogLevel level) { - return this.compareTo(level) <= 0; - } - - /** - * Return true if this log level is of a priority greater than that of - * level. - */ - public boolean moreThan(LogLevel level) { - return this.compareTo(level) < 0; - } - - - /** - * Return a log level corresponding to a string. The string is case-insensitive. If the - * string is case-insensitively equal to "all", then the lowest logging level is returned. - * - * @param value the string name of a log level, or "all" - * @param defaultLevel the value to return if the string doesn't correspond to any log level or is null - * @return the corresponding log level, of defaultLevel. - */ - public static LogLevel fromString(String value, LogLevel defaultLevel) { - - // Normalize the string - if (value == null) { - return defaultLevel; - } - value = value.toUpperCase(Locale.ENGLISH).trim(); - - // Find the correct level - LogLevel level = defaultLevel; - if (value.equals("ALL")) { - LogLevel[] values = LogLevel.values(); - level = values[values.length - 1]; - } else { - try { - level = LogLevel.valueOf(value); - } catch (Exception e) { - // Ignore - } - } - return level; - } - -} diff --git a/core/src/net/sf/openrocket/logging/LogLevelBufferLogger.java b/core/src/net/sf/openrocket/logging/LogLevelBufferLogger.java deleted file mode 100644 index d9021065..00000000 --- a/core/src/net/sf/openrocket/logging/LogLevelBufferLogger.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.sf.openrocket.logging; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumMap; -import java.util.List; - -/** - * A logger that buffers a specific number of log lines from every log - * level. This prevents a multitude of lower-level lines from purging - * away important higher-level messages. The method {@link #getLogs()} - * combines these logs into their original (natural) order. A log line - * is also inserted stating the number of log lines of the particular - * level that have been purged from the buffer. - * - * @author Sampo Niskanen - */ -public class LogLevelBufferLogger extends LogHelper { - - private final EnumMap loggers = - new EnumMap(LogLevel.class); - - - /** - * Sole constructor. - * @param count the number of log lines from each level to buffer. - */ - public LogLevelBufferLogger(int count) { - for (LogLevel level : LogLevel.values()) { - loggers.put(level, new BufferLogger(count)); - } - } - - @Override - public void log(LogLine line) { - // Delegate to the buffered logger of this level - loggers.get(line.getLevel()).log(line); - } - - - /** - * Retrieve all buffered log lines in order. A log line is also added to indicate the number of - * log lines that have been purged for that log level. - * - * @return a list of log lines in order. - */ - public List getLogs() { - List result = new ArrayList(); - - for (LogLevel level : LogLevel.values()) { - BufferLogger logger = loggers.get(level); - List logs = logger.getLogs(); - int misses = logger.getOverwriteCount(); - - if (misses > 0) { - if (logs.isEmpty()) { - result.add(new LogLine(level, 0, 0, null, - "===== " + misses + " " + level + " lines removed but log is empty! =====", - null)); - } else { - result.add(new LogLine(level, logs.get(0).getLogCount(), 0, null, - "===== " + misses + " " + level + " lines removed =====", null)); - } - } - result.addAll(logs); - } - - Collections.sort(result); - return result; - } - - -} diff --git a/core/src/net/sf/openrocket/logging/LogLine.java b/core/src/net/sf/openrocket/logging/LogLine.java deleted file mode 100644 index c2dc4fa6..00000000 --- a/core/src/net/sf/openrocket/logging/LogLine.java +++ /dev/null @@ -1,155 +0,0 @@ -package net.sf.openrocket.logging; - -import java.io.PrintWriter; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Container object for a log line. A log line consists of the following elements: - *

    - *
  • a LogLevel - *
  • a TraceException - *
  • a message - *
  • a cause Throwable - *
  • an incremental log line counter (provided by LogLine) - *
  • a millisecond timestamp (provided by LogLine) - *
- * Any one of the provided input values may be null. - * - * @author Sampo Niskanen - */ -public class LogLine implements Comparable { - - private static final AtomicInteger logCount = new AtomicInteger(1); - private static final long startTime = System.currentTimeMillis(); - - private final LogLevel level; - private final int count; - private final long timestamp; - private final TraceException trace; - private final String message; - private final Throwable cause; - - private volatile String formattedMessage = null; - - - /** - * Construct a LogLine at the current moment. The next log line count number is selected - * and the current run time set to the timestamp. - * - * @param level the logging level - * @param trace the trace exception for the log line, null permitted - * @param message the log message - * @param cause the causing throwable, null permitted - */ - public LogLine(LogLevel level, TraceException trace, String message, Throwable cause) { - this(level, logCount.getAndIncrement(), System.currentTimeMillis() - startTime, trace, message, cause); - } - - /** - * Construct a LogLine with all parameters. This should only be used in special conditions, - * for example to insert a log line at a specific point within normal logs. - * - * @param level the logging level - * @param count the log line count number - * @param timestamp the log line timestamp - * @param trace the trace exception for the log line, null permitted - * @param message the log message - * @param cause the causing throwable, null permitted - */ - public LogLine(LogLevel level, int count, long timestamp, - TraceException trace, String message, Throwable cause) { - this.level = level; - this.count = count; - this.timestamp = timestamp; - this.trace = trace; - this.message = message; - this.cause = cause; - } - - - - /** - * @return the level - */ - public LogLevel getLevel() { - return level; - } - - - /** - * @return the count - */ - public int getLogCount() { - return count; - } - - - /** - * @return the timestamp - */ - public long getTimestamp() { - return timestamp; - } - - - /** - * @return the trace - */ - public TraceException getTrace() { - return trace; - } - - - /** - * @return the message - */ - public String getMessage() { - return message; - } - - - /** - * @return the error - */ - public Throwable getCause() { - return cause; - } - - - - - /** - * Return a formatted string of the log line. The line contains the log - * line count, the time stamp, the log level, the trace position, the log - * message and, if provided, the stack trace of the error throwable. - */ - @Override - public String toString() { - if (formattedMessage == null) { - String str; - str = String.format("%4d %10.3f %-" + LogLevel.LENGTH + "s %s %s", - count, timestamp / 1000.0, (level != null) ? level.toString() : "NULL", - (trace != null) ? trace.getMessage() : "(-)", - message); - if (cause != null) { - StackTraceWriter stw = new StackTraceWriter(); - PrintWriter pw = new PrintWriter(stw); - cause.printStackTrace(pw); - pw.flush(); - str = str + "\n" + stw.toString(); - } - formattedMessage = str; - } - return formattedMessage; - } - - - /** - * Compare against another log line based on the log line count number. - */ - @Override - public int compareTo(LogLine o) { - return this.count - o.count; - } - -} diff --git a/core/src/net/sf/openrocket/logging/PrintStreamLogger.java b/core/src/net/sf/openrocket/logging/PrintStreamLogger.java deleted file mode 100644 index d598783f..00000000 --- a/core/src/net/sf/openrocket/logging/PrintStreamLogger.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.sf.openrocket.logging; - -import java.io.PrintStream; -import java.util.EnumMap; - -/** - * A logger that output log lines to various print streams depending on the log level. - * By default output is logged nowhere. - * - * @author Sampo Niskanen - */ -public class PrintStreamLogger extends LogHelper { - - private final EnumMap output = new EnumMap(LogLevel.class); - - - @Override - public void log(LogLine line) { - PrintStream stream = output.get(line.getLevel()); - if (stream != null) { - stream.println(line.toString()); - } - } - - public PrintStream getOutput(LogLevel level) { - return output.get(level); - } - - public void setOutput(LogLevel level, PrintStream stream) { - if (level == null) { - throw new IllegalArgumentException("level=" + level + " stream=" + stream); - } - output.put(level, stream); - } - -} diff --git a/core/src/net/sf/openrocket/logging/StackTraceWriter.java b/core/src/net/sf/openrocket/logging/StackTraceWriter.java deleted file mode 100644 index dbe2c5a9..00000000 --- a/core/src/net/sf/openrocket/logging/StackTraceWriter.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.sf.openrocket.logging; - -import java.io.IOException; -import java.io.Writer; - -public class StackTraceWriter extends Writer { - - public static final String PREFIX = " > "; - - private final StringBuilder buffer = new StringBuilder(); - private boolean addPrefix = true; - - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - for (int i=0; i 0) { - return buffer.substring(0, buffer.length()-1); - } else { - return buffer.toString(); - } - } - - - @Override - public void close() throws IOException { - // no-op - } - - @Override - public void flush() throws IOException { - // no-op - } - -} diff --git a/core/src/net/sf/openrocket/logging/TraceException.java b/core/src/net/sf/openrocket/logging/TraceException.java deleted file mode 100644 index f3fc1714..00000000 --- a/core/src/net/sf/openrocket/logging/TraceException.java +++ /dev/null @@ -1,139 +0,0 @@ -package net.sf.openrocket.logging; - - - -/** - * An exception that is used to store a stack trace. On modern computers - * instantiation of an exception takes on the order of one microsecond, while - * examining the trace typically takes several times longer. Therefore the - * exception should be stored and the stack trace examined only when necessary. - *

- * The {@link #getMessage()} method returns a description of the position - * where this exception has been instantiated. The position is provided - * as many levels upwards from the instantiation position as provided to the - * constructor. - * - * @author Sampo Niskanen - */ -public class TraceException extends Exception { - - private static final String STANDARD_PACKAGE_PREFIX = "net.sf.openrocket."; - - private final int minLevel; - private final int maxLevel; - private volatile String message = null; - - - /** - * Instantiate exception that provides the line of instantiation as a message. - */ - public TraceException() { - this(0, 0); - } - - /** - * Instantiate exception that provides the provided number of levels upward - * from the instantiation location as a message. The level provided - * is how many levels upward should be examined to find the stack trace - * position for the exception message. - * - * @param level how many levels upward to examine the stack trace to find - * the correct message. - */ - public TraceException(int level) { - this(level, level); - } - - - /** - * Instantiate exception that provides a range of levels upward from the - * instantiation location as a message. This is useful to identify the - * next level of callers upward. - * - * @param minLevel the first level which to include. - * @param maxLevel the last level which to include. - */ - public TraceException(int minLevel, int maxLevel) { - if (minLevel > maxLevel || minLevel < 0) { - throw new IllegalArgumentException("minLevel=" + minLevel + " maxLevel=" + maxLevel); - } - this.minLevel = minLevel; - this.maxLevel = maxLevel; - } - - - /** - * Construct an exception with the specified message. - * - * @param message the message for the exception. - */ - public TraceException(String message) { - this(0, 0); - this.message = message; - } - - - /** - * Construct an exception with the specified message and cause. - * - * @param message the message for the exception. - * @param cause the cause for this exception. - */ - public TraceException(String message, Throwable cause) { - this(0, 0); - this.message = message; - this.initCause(cause); - } - - - /** - * Get the description of the code position as provided in the constructor. - */ - @Override - public String getMessage() { - if (message == null) { - StackTraceElement[] elements = this.getStackTrace(); - - StringBuilder sb = new StringBuilder(); - sb.append('('); - - if (elements == null || elements.length == 0) { - sb.append("no stack trace"); - } else { - - int levelCount = 0; - int position = minLevel; - while (levelCount <= (maxLevel - minLevel) && position < elements.length) { - - // Ignore synthetic "access$0" methods generated by the JRE - if (elements[position].getMethodName().contains("$")) { - position++; - continue; - } - - if (levelCount > 0) { - sb.append(' '); - } - sb.append(toString(elements[position])); - levelCount++; - position++; - } - - } - sb.append(')'); - - message = sb.toString(); - } - return message; - } - - - private static String toString(StackTraceElement element) { - if (element.getClassName().startsWith(STANDARD_PACKAGE_PREFIX)) { - return element.getFileName() + ":" + element.getLineNumber(); - } else { - return element.toString(); - } - } - -} diff --git a/core/src/net/sf/openrocket/masscalc/AbstractMassCalculator.java b/core/src/net/sf/openrocket/masscalc/AbstractMassCalculator.java deleted file mode 100644 index 30b53de6..00000000 --- a/core/src/net/sf/openrocket/masscalc/AbstractMassCalculator.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.sf.openrocket.masscalc; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.startup.Application; - -/** - * Abstract base for mass calculators. Provides functionality for cacheing mass data. - * - * @author Sampo Niskanen - */ -public abstract class AbstractMassCalculator implements MassCalculator { - private static final LogHelper log = Application.getLogger(); - - private int rocketMassModID = -1; - private int rocketTreeModID = -1; - - - /** - * Check the current cache consistency. This method must be called by all - * methods that may use any cached data before any other operations are - * performed. If the rocket has changed since the previous call to - * checkCache(), then {@link #voidMassCache()} is called. - *

- * This method performs the checking based on the rocket's modification IDs, - * so that these method may be called from listeners of the rocket itself. - * - * @param configuration the configuration of the current call - */ - protected final void checkCache(Configuration configuration) { - if (rocketMassModID != configuration.getRocket().getMassModID() || - rocketTreeModID != configuration.getRocket().getTreeModID()) { - rocketMassModID = configuration.getRocket().getMassModID(); - rocketTreeModID = configuration.getRocket().getTreeModID(); - log.debug("Voiding the mass cache"); - voidMassCache(); - } - } - - - - /** - * Void cached mass data. This method is called whenever a change occurs in - * the rocket structure that affects the mass of the rocket and when a new - * Rocket is used. This method must be overridden to void any cached data - * necessary. The method must call super.voidMassCache() during - * its execution. - */ - protected void voidMassCache() { - // No-op - } - -} diff --git a/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java b/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java deleted file mode 100644 index 3fd82fdf..00000000 --- a/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java +++ /dev/null @@ -1,373 +0,0 @@ -package net.sf.openrocket.masscalc; - -import static net.sf.openrocket.util.MathUtil.pow2; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.motor.MotorInstanceConfiguration; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -public class BasicMassCalculator extends AbstractMassCalculator { - - private static final double MIN_MASS = 0.001 * MathUtil.EPSILON; - - - /* - * Cached data. All CG data is in absolute coordinates. All moments of inertia - * are relative to their respective CG. - */ - private Coordinate[] cgCache = null; - private double longitudinalInertiaCache[] = null; - private double rotationalInertiaCache[] = null; - - - - ////////////////// Mass property calculations /////////////////// - - - /** - * Return the CG of the rocket with the specified motor status (no motors, - * ignition, burnout). - */ - @Override - public Coordinate getCG(Configuration configuration, MassCalcType type) { - checkCache(configuration); - calculateStageCache(configuration); - - Coordinate totalCG = null; - - // Stage contribution - for (int stage : configuration.getActiveStages()) { - totalCG = cgCache[stage].average(totalCG); - } - - if (totalCG == null) - totalCG = Coordinate.NUL; - - // Add motor CGs - String motorId = configuration.getMotorConfigurationID(); - if (type != MassCalcType.NO_MOTORS && motorId != null) { - Iterator iterator = configuration.motorIterator(); - while (iterator.hasNext()) { - MotorMount mount = iterator.next(); - RocketComponent comp = (RocketComponent) mount; - Motor motor = mount.getMotor(motorId); - if (motor == null) - continue; - - Coordinate motorCG = type.getCG(motor).add(mount.getMotorPosition(motorId)); - Coordinate[] cgs = comp.toAbsolute(motorCG); - for (Coordinate cg : cgs) { - totalCG = totalCG.average(cg); - } - } - } - - return totalCG; - } - - - - - /** - * Return the CG of the rocket with the provided motor configuration. - */ - @Override - public Coordinate getCG(Configuration configuration, MotorInstanceConfiguration motors) { - checkCache(configuration); - calculateStageCache(configuration); - - Coordinate totalCG = getCG(configuration, MassCalcType.NO_MOTORS); - - // Add motor CGs - if (motors != null) { - for (MotorId id : motors.getMotorIDs()) { - int stage = ((RocketComponent) motors.getMotorMount(id)).getStageNumber(); - if (configuration.isStageActive(stage)) { - - MotorInstance motor = motors.getMotorInstance(id); - Coordinate position = motors.getMotorPosition(id); - Coordinate cg = motor.getCG().add(position); - totalCG = totalCG.average(cg); - - } - } - } - return totalCG; - } - - /** - * Return the longitudinal inertia of the rocket with the specified motor instance - * configuration. - * - * @param configuration the current motor instance configuration - * @return the longitudinal inertia of the rocket - */ - @Override - public double getLongitudinalInertia(Configuration configuration, MotorInstanceConfiguration motors) { - checkCache(configuration); - calculateStageCache(configuration); - - final Coordinate totalCG = getCG(configuration, motors); - double totalInertia = 0; - - // Stages - for (int stage : configuration.getActiveStages()) { - Coordinate stageCG = cgCache[stage]; - - totalInertia += (longitudinalInertiaCache[stage] + - stageCG.weight * MathUtil.pow2(stageCG.x - totalCG.x)); - } - - - // Motors - if (motors != null) { - for (MotorId id : motors.getMotorIDs()) { - int stage = ((RocketComponent) motors.getMotorMount(id)).getStageNumber(); - if (configuration.isStageActive(stage)) { - MotorInstance motor = motors.getMotorInstance(id); - Coordinate position = motors.getMotorPosition(id); - Coordinate cg = motor.getCG().add(position); - - double inertia = motor.getLongitudinalInertia(); - totalInertia += inertia + cg.weight * MathUtil.pow2(cg.x - totalCG.x); - } - } - } - - return totalInertia; - } - - - - /** - * Return the rotational inertia of the rocket with the specified motor instance - * configuration. - * - * @param configuration the current motor instance configuration - * @return the rotational inertia of the rocket - */ - @Override - public double getRotationalInertia(Configuration configuration, MotorInstanceConfiguration motors) { - checkCache(configuration); - calculateStageCache(configuration); - - final Coordinate totalCG = getCG(configuration, motors); - double totalInertia = 0; - - // Stages - for (int stage : configuration.getActiveStages()) { - Coordinate stageCG = cgCache[stage]; - - totalInertia += (rotationalInertiaCache[stage] + - stageCG.weight * (MathUtil.pow2(stageCG.y - totalCG.y) + - MathUtil.pow2(stageCG.z - totalCG.z))); - } - - - // Motors - if (motors != null) { - for (MotorId id : motors.getMotorIDs()) { - int stage = ((RocketComponent) motors.getMotorMount(id)).getStageNumber(); - if (configuration.isStageActive(stage)) { - MotorInstance motor = motors.getMotorInstance(id); - Coordinate position = motors.getMotorPosition(id); - Coordinate cg = motor.getCG().add(position); - - double inertia = motor.getRotationalInertia(); - totalInertia += inertia + cg.weight * (MathUtil.pow2(cg.y - totalCG.y) + - MathUtil.pow2(cg.z - totalCG.z)); - } - } - } - - return totalInertia; - } - - /** - * Return the total mass of the motors - * - * @param configuration the current motor instance configuration - * @return the total mass of all motors - */ - @Override - public double getPropellantMass(Configuration configuration, MotorInstanceConfiguration motors){ - double mass = 0; - - // add up the masses of all motors in the rocket - if (motors != null) { - for (MotorId id : motors.getMotorIDs()) { - MotorInstance motor = motors.getMotorInstance(id); - mass = mass + motor.getCG().weight - motor.getParentMotor().getEmptyCG().weight; - } - } - return mass; - } - - @Override - public Map getCGAnalysis(Configuration configuration, MassCalcType type) { - checkCache(configuration); - calculateStageCache(configuration); - - Map map = new HashMap(); - - for (RocketComponent c : configuration) { - Coordinate[] cgs = c.toAbsolute(c.getCG()); - Coordinate totalCG = Coordinate.NUL; - for (Coordinate cg : cgs) { - totalCG = totalCG.average(cg); - } - map.put(c, totalCG); - } - - map.put(configuration.getRocket(), getCG(configuration, type)); - - return map; - } - - //////// Cache computations //////// - - private void calculateStageCache(Configuration config) { - if (cgCache == null) { - - int stages = config.getRocket().getStageCount(); - - cgCache = new Coordinate[stages]; - longitudinalInertiaCache = new double[stages]; - rotationalInertiaCache = new double[stages]; - - for (int i = 0; i < stages; i++) { - RocketComponent stage = config.getRocket().getChild(i); - MassData data = calculateAssemblyMassData(stage); - cgCache[i] = stage.toAbsolute(data.cg)[0]; - longitudinalInertiaCache[i] = data.longitudinalInertia; - rotationalInertiaCache[i] = data.rotationalInetria; - } - - } - } - - - - /** - * Returns the mass and inertia data for this component and all subcomponents. - * The inertia is returned relative to the CG, and the CG is in the coordinates - * of the specified component, not global coordinates. - */ - private MassData calculateAssemblyMassData(RocketComponent parent) { - MassData parentData = new MassData(); - - // Calculate data for this component - parentData.cg = parent.getComponentCG(); - if (parentData.cg.weight < MIN_MASS) - parentData.cg = parentData.cg.setWeight(MIN_MASS); - - - // Override only this component's data - if (!parent.getOverrideSubcomponents()) { - if (parent.isMassOverridden()) - parentData.cg = parentData.cg.setWeight(MathUtil.max(parent.getOverrideMass(), MIN_MASS)); - if (parent.isCGOverridden()) - parentData.cg = parentData.cg.setXYZ(parent.getOverrideCG()); - } - - parentData.longitudinalInertia = parent.getLongitudinalUnitInertia() * parentData.cg.weight; - parentData.rotationalInetria = parent.getRotationalUnitInertia() * parentData.cg.weight; - - - // Combine data for subcomponents - for (RocketComponent sibling : parent.getChildren()) { - Coordinate combinedCG; - double dx2, dr2; - - // Compute data of sibling - MassData siblingData = calculateAssemblyMassData(sibling); - Coordinate[] siblingCGs = sibling.toRelative(siblingData.cg, parent); - - for (Coordinate siblingCG : siblingCGs) { - - // Compute CG of this + sibling - combinedCG = parentData.cg.average(siblingCG); - - // Add effect of this CG change to parent inertia - dx2 = pow2(parentData.cg.x - combinedCG.x); - parentData.longitudinalInertia += parentData.cg.weight * dx2; - - dr2 = pow2(parentData.cg.y - combinedCG.y) + pow2(parentData.cg.z - combinedCG.z); - parentData.rotationalInetria += parentData.cg.weight * dr2; - - - // Add inertia of sibling - parentData.longitudinalInertia += siblingData.longitudinalInertia; - parentData.rotationalInetria += siblingData.rotationalInetria; - - // Add effect of sibling CG change - dx2 = pow2(siblingData.cg.x - combinedCG.x); - parentData.longitudinalInertia += siblingData.cg.weight * dx2; - - dr2 = pow2(siblingData.cg.y - combinedCG.y) + pow2(siblingData.cg.z - combinedCG.z); - parentData.rotationalInetria += siblingData.cg.weight * dr2; - - // Set combined CG - parentData.cg = combinedCG; - } - } - - // Override total data - if (parent.getOverrideSubcomponents()) { - if (parent.isMassOverridden()) { - double oldMass = parentData.cg.weight; - double newMass = MathUtil.max(parent.getOverrideMass(), MIN_MASS); - parentData.longitudinalInertia = parentData.longitudinalInertia * newMass / oldMass; - parentData.rotationalInetria = parentData.rotationalInetria * newMass / oldMass; - parentData.cg = parentData.cg.setWeight(newMass); - } - if (parent.isCGOverridden()) { - double oldx = parentData.cg.x; - double newx = parent.getOverrideCGX(); - parentData.longitudinalInertia += parentData.cg.weight * pow2(oldx - newx); - parentData.cg = parentData.cg.setX(newx); - } - } - - return parentData; - } - - - private static class MassData { - public Coordinate cg = Coordinate.NUL; - public double longitudinalInertia = 0; - public double rotationalInetria = 0; - } - - - @Override - protected void voidMassCache() { - super.voidMassCache(); - this.cgCache = null; - this.longitudinalInertiaCache = null; - this.rotationalInertiaCache = null; - } - - - - - @Override - public int getModID() { - return 0; - } - - - -} diff --git a/core/src/net/sf/openrocket/masscalc/MassCalculator.java b/core/src/net/sf/openrocket/masscalc/MassCalculator.java deleted file mode 100644 index 5e657f7a..00000000 --- a/core/src/net/sf/openrocket/masscalc/MassCalculator.java +++ /dev/null @@ -1,96 +0,0 @@ -package net.sf.openrocket.masscalc; - -import java.util.Map; - -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorInstanceConfiguration; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Monitorable; - -public interface MassCalculator extends Monitorable { - - public static enum MassCalcType { - NO_MOTORS { - @Override - public Coordinate getCG(Motor motor) { - return Coordinate.NUL; - } - }, - LAUNCH_MASS { - @Override - public Coordinate getCG(Motor motor) { - return motor.getLaunchCG(); - } - }, - BURNOUT_MASS { - @Override - public Coordinate getCG(Motor motor) { - return motor.getEmptyCG(); - } - }; - - public abstract Coordinate getCG(Motor motor); - } - - /** - * Compute the CG of the provided configuration. - * - * @param configuration the rocket configuration - * @param type the state of the motors (none, launch mass, burnout mass) - * @return the CG of the configuration - */ - public Coordinate getCG(Configuration configuration, MassCalcType type); - - /** - * Compute the CG of the provided configuration with specified motors. - * - * @param configuration the rocket configuration - * @param motors the motor configuration - * @return the CG of the configuration - */ - public Coordinate getCG(Configuration configuration, MotorInstanceConfiguration motors); - - /** - * Compute the longitudinal inertia of the provided configuration with specified motors. - * - * @param configuration the rocket configuration - * @param motors the motor configuration - * @return the longitudinal inertia of the configuration - */ - public double getLongitudinalInertia(Configuration configuration, MotorInstanceConfiguration motors); - - /** - * Compute the rotational inertia of the provided configuration with specified motors. - * - * @param configuration the rocket configuration - * @param motors the motor configuration - * @return the rotational inertia of the configuration - */ - public double getRotationalInertia(Configuration configuration, MotorInstanceConfiguration motors); - - /** - * Return the total mass of the motors - * - * @param motors the motor configuration - * @param configuration the current motor instance configuration - * @return the total mass of all motors - */ - public double getPropellantMass(Configuration configuration, MotorInstanceConfiguration motors); - - /** - * Compute an analysis of the per-component CG's of the provided configuration. - * The returned map will contain an entry for each physical rocket component (not stages) - * with its corresponding (best-effort) CG. Overriding of subcomponents is ignored. - * The CG of the entire configuration with motors is stored in the entry with the corresponding - * Rocket as the key. - * - * @param configuration the rocket configuration - * @param type the state of the motors (none, launch mass, burnout mass) - * @return a map from each rocket component to its corresponding CG. - */ - public Map getCGAnalysis(Configuration configuration, MassCalcType type); - - -} diff --git a/core/src/net/sf/openrocket/material/Material.java b/core/src/net/sf/openrocket/material/Material.java deleted file mode 100644 index 055fc336..00000000 --- a/core/src/net/sf/openrocket/material/Material.java +++ /dev/null @@ -1,250 +0,0 @@ -package net.sf.openrocket.material; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.MathUtil; - -/** - * A class for different material types. Each material has a name and density. - * The interpretation of the density depends on the material type. For - * {@link Type#BULK} it is kg/m^3, for {@link Type#SURFACE} km/m^2. - *

- * Objects of this type are immutable. - * - * @author Sampo Niskanen - */ - -public abstract class Material implements Comparable { - - private static final Translator trans = Application.getTranslator(); - - public enum Type { - LINE("Databases.materials.types.Line", UnitGroup.UNITS_DENSITY_LINE), - SURFACE("Databases.materials.types.Surface", UnitGroup.UNITS_DENSITY_SURFACE), - BULK("Databases.materials.types.Bulk", UnitGroup.UNITS_DENSITY_BULK); - - private final String name; - private final UnitGroup units; - - private Type(String nameKey, UnitGroup units) { - this.name = trans.get(nameKey); - this.units = units; - } - - public UnitGroup getUnitGroup() { - return units; - } - - @Override - public String toString() { - return name; - } - } - - - ///// Definitions of different material types ///// - - public static class Line extends Material { - Line(String name, double density, boolean userDefined) { - super(name, density, userDefined); - } - - @Override - public Type getType() { - return Type.LINE; - } - } - - public static class Surface extends Material { - - Surface(String name, double density, boolean userDefined) { - super(name, density, userDefined); - } - - @Override - public Type getType() { - return Type.SURFACE; - } - - @Override - public String toStorableString() { - return super.toStorableString(); - } - } - - public static class Bulk extends Material { - Bulk(String name, double density, boolean userDefined) { - super(name, density, userDefined); - } - - @Override - public Type getType() { - return Type.BULK; - } - } - - - - private final String name; - private final double density; - private final boolean userDefined; - - - /** - * Constructor for materials. - * - * @param name ignored when defining system materials. - * @param key ignored when defining user materials. - * @param density - * @param userDefined true if this is a user defined material, false if it is a system material. - */ - private Material(String name, double density, boolean userDefined) { - this.name = name; - this.userDefined = userDefined; - this.density = density; - } - - public double getDensity() { - return density; - } - - public String getName() { - return name; - } - - public String getName(Unit u) { - return name + " (" + u.toStringUnit(density) + ")"; - } - - public boolean isUserDefined() { - return userDefined; - } - - public abstract Type getType(); - - @Override - public String toString() { - return this.getName(this.getType().getUnitGroup().getDefaultUnit()); - } - - - /** - * Compares this object to another object. Material objects are equal if and only if - * their types, names and densities are identical. - */ - @Override - public boolean equals(Object o) { - if (o == null) - return false; - if (this.getClass() != o.getClass()) - return false; - Material m = (Material) o; - return ((m.name.equals(this.name)) && MathUtil.equals(m.density, this.density)); - } - - - /** - * A hashCode() method giving a hash code compatible with the equals() method. - */ - @Override - public int hashCode() { - return name.hashCode() + (int) (density * 1000); - } - - - /** - * Order the materials according to their name, secondarily according to density. - */ - @Override - public int compareTo(Material o) { - int c = this.name.compareTo(o.name); - if (c != 0) { - return c; - } else { - return (int) ((this.density - o.density) * 1000); - } - } - - - /** - * Return a new material. The name is used as-is, without any translation. - * - * @param type the material type - * @param name the material name - * @param density the material density - * @param userDefined whether the material is user-defined or not - * @return the new material - */ - public static Material newMaterial(Type type, String name, double density, boolean userDefined) { - switch (type) { - case LINE: - return new Material.Line(name, density, userDefined); - - case SURFACE: - return new Material.Surface(name, density, userDefined); - - case BULK: - return new Material.Bulk(name, density, userDefined); - - default: - throw new IllegalArgumentException("Unknown material type: " + type); - } - } - - public String toStorableString() { - return getType().name() + "|" + name.replace('|', ' ') + '|' + density; - } - - - /** - * Return a material defined by the provided string. - * - * @param str the material storage string. - * @param userDefined whether the created material is user-defined. - * @return a new Material object. - * @throws IllegalArgumentException if str is invalid or null. - */ - public static Material fromStorableString(String str, boolean userDefined) { - if (str == null) - throw new IllegalArgumentException("Material string is null"); - - String[] split = str.split("\\|", 3); - if (split.length < 3) - throw new IllegalArgumentException("Illegal material string: " + str); - - Type type = null; - String name; - double density; - - try { - type = Type.valueOf(split[0]); - } catch (Exception e) { - throw new IllegalArgumentException("Illegal material string: " + str, e); - } - - name = split[1]; - - try { - density = Double.parseDouble(split[2]); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Illegal material string: " + str, e); - } - - switch (type) { - case BULK: - return new Material.Bulk(name, density, userDefined); - - case SURFACE: - return new Material.Surface(name, density, userDefined); - - case LINE: - return new Material.Line(name, density, userDefined); - - default: - throw new IllegalArgumentException("Illegal material string: " + str); - } - } - -} diff --git a/core/src/net/sf/openrocket/material/MaterialStorage.java b/core/src/net/sf/openrocket/material/MaterialStorage.java deleted file mode 100644 index 0d7f11b4..00000000 --- a/core/src/net/sf/openrocket/material/MaterialStorage.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.material; - -import net.sf.openrocket.database.Database; -import net.sf.openrocket.database.DatabaseListener; -import net.sf.openrocket.startup.Application; - -/** - * Class for storing changes to user-added materials. The materials are stored to - * the OpenRocket preferences. - * - * @author Sampo Niskanen - */ -public class MaterialStorage implements DatabaseListener { - - @Override - public void elementAdded(Material material, Database source) { - if (material.isUserDefined()) { - Application.getPreferences().addUserMaterial(material); - } - } - - @Override - public void elementRemoved(Material material, Database source) { - Application.getPreferences().removeUserMaterial(material); - } - -} diff --git a/core/src/net/sf/openrocket/models/atmosphere/AtmosphericConditions.java b/core/src/net/sf/openrocket/models/atmosphere/AtmosphericConditions.java deleted file mode 100644 index a988ac8e..00000000 --- a/core/src/net/sf/openrocket/models/atmosphere/AtmosphericConditions.java +++ /dev/null @@ -1,151 +0,0 @@ -package net.sf.openrocket.models.atmosphere; - -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.UniqueID; - -public class AtmosphericConditions implements Cloneable, Monitorable { - - /** Specific gas constant of dry air. */ - public static final double R = 287.053; - - /** Specific heat ratio of air. */ - public static final double GAMMA = 1.4; - - /** The standard air pressure (1.01325 bar). */ - public static final double STANDARD_PRESSURE = 101325.0; - - /** The standard air temperature (20 degrees Celcius). */ - public static final double STANDARD_TEMPERATURE = 293.15; - - - - /** Air pressure, in Pascals. */ - private double pressure; - - /** Air temperature, in Kelvins. */ - private double temperature; - - private int modID; - - - /** - * Construct standard atmospheric conditions. - */ - public AtmosphericConditions() { - this(STANDARD_TEMPERATURE, STANDARD_PRESSURE); - } - - /** - * Construct specified atmospheric conditions. - * - * @param temperature the temperature in Kelvins. - * @param pressure the pressure in Pascals. - */ - public AtmosphericConditions(double temperature, double pressure) { - this.setTemperature(temperature); - this.setPressure(pressure); - this.modID = UniqueID.next(); - } - - - - public double getPressure() { - return pressure; - } - - public void setPressure(double pressure) { - this.pressure = pressure; - this.modID = UniqueID.next(); - } - - public double getTemperature() { - return temperature; - } - - public void setTemperature(double temperature) { - this.temperature = temperature; - this.modID = UniqueID.next(); - } - - /** - * Return the current density of air for dry air. - * - * @return the current density of air. - */ - public double getDensity() { - return getPressure() / (R*getTemperature()); - } - - - /** - * Return the current speed of sound for dry air. - *

- * The speed of sound is calculated using the expansion around the temperature 0 C - * c = 331.3 + 0.606*T where T is in Celcius. The result is accurate - * to about 0.5 m/s for temperatures between -30 and 30 C, and within 2 m/s - * for temperatures between -55 and 30 C. - * - * @return the current speed of sound. - */ - public double getMachSpeed() { - return 165.77 + 0.606 * getTemperature(); - } - - - /** - * Return the current kinematic viscosity of the air. - *

- * The effect of temperature on the viscosity of a gas can be computed using - * Sutherland's formula. In the region of -40 ... 40 degrees Celcius the effect - * is highly linear, and thus a linear approximation is used in its stead. - * This is divided by the result of {@link #getDensity()} to achieve the - * kinematic viscosity. - * - * @return the current kinematic viscosity. - */ - public double getKinematicViscosity() { - double v = 3.7291e-06 + 4.9944e-08 * getTemperature(); - return v / getDensity(); - } - - - /** - * Return a copy of the atmospheric conditions. - */ - @Override - public AtmosphericConditions clone() { - try { - return (AtmosphericConditions) super.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException encountered!"); - } - } - - @Override - public boolean equals(Object other) { - if (this == other) - return true; - if (!(other instanceof AtmosphericConditions)) - return false; - AtmosphericConditions o = (AtmosphericConditions) other; - return MathUtil.equals(this.pressure, o.pressure) && MathUtil.equals(this.temperature, o.temperature); - } - - @Override - public int hashCode() { - return (int) (this.pressure + this.temperature*1000); - } - - @Override - public int getModID() { - return modID; - } - - @Override - public String toString() { - return String.format("AtmosphericConditions[T=%.2f,P=%.2f]", getTemperature(), getPressure()); - } - -} diff --git a/core/src/net/sf/openrocket/models/atmosphere/AtmosphericModel.java b/core/src/net/sf/openrocket/models/atmosphere/AtmosphericModel.java deleted file mode 100644 index 6a4eec84..00000000 --- a/core/src/net/sf/openrocket/models/atmosphere/AtmosphericModel.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.sf.openrocket.models.atmosphere; - -import net.sf.openrocket.util.Monitorable; - -public interface AtmosphericModel extends Monitorable { - - public AtmosphericConditions getConditions(double altitude); - -} diff --git a/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java b/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java deleted file mode 100644 index eef78b00..00000000 --- a/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.sf.openrocket.models.atmosphere; - -import static net.sf.openrocket.models.atmosphere.AtmosphericConditions.R; -import net.sf.openrocket.util.MathUtil; - - -/** - * An atmospheric temperature/pressure model based on the International Standard Atmosphere - * (ISA). The no-argument constructor creates an {@link AtmosphericModel} that corresponds - * to the ISA model. It is extended by the other constructors to allow defining a custom - * first layer. The base temperature and pressure are as given, and all other values - * are calculated based on these. - *

- * TODO: LOW: Values at altitudes over 32km differ from standard results by ~5%. - * - * @author Sampo Niskanen - */ -public class ExtendedISAModel extends InterpolatingAtmosphericModel { - - public static final double STANDARD_TEMPERATURE = 288.15; - public static final double STANDARD_PRESSURE = 101325; - - private static final double G = 9.80665; - - private final double[] layer = { 0, 11000, 20000, 32000, 47000, 51000, 71000, 84852 }; - private final double[] baseTemperature = { - 288.15, 216.65, 216.65, 228.65, 270.65, 270.65, 214.65, 186.95 - }; - private final double[] basePressure = new double[layer.length]; - - - /** - * Construct the standard ISA model. - */ - public ExtendedISAModel() { - this(STANDARD_TEMPERATURE, STANDARD_PRESSURE); - } - - /** - * Construct an extended model with the given temperature and pressure at MSL. - * - * @param temperature the temperature at MSL. - * @param pressure the pressure at MSL. - */ - public ExtendedISAModel(double temperature, double pressure) { - this(0, temperature, pressure); - } - - - /** - * Construct an extended model with the given temperature and pressure at the - * specified altitude. Conditions below the given altitude cannot be calculated, - * and the values at the specified altitude will be returned instead. The altitude - * must be lower than the altitude of the next ISA standard layer (below 11km). - * - * @param altitude the altitude of the measurements. - * @param temperature the temperature. - * @param pressure the pressure. - * @throws IllegalArgumentException if the altitude exceeds the second layer boundary - * of the ISA model (over 11km). - */ - public ExtendedISAModel(double altitude, double temperature, double pressure) { - if (altitude >= layer[1]) { - throw new IllegalArgumentException("Too high first altitude: " + altitude); - } - - layer[0] = altitude; - baseTemperature[0] = temperature; - basePressure[0] = pressure; - - for (int i = 1; i < basePressure.length; i++) { - basePressure[i] = getExactConditions(layer[i] - 1).getPressure(); - } - } - - - @Override - protected AtmosphericConditions getExactConditions(double altitude) { - altitude = MathUtil.clamp(altitude, layer[0], layer[layer.length - 1]); - int n; - for (n = 0; n < layer.length - 1; n++) { - if (layer[n + 1] > altitude) - break; - } - - double rate = (baseTemperature[n + 1] - baseTemperature[n]) / (layer[n + 1] - layer[n]); - - double t = baseTemperature[n] + (altitude - layer[n]) * rate; - double p; - if (Math.abs(rate) > 0.001) { - p = basePressure[n] * - Math.pow(1 + (altitude - layer[n]) * rate / baseTemperature[n], -G / (rate * R)); - } else { - p = basePressure[n] * - Math.exp(-(altitude - layer[n]) * G / (R * baseTemperature[n])); - } - - return new AtmosphericConditions(t, p); - } - - @Override - protected double getMaxAltitude() { - return layer[layer.length - 1]; - } - - - public static void main(String foo[]) { - ExtendedISAModel model1 = new ExtendedISAModel(); - ExtendedISAModel model2 = new ExtendedISAModel(278.15, 100000); - - for (double alt = 0; alt < 80000; alt += 500) { - AtmosphericConditions cond1 = model1.getConditions(alt); - AtmosphericConditions cond2 = model2.getConditions(alt); - - AtmosphericConditions diff = new AtmosphericConditions(); - diff.setPressure((cond2.getPressure() - cond1.getPressure()) / cond1.getPressure() * 100); - diff.setTemperature((cond2.getTemperature() - cond1.getTemperature()) / cond1.getTemperature() * 100); - //System.out.println("alt=" + alt + ": std:" + cond1 + " mod:" + cond2 + " diff:" + diff); - } - } - - @Override - public int getModID() { - return 0; - } - -} diff --git a/core/src/net/sf/openrocket/models/atmosphere/InterpolatingAtmosphericModel.java b/core/src/net/sf/openrocket/models/atmosphere/InterpolatingAtmosphericModel.java deleted file mode 100644 index 6a416a9a..00000000 --- a/core/src/net/sf/openrocket/models/atmosphere/InterpolatingAtmosphericModel.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.sf.openrocket.models.atmosphere; - -/** - * An abstract atmospheric model that pre-computes the conditions on a number of layers - * and later linearly interpolates the values from between these layers. - * - * @author Sampo Niskanen - */ -public abstract class InterpolatingAtmosphericModel implements AtmosphericModel { - /** Layer thickness of interpolated altitude. */ - private static final double DELTA = 500; - - private AtmosphericConditions[] levels = null; - - - public AtmosphericConditions getConditions(double altitude) { - if (levels == null) - computeLayers(); - - if (altitude <= 0) - return levels[0]; - if (altitude >= DELTA * (levels.length - 1)) - return levels[levels.length - 1]; - - int n = (int) (altitude / DELTA); - double d = (altitude - n * DELTA) / DELTA; - AtmosphericConditions c = new AtmosphericConditions(); - c.setTemperature(levels[n].getTemperature() * (1 - d) + levels[n + 1].getTemperature() * d); - c.setPressure(levels[n].getPressure() * (1 - d) + levels[n + 1].getPressure() * d); - - return c; - } - - - private void computeLayers() { - double max = getMaxAltitude(); - int n = (int) (max / DELTA) + 1; - levels = new AtmosphericConditions[n]; - for (int i = 0; i < n; i++) { - levels[i] = getExactConditions(i * DELTA); - } - } - - - protected abstract double getMaxAltitude(); - - protected abstract AtmosphericConditions getExactConditions(double altitude); -} diff --git a/core/src/net/sf/openrocket/models/gravity/GravityModel.java b/core/src/net/sf/openrocket/models/gravity/GravityModel.java deleted file mode 100644 index 6bee52a7..00000000 --- a/core/src/net/sf/openrocket/models/gravity/GravityModel.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.models.gravity; - -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.WorldCoordinate; - -/** - * An interface for modeling gravitational acceleration. - * - * @author Sampo Niskanen - */ -public interface GravityModel extends Monitorable { - - /** - * Compute the gravitational acceleration at a given world coordinate - * - * @param wc the world coordinate location - * @return gravitational acceleration in m/s/s - */ - public double getGravity(WorldCoordinate wc); - -} diff --git a/core/src/net/sf/openrocket/models/gravity/WGSGravityModel.java b/core/src/net/sf/openrocket/models/gravity/WGSGravityModel.java deleted file mode 100644 index 41fb5c23..00000000 --- a/core/src/net/sf/openrocket/models/gravity/WGSGravityModel.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.sf.openrocket.models.gravity; - -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.WorldCoordinate; - -/** - * A gravity model based on the WGS84 ellipsoid. - * - * @author Richard Graham - */ -public class WGSGravityModel implements GravityModel { - - // Cache the previously computed value - private WorldCoordinate lastWorldCoordinate; - private double lastg; - - - @Override - public double getGravity(WorldCoordinate wc) { - - // This is a proxy method to calcGravity, to avoid repeated calculation - if (wc != this.lastWorldCoordinate) { - this.lastg = calcGravity(wc); - this.lastWorldCoordinate = wc; - } - - return this.lastg; - - } - - - @Override - public int getModID() { - // The model is immutable, so it can return a constant mod ID - return 0; - } - - - private double calcGravity(WorldCoordinate wc) { - - double sin2lat = MathUtil.pow2(Math.sin(wc.getLatitudeRad())); - double g_0 = 9.7803267714 * ((1.0 + 0.00193185138639 * sin2lat) / Math.sqrt(1.0 - 0.00669437999013 * sin2lat)); - - // Apply correction due to altitude. Note this assumes a spherical earth, but it is a small correction - // so it probably doesn't really matter. Also does not take into account gravity of the atmosphere, again - // correction could be done but not really necessary. - double g_alt = g_0 * MathUtil.pow2(WorldCoordinate.REARTH / (WorldCoordinate.REARTH + wc.getAltitude())); - - return g_alt; - } - -} diff --git a/core/src/net/sf/openrocket/models/wind/PinkNoiseWindModel.java b/core/src/net/sf/openrocket/models/wind/PinkNoiseWindModel.java deleted file mode 100644 index 960325d5..00000000 --- a/core/src/net/sf/openrocket/models/wind/PinkNoiseWindModel.java +++ /dev/null @@ -1,169 +0,0 @@ -package net.sf.openrocket.models.wind; - -import java.util.Random; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.PinkNoise; - -/** - * A wind simulator that generates wind speed as pink noise from a specified average wind speed - * and standard deviance. Currently the wind is always directed in the direction of the negative - * X-axis. The simulated wind is unaffected by the altitude. - * - * @author Sampo Niskanen - */ -public class PinkNoiseWindModel implements WindModel { - - /** Random value with which to XOR the random seed value */ - private static final int SEED_RANDOMIZATION = 0x7343AA03; - - - - /** Pink noise alpha parameter. */ - private static final double ALPHA = 5.0 / 3.0; - - /** Number of poles to use in the pink noise IIR filter. */ - private static final int POLES = 2; - - /** The standard deviation of the generated pink noise with the specified number of poles. */ - private static final double STDDEV = 2.252; - - /** Time difference between random samples. */ - private static final double DELTA_T = 0.05; - - - private double average = 0; - private double standardDeviation = 0; - - private final int seed; - - private PinkNoise randomSource = null; - private double time1; - private double value1, value2; - - - /** - * Construct a new wind simulation with a specific seed value. - * @param seed the seed value. - */ - public PinkNoiseWindModel(int seed) { - this.seed = seed ^ SEED_RANDOMIZATION; - } - - - - /** - * Return the average wind speed. - * - * @return the average wind speed. - */ - public double getAverage() { - return average; - } - - /** - * Set the average wind speed. This method will also modify the - * standard deviation such that the turbulence intensity remains constant. - * - * @param average the average wind speed to set - */ - public void setAverage(double average) { - double intensity = getTurbulenceIntensity(); - this.average = Math.max(average, 0); - setTurbulenceIntensity(intensity); - } - - - - /** - * Return the standard deviation from the average wind speed. - * - * @return the standard deviation of the wind speed - */ - public double getStandardDeviation() { - return standardDeviation; - } - - /** - * Set the standard deviation of the average wind speed. - * - * @param standardDeviation the standardDeviation to set - */ - public void setStandardDeviation(double standardDeviation) { - this.standardDeviation = Math.max(standardDeviation, 0); - } - - - /** - * Return the turbulence intensity (standard deviation / average). - * - * @return the turbulence intensity - */ - public double getTurbulenceIntensity() { - if (MathUtil.equals(average, 0)) { - if (MathUtil.equals(standardDeviation, 0)) - return 0; - else - return 1000; - } - return standardDeviation / average; - } - - /** - * Set the standard deviation to match the turbulence intensity. - * - * @param intensity the turbulence intensity - */ - public void setTurbulenceIntensity(double intensity) { - setStandardDeviation(intensity * average); - } - - - - - - @Override - public Coordinate getWindVelocity(double time, double altitude) { - if (time < 0) { - throw new IllegalArgumentException("Requesting wind speed at t=" + time); - } - - if (randomSource == null) { - randomSource = new PinkNoise(ALPHA, POLES, new Random(seed)); - time1 = 0; - value1 = randomSource.nextValue(); - value2 = randomSource.nextValue(); - } - - if (time < time1) { - reset(); - return getWindVelocity(time, altitude); - } - - while (time1 + DELTA_T < time) { - value1 = value2; - value2 = randomSource.nextValue(); - time1 += DELTA_T; - } - - double a = (time - time1) / DELTA_T; - - double speed = average + (value1 * (1 - a) + value2 * a) * standardDeviation / STDDEV; - // TODO: MEDIUM: Make wind direction configurable - return new Coordinate(speed, 0, 0); - } - - - private void reset() { - randomSource = null; - } - - - - @Override - public int getModID() { - return (int) (average * 1000 + standardDeviation); - } - -} diff --git a/core/src/net/sf/openrocket/models/wind/WindModel.java b/core/src/net/sf/openrocket/models/wind/WindModel.java deleted file mode 100644 index 3f78f102..00000000 --- a/core/src/net/sf/openrocket/models/wind/WindModel.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.sf.openrocket.models.wind; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Monitorable; - -public interface WindModel extends Monitorable { - - public Coordinate getWindVelocity(double time, double altitude); - -} diff --git a/core/src/net/sf/openrocket/motor/DesignationComparator.java b/core/src/net/sf/openrocket/motor/DesignationComparator.java deleted file mode 100644 index 21489cb7..00000000 --- a/core/src/net/sf/openrocket/motor/DesignationComparator.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.motor; - -import java.text.Collator; -import java.util.Comparator; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Compares two motors designations. The motors are ordered first - * by their motor class, second by their average thrust and lastly by any - * extra modifiers at the end of the designation. - * - * @author Sampo Niskanen - */ -public class DesignationComparator implements Comparator { - private static final Collator COLLATOR; - static { - COLLATOR = Collator.getInstance(Locale.US); - COLLATOR.setStrength(Collator.PRIMARY); - } - - private Pattern pattern = - Pattern.compile("^([0-9][0-9]+|1/([1-8]))?([a-zA-Z])([0-9]+)(.*?)$"); - - @Override - public int compare(String o1, String o2) { - int value; - Matcher m1, m2; - - m1 = pattern.matcher(o1); - m2 = pattern.matcher(o2); - - if (m1.find() && m2.find()) { - - String o1Class = m1.group(3); - int o1Thrust = Integer.parseInt(m1.group(4)); - String o1Extra = m1.group(5); - - String o2Class = m2.group(3); - int o2Thrust = Integer.parseInt(m2.group(4)); - String o2Extra = m2.group(5); - - // 1. Motor class - if (o1Class.equalsIgnoreCase("A") && o2Class.equalsIgnoreCase("A")) { - // 1/2A and 1/4A comparison - String sub1 = m1.group(2); - String sub2 = m2.group(2); - - if (sub1 != null || sub2 != null) { - if (sub1 == null) - sub1 = "1"; - if (sub2 == null) - sub2 = "1"; - value = -COLLATOR.compare(sub1,sub2); - if (value != 0) - return value; - } - } - value = COLLATOR.compare(o1Class,o2Class); - if (value != 0) - return value; - - // 2. Average thrust - if (o1Thrust != o2Thrust) - return o1Thrust - o2Thrust; - - // 3. Extra modifier - return COLLATOR.compare(o1Extra, o2Extra); - - } else { - - // Not understandable designation, simply compare strings - return COLLATOR.compare(o1, o2); - } - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/motor/Manufacturer.java b/core/src/net/sf/openrocket/motor/Manufacturer.java deleted file mode 100644 index 5d562ed7..00000000 --- a/core/src/net/sf/openrocket/motor/Manufacturer.java +++ /dev/null @@ -1,261 +0,0 @@ -package net.sf.openrocket.motor; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Class containing information about motor manufacturers. - * - * @author Sampo Niskanen - */ -public class Manufacturer { - - private static class ManufacturerList extends ConcurrentHashMap { - - void add( Manufacturer m ) { - for( String s : m.getSearchNames() ) { - Manufacturer previousRegistered; - if ( (previousRegistered = putIfAbsent( s, m )) != null ) { - throw new IllegalStateException("Manufacturer name clash between " + - "manufacturers " + previousRegistered + " and " + m + " name " + s); - } - } - } - - } - private static ManufacturerList manufacturers = new ManufacturerList(); - - static { - - // AeroTech has many name combinations... - List names = new ArrayList(); - for (String s : new String[] { "A", "AT", "AERO", "AEROT", "AEROTECH" }) { - names.add(s); - names.add(s + "-RMS"); - names.add(s + "-RCS"); - names.add("RCS-" + s); - names.add(s + "-APOGEE"); - } - names.add("ISP"); - - // Aerotech has single-use, reload and hybrid motors - manufacturers.add(new Manufacturer("AeroTech", "AeroTech", Motor.Type.UNKNOWN, - names.toArray(new String[0]))); - - manufacturers.add(new Manufacturer("Alpha Hybrid Rocketry LLC", "Alpha Hybrid Rocketry", Motor.Type.HYBRID, - "AHR", "ALPHA", "ALPHA HYBRID", "ALPHA HYBRIDS", "ALPHA HYBRIDS ROCKETRY")); - - // TODO: HIGH: AMW/ProX - how to classify? - - manufacturers.add(new Manufacturer("Animal Motor Works", "Animal Motor Works", Motor.Type.RELOAD, - "AMW", "AW", "ANIMAL")); - - manufacturers.add(new Manufacturer("Apogee", "Apogee", Motor.Type.SINGLE, - "AP", "APOG", "P")); - - manufacturers.add(new Manufacturer("Cesaroni Technology Inc.", "Cesaroni Technology", Motor.Type.RELOAD, - "CES", "CESARONI", "CESARONI TECHNOLOGY INCORPORATED", "CTI", - "CS", "CSR", "PRO38", "ABC")); - - manufacturers.add(new Manufacturer("Contrail Rockets", "Contrail Rockets", Motor.Type.HYBRID, - "CR", "CONTR", "CONTRAIL", "CONTRAIL ROCKET")); - - manufacturers.add(new Manufacturer("Estes", "Estes", Motor.Type.SINGLE, - "E", "ES")); - - // Ellis Mountain has both single-use and reload motors - manufacturers.add(new Manufacturer("Ellis Mountain", "Ellis Mountain", Motor.Type.UNKNOWN, - "EM", "ELLIS", "ELLIS MOUNTAIN ROCKET", "ELLIS MOUNTAIN ROCKETS")); - - manufacturers.add(new Manufacturer("Gorilla Rocket Motors", "Gorilla Rocket Motors", Motor.Type.RELOAD, - "GR", "GORILLA", "GORILLA ROCKET", "GORILLA ROCKETS", "GORILLA MOTOR", - "GORILLA MOTORS", "GORILLA ROCKET MOTOR")); - - manufacturers.add(new Manufacturer("HyperTEK", "HyperTEK", Motor.Type.HYBRID, - "H", "HT", "HYPER")); - - manufacturers.add(new Manufacturer("Kosdon by AeroTech", "Kosdon by AeroTech", Motor.Type.RELOAD, - "K", "KBA", "K-AT", "KOS", "KOSDON", "KOSDON/AT", "KOSDON/AEROTECH")); - - manufacturers.add(new Manufacturer("Loki Research", "Loki Research", Motor.Type.RELOAD, - "LOKI", "LR")); - - manufacturers.add(new Manufacturer("Public Missiles, Ltd.", "Public Missiles", Motor.Type.SINGLE, - "PM", "PML", "PUBLIC MISSILES LIMITED")); - - manufacturers.add(new Manufacturer("Propulsion Polymers", "Propulsion Polymers", Motor.Type.HYBRID, - "PP", "PROP", "PROPULSION")); - - manufacturers.add(new Manufacturer("Quest", "Quest", Motor.Type.SINGLE, - "Q", "QU")); - - manufacturers.add(new Manufacturer("RATT Works", "RATT Works", Motor.Type.HYBRID, - "RATT", "RT", "RTW")); - - manufacturers.add(new Manufacturer("Roadrunner Rocketry", "Roadrunner Rocketry", Motor.Type.SINGLE, - "RR", "ROADRUNNER")); - - manufacturers.add(new Manufacturer("Rocketvision", "Rocketvision", Motor.Type.SINGLE, - "RV", "ROCKET VISION")); - - manufacturers.add(new Manufacturer("Sky Ripper Systems", "Sky Ripper Systems", Motor.Type.HYBRID, - "SR", "SRS", "SKYR", "SKYRIPPER", "SKY RIPPER", "SKYRIPPER SYSTEMS")); - - manufacturers.add(new Manufacturer("West Coast Hybrids", "West Coast Hybrids", Motor.Type.HYBRID, - "WCH", "WCR", "WEST COAST", "WEST COAST HYBRID")); - - // German WECO Feuerwerk, previously Sachsen Feuerwerk - manufacturers.add(new Manufacturer("WECO Feuerwerk", "WECO Feuerwerk", Motor.Type.SINGLE, - "WECO", "WECO FEUERWERKS", "SF", "SACHSEN", "SACHSEN FEUERWERK", - "SACHSEN FEUERWERKS")); - - } - - - - private final String displayName; - private final String simpleName; - private final Set allNames; - private final Set searchNames; - private final Motor.Type motorType; - - - private Manufacturer(String displayName, String simpleName, Motor.Type motorType, String... alternateNames) { - this.displayName = displayName; - this.simpleName = simpleName; - this.motorType = motorType; - if (motorType == null) { - throw new IllegalArgumentException("motorType cannot be null"); - } - - Set all = new HashSet(); - Set search = new HashSet(); - - all.add(displayName); - all.add(simpleName); - search.add(generateSearchString(displayName)); - search.add(generateSearchString(simpleName)); - - for (String name : alternateNames) { - all.add(name); - search.add(generateSearchString(name)); - } - - this.allNames = Collections.unmodifiableSet(all); - this.searchNames = Collections.unmodifiableSet(search); - } - - - /** - * Returns the display name of the manufacturer. This is the value that - * should be presented in the UI to the user. - * - * @return the display name - */ - public String getDisplayName() { - return displayName; - } - - - /** - * Returns the simple name of the manufacturer. This should be used for example - * when saving the manufacturer for compatibility. - * - * @return the simple name. - */ - public String getSimpleName() { - return simpleName; - } - - - /** - * Return all names of the manufacturer. This includes all kinds of - * codes that correspond to the manufacturer (for example "A" for AeroTech). - * - * @return an unmodifiable set of the alternative names. - */ - public Set getAllNames() { - return allNames; - } - - Set getSearchNames() { - return searchNames; - } - - /** - * Return the motor type that this manufacturer produces if it produces only one motor type. - * If the manufacturer manufactures multiple motor types or the type is unknown, - * type UNKNOWN is returned. - * - * @return the manufactured motor type, or UNKNOWN. - */ - public Motor.Type getMotorType() { - return motorType; - } - - - /** - * Check whether the display, simple or any of the alternative names matches the - * specified name. Matching is performed case insensitively and ignoring any - * non-letter and non-number characters. - * - * @param name the name to search for. - * @return whether this manufacturer matches the request. - */ - public boolean matches(String name) { - if (name == null) - return false; - return this.searchNames.contains(generateSearchString(name)); - } - - - /** - * Return the display name of the manufacturer. - */ - @Override - public String toString() { - return displayName; - } - - - /** - * Returns a manufacturer for the given name. The manufacturer is searched for - * within the manufacturers and if a match is found the corresponding - * object is returned. If not, a new manufacturer is returned with display and - * simple name the name specified. Subsequent requests for the same (or corresponding) - * manufacturer name will return the same object. - * - * @param name the manufacturer name to search for. - * @return the Manufacturer object corresponding the name. - */ - public static Manufacturer getManufacturer(String name) { - String searchString = generateSearchString(name); - Manufacturer m = manufacturers.get(searchString); - if ( m != null ) { - return m; - } - - m = new Manufacturer(name.trim(), name.trim(), Motor.Type.UNKNOWN); - - // We need some additional external synchronization here so we lock on the manufacturers. - synchronized( manufacturers ) { - Manufacturer retest = manufacturers.get(searchString); - if ( retest != null ) { - // it exists now. - return retest; - } - manufacturers.add(m); - } - return m; - } - - private static String generateSearchString(String str) { - return str.toLowerCase(Locale.getDefault()).replaceAll("[^a-zA-Z0-9]+", " ").trim(); - } - -} diff --git a/core/src/net/sf/openrocket/motor/Motor.java b/core/src/net/sf/openrocket/motor/Motor.java deleted file mode 100644 index 744a6154..00000000 --- a/core/src/net/sf/openrocket/motor/Motor.java +++ /dev/null @@ -1,147 +0,0 @@ -package net.sf.openrocket.motor; - -import net.sf.openrocket.util.Coordinate; - -public interface Motor { - - /** - * Enum of rocket motor types. - * - * @author Sampo Niskanen - */ - public enum Type { - SINGLE("Single-use", "Single-use solid propellant motor"), - RELOAD("Reloadable", "Reloadable solid propellant motor"), - HYBRID("Hybrid", "Hybrid rocket motor engine"), - UNKNOWN("Unknown", "Unknown motor type"); - - private final String name; - private final String description; - - Type(String name, String description) { - this.name = name; - this.description = description; - } - - - /** - * Return a short name of this motor type. - * @return a short name of the motor type. - */ - public String getName() { - return name; - } - - /** - * Return a long description of this motor type. - * @return a description of the motor type. - */ - public String getDescription() { - return description; - } - - @Override - public String toString() { - return name; - } - } - - - /** - * Ejection charge delay value signifying a "plugged" motor with no ejection charge. - * The value is that of Double.POSITIVE_INFINITY. - */ - public static final double PLUGGED = Double.POSITIVE_INFINITY; - - - /** - * Below what portion of maximum thrust is the motor chosen to be off when - * calculating average thrust and burn time. NFPA 1125 defines the "official" - * burn time to be the time which the motor produces over 5% of its maximum thrust. - */ - public static final double MARGINAL_THRUST = 0.05; - - - - /** - * Return the motor type. - * - * @return the motorType - */ - public Type getMotorType(); - - - /** - * Return the designation of the motor. - * - * @return the designation - */ - public String getDesignation(); - - /** - * Return the designation of the motor, including a delay. - * - * @param delay the delay of the motor. - * @return designation with delay. - */ - public String getDesignation(double delay); - - - /** - * Return extra description for the motor. This may include for example - * comments on the source of the thrust curve. The returned String - * may include new-lines. - * - * @return the description - */ - public String getDescription(); - - - /** - * Return the maximum diameter of the motor. - * - * @return the diameter - */ - public double getDiameter(); - - /** - * Return the length of the motor. This should be a "characteristic" length, - * and the exact definition may depend on the motor type. Typically this should - * be the length from the bottom of the motor to the end of the maximum diameter - * portion, ignoring any smaller ejection charge compartments. - * - * @return the length - */ - public double getLength(); - - public String getDigest(); - - public MotorInstance getInstance(); - - - public Coordinate getLaunchCG(); - - public Coordinate getEmptyCG(); - - - /** - * Return an estimate of the burn time of this motor, or NaN if an estimate is unavailable. - */ - public double getBurnTimeEstimate(); - - /** - * Return an estimate of the average thrust of this motor, or NaN if an estimate is unavailable. - */ - public double getAverageThrustEstimate(); - - /** - * Return an estimate of the maximum thrust of this motor, or NaN if an estimate is unavailable. - */ - public double getMaxThrustEstimate(); - - /** - * Return an estimate of the total impulse of this motor, or NaN if an estimate is unavailable. - */ - public double getTotalImpulseEstimate(); - -} diff --git a/core/src/net/sf/openrocket/motor/MotorDigest.java b/core/src/net/sf/openrocket/motor/MotorDigest.java deleted file mode 100644 index 92f01d3c..00000000 --- a/core/src/net/sf/openrocket/motor/MotorDigest.java +++ /dev/null @@ -1,180 +0,0 @@ -package net.sf.openrocket.motor; - -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.TextUtil; - -/** - * A class that generated a "digest" of a motor. A digest is a string value that - * uniquely identifies a motor (like a hash code or checksum). Two motors that have - * the same digest behave similarly with a very high probability. The digest can - * therefore be used to identify motors that otherwise have the same specifications. - *

- * The digest only uses a limited amount of precision, so that rounding errors won't - * cause differing digest results. - * - * @author Sampo Niskanen - */ -public class MotorDigest { - - private static final double EPSILON = 0.00000000001; - - public enum DataType { - /** An array of time points at which data is available (in ms) */ - TIME_ARRAY(0, 1000), - /** Mass data for a few specific points (normally initial and empty mass) (in 0.1g) */ - MASS_SPECIFIC(1, 10000), - /** Mass per time (in 0.1g) */ - MASS_PER_TIME(2, 10000), - /** CG position for a few specific points (normally initial and final CG) (in mm) */ - CG_SPECIFIC(3, 1000), - /** CG position per time (in mm) */ - CG_PER_TIME(4, 1000), - /** Thrust force per time (in mN) */ - FORCE_PER_TIME(5, 1000); - - private final int order; - private final int multiplier; - - DataType(int order, int multiplier) { - this.order = order; - this.multiplier = multiplier; - } - - public int getOrder() { - return order; - } - - public int getMultiplier() { - return multiplier; - } - } - - - private final MessageDigest digest; - private boolean used = false; - private int lastOrder = -1; - - - public MotorDigest() { - try { - digest = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("MD5 digest not supported by JRE", e); - } - } - - - - public void update(DataType type, double... values) { - int multiplier = type.getMultiplier(); - - int[] intValues = new int[values.length]; - for (int i = 0; i < values.length; i++) { - double v = values[i]; - v = next(v); - v *= multiplier; - v = next(v); - intValues[i] = (int) Math.round(v); - } - update(type, intValues); - } - - - private void update(DataType type, int... values) { - - // Check for correct order - if (lastOrder >= type.getOrder()) { - throw new IllegalArgumentException("Called with type=" + type + " order=" + type.getOrder() + - " while lastOrder=" + lastOrder); - } - lastOrder = type.getOrder(); - - // Digest the type - digest.update(bytes(type.getOrder())); - - // Digest the data length - digest.update(bytes(values.length)); - - // Digest the values - for (int v : values) { - digest.update(bytes(v)); - } - - } - - - private static double next(double v) { - return v + Math.signum(v) * EPSILON; - } - - - public String getDigest() { - if (used) { - throw new IllegalStateException("MotorDigest already used"); - } - used = true; - byte[] result = digest.digest(); - return TextUtil.hexString(result); - } - - - - private byte[] bytes(int value) { - return new byte[] { - (byte) ((value >>> 24) & 0xFF), (byte) ((value >>> 16) & 0xFF), - (byte) ((value >>> 8) & 0xFF), (byte) (value & 0xFF) }; - } - - - /** - * Digest the contents of a thrust curve motor. The result is a string uniquely - * defining the functional aspects of the motor. - * - * @param m the motor to digest - * @return the digest - */ - public static String digestMotor(ThrustCurveMotor m) { - - // Create the motor digest from data available in RASP files - MotorDigest motorDigest = new MotorDigest(); - motorDigest.update(DataType.TIME_ARRAY, m.getTimePoints()); - - Coordinate[] cg = m.getCGPoints(); - double[] cgx = new double[cg.length]; - double[] mass = new double[cg.length]; - for (int i = 0; i < cg.length; i++) { - cgx[i] = cg[i].x; - mass[i] = cg[i].weight; - } - - motorDigest.update(DataType.MASS_PER_TIME, mass); - motorDigest.update(DataType.CG_PER_TIME, cgx); - motorDigest.update(DataType.FORCE_PER_TIME, m.getThrustPoints()); - return motorDigest.getDigest(); - - } - - public static String digestComment(String comment) { - comment = comment.replaceAll("\\s+", " ").trim(); - - MessageDigest digest; - try { - digest = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("MD5 digest not supported by JRE", e); - } - - try { - digest.update(comment.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 encoding not supported by JRE", e); - } - - return TextUtil.hexString(digest.digest()); - } - -} diff --git a/core/src/net/sf/openrocket/motor/MotorId.java b/core/src/net/sf/openrocket/motor/MotorId.java deleted file mode 100644 index 126fff1c..00000000 --- a/core/src/net/sf/openrocket/motor/MotorId.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.sf.openrocket.motor; - -/** - * An immutable identifier for a motor instance in a MotorInstanceConfiguration. - * The motor is identified by the ID of its mounting component and a - * positive motor count number. - * - * @author Sampo Niskanen - */ -public final class MotorId { - - private final String componentId; - private final int number; - - - /** - * Sole constructor. - * - * @param componentId the component ID, must not be null - * @param number a positive motor doun5 number - */ - public MotorId(String componentId, int number) { - super(); - - if (componentId == null) { - throw new IllegalArgumentException("Component ID was null"); - } - if (number <= 0) { - throw new IllegalArgumentException("Number must be positive, n=" + number); - } - - // Use intern so comparison can be done using == instead of equals() - this.componentId = componentId.intern(); - this.number = number; - } - - - public String getComponentId() { - return componentId; - } - - public int getNumber() { - return number; - } - - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - - if (!(o instanceof MotorId)) - return false; - - MotorId other = (MotorId)o; - // Comparison with == ok since string is intern()'ed - return this.componentId == other.componentId && this.number == other.number; - } - - - @Override - public int hashCode() { - return componentId.hashCode() + (number << 12); - } - - // TODO: toString() -} diff --git a/core/src/net/sf/openrocket/motor/MotorInstance.java b/core/src/net/sf/openrocket/motor/MotorInstance.java deleted file mode 100644 index ab474a8e..00000000 --- a/core/src/net/sf/openrocket/motor/MotorInstance.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.sf.openrocket.motor; - -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Monitorable; - -public interface MotorInstance extends Cloneable, Monitorable { - - /** - * Step the motor instance forward in time. - * - * @param time the time to step to, from motor ignition. - * @param acceleration the average acceleration during the step. - * @param cond the average atmospheric conditions during the step. - */ - public void step(double time, double acceleration, AtmosphericConditions cond); - - - /** - * Return the time to which this motor has been stepped. - * @return the current step time. - */ - public double getTime(); - - /** - * Return the average thrust during the last step. - */ - public double getThrust(); - - /** - * Return the average CG location during the last step. - */ - public Coordinate getCG(); - - /** - * Return the average longitudinal moment of inertia during the last step. - * This is the actual inertia, not the unit inertia! - */ - public double getLongitudinalInertia(); - - /** - * Return the average rotational moment of inertia during the last step. - * This is the actual inertia, not the unit inertia! - */ - public double getRotationalInertia(); - - /** - * Return whether this motor still produces thrust. If this method returns false - * the motor has burnt out, and will not produce any significant thrust anymore. - */ - public boolean isActive(); - - - /** - * Create a new instance of this motor instance. The state of the motor is - * identical to this instance and can be used independently from this one. - */ - public MotorInstance clone(); - - - public Motor getParentMotor(); - -} diff --git a/core/src/net/sf/openrocket/motor/MotorInstanceConfiguration.java b/core/src/net/sf/openrocket/motor/MotorInstanceConfiguration.java deleted file mode 100644 index a3142028..00000000 --- a/core/src/net/sf/openrocket/motor/MotorInstanceConfiguration.java +++ /dev/null @@ -1,141 +0,0 @@ -package net.sf.openrocket.motor; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Monitorable; - -/** - * A configuration of motor instances identified by a string id. Each motor instance has - * an individual position, ingition time etc. - * - * @author Sampo Niskanen - */ -public final class MotorInstanceConfiguration implements Monitorable, Cloneable { - - private final List ids = new ArrayList(); - private final List unmodifiableIds = Collections.unmodifiableList(ids); - private final List motors = new ArrayList(); - private final List mounts = new ArrayList(); - private final List positions = new ArrayList(); - private final List ignitionTimes = new ArrayList(); - - - private int modID = 0; - - - /** - * Add a motor instance to this configuration. The motor is placed at - * the specified position and with an infinite ignition time (never ignited). - * - * @param id the ID of this motor instance. - * @param motor the motor instance. - * @param mount the motor mount containing this motor - * @param position the position of the motor in absolute coordinates. - * @throws IllegalArgumentException if a motor with the specified ID already exists. - */ - public void addMotor(MotorId id, MotorInstance motor, MotorMount mount, Coordinate position) { - if (this.ids.contains(id)) { - throw new IllegalArgumentException("MotorInstanceConfiguration already " + - "contains a motor with id " + id); - } - this.ids.add(id); - this.motors.add(motor); - this.mounts.add(mount); - this.positions.add(position); - this.ignitionTimes.add(Double.POSITIVE_INFINITY); - modID++; - } - - /** - * Return a list of all motor IDs in this configuration (not only ones in active stages). - */ - public List getMotorIDs() { - return unmodifiableIds; - } - - public MotorInstance getMotorInstance(MotorId id) { - return motors.get(indexOf(id)); - } - - public MotorMount getMotorMount(MotorId id) { - return mounts.get(indexOf(id)); - } - - public Coordinate getMotorPosition(MotorId id) { - return positions.get(indexOf(id)); - } - - public void setMotorPosition(MotorId id, Coordinate position) { - positions.set(indexOf(id), position); - modID++; - } - - public double getMotorIgnitionTime(MotorId id) { - return ignitionTimes.get(indexOf(id)); - } - - public void setMotorIgnitionTime(MotorId id, double time) { - this.ignitionTimes.set(indexOf(id), time); - modID++; - } - - - - private int indexOf(MotorId id) { - int index = ids.indexOf(id); - if (index < 0) { - throw new IllegalArgumentException("MotorInstanceConfiguration does not " + - "contain a motor with id " + id); - } - return index; - } - - - - /** - * Step all of the motor instances to the specified time minus their ignition time. - * @param time the "global" time - */ - public void step(double time, double acceleration, AtmosphericConditions cond) { - for (int i = 0; i < motors.size(); i++) { - double t = time - ignitionTimes.get(i); - if (t >= 0) { - motors.get(i).step(t, acceleration, cond); - } - } - modID++; - } - - @Override - public int getModID() { - int id = modID; - for (MotorInstance motor : motors) { - id += motor.getModID(); - } - return id; - } - - /** - * Return a copy of this motor instance configuration with independent motor instances - * from this instance. - */ - @Override - public MotorInstanceConfiguration clone() { - MotorInstanceConfiguration clone = new MotorInstanceConfiguration(); - clone.ids.addAll(this.ids); - clone.mounts.addAll(this.mounts); - clone.positions.addAll(this.positions); - clone.ignitionTimes.addAll(this.ignitionTimes); - for (MotorInstance motor : this.motors) { - clone.motors.add(motor.clone()); - } - clone.modID = this.modID; - return clone; - } - -} diff --git a/core/src/net/sf/openrocket/motor/ThrustCurveMotor.java b/core/src/net/sf/openrocket/motor/ThrustCurveMotor.java deleted file mode 100644 index e795c823..00000000 --- a/core/src/net/sf/openrocket/motor/ThrustCurveMotor.java +++ /dev/null @@ -1,600 +0,0 @@ -package net.sf.openrocket.motor; - -import java.text.Collator; -import java.util.Arrays; -import java.util.Locale; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayUtils; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Inertia; -import net.sf.openrocket.util.MathUtil; - - -public class ThrustCurveMotor implements Motor, Comparable { - private static final LogHelper log = Application.getLogger(); - - public static final double MAX_THRUST = 10e6; - - // Comparators: - private static final Collator COLLATOR = Collator.getInstance(Locale.US); - static { - COLLATOR.setStrength(Collator.PRIMARY); - } - private static final DesignationComparator DESIGNATION_COMPARATOR = new DesignationComparator(); - - private final String digest; - - private final Manufacturer manufacturer; - private final String designation; - private final String description; - private final Motor.Type type; - private final double[] delays; - private final double diameter; - private final double length; - private final double[] time; - private final double[] thrust; - private final Coordinate[] cg; - - private double maxThrust; - private double burnTime; - private double averageThrust; - private double totalImpulse; - - /** - * Deep copy constructor. - * Constructs a new ThrustCurveMotor from an existing ThrustCurveMotor. - * @param m - */ - protected ThrustCurveMotor( ThrustCurveMotor m ) { - this.digest = m.digest; - this.manufacturer = m.manufacturer; - this.designation = m.designation; - this.description = m.description; - this.type = m.type; - this.delays = ArrayUtils.copyOf(m.delays, m.delays.length); - this.diameter = m.diameter; - this.length = m.length; - this.time = ArrayUtils.copyOf(m.time, m.time.length); - this.thrust = ArrayUtils.copyOf(m.thrust, m.thrust.length); - this.cg = new Coordinate[ m.cg.length ]; - for( int i = 0; i< cg.length; i++ ) { - this.cg[i] = m.cg[i].clone(); - } - this.maxThrust = m.maxThrust; - this.burnTime = m.burnTime; - this.averageThrust = m.averageThrust; - this.totalImpulse = m.totalImpulse; - } - - /** - * Sole constructor. Sets all the properties of the motor. - * - * @param manufacturer the manufacturer of the motor. - * @param designation the designation of the motor. - * @param description extra description of the motor. - * @param type the motor type - * @param delays the delays defined for this thrust curve - * @param diameter diameter of the motor. - * @param length length of the motor. - * @param time the time points for the thrust curve. - * @param thrust thrust at the time points. - * @param cg cg at the time points. - */ - public ThrustCurveMotor(Manufacturer manufacturer, String designation, String description, - Motor.Type type, double[] delays, double diameter, double length, - double[] time, double[] thrust, Coordinate[] cg, String digest) { - this.digest = digest; - // Check argument validity - if ((time.length != thrust.length) || (time.length != cg.length)) { - throw new IllegalArgumentException("Array lengths do not match, " + - "time:" + time.length + " thrust:" + thrust.length + - " cg:" + cg.length); - } - if (time.length < 2) { - throw new IllegalArgumentException("Too short thrust-curve, length=" + - time.length); - } - for (int i = 0; i < time.length - 1; i++) { - if (time[i + 1] < time[i]) { - throw new IllegalArgumentException("Time goes backwards, " + - "time[" + i + "]=" + time[i] + " " + - "time[" + (i + 1) + "]=" + time[i + 1]); - } - } - if (!MathUtil.equals(time[0], 0)) { - throw new IllegalArgumentException("Curve starts at time " + time[0]); - } - if (!MathUtil.equals(thrust[0], 0)) { - throw new IllegalArgumentException("Curve starts at thrust " + thrust[0]); - } - if (!MathUtil.equals(thrust[thrust.length - 1], 0)) { - throw new IllegalArgumentException("Curve ends at thrust " + - thrust[thrust.length - 1]); - } - for (double t : thrust) { - if (t < 0) { - throw new IllegalArgumentException("Negative thrust."); - } - if (t > MAX_THRUST || Double.isNaN(t)) { - throw new IllegalArgumentException("Invalid thrust " + t); - } - } - for (Coordinate c : cg) { - if (c.isNaN()) { - throw new IllegalArgumentException("Invalid CG " + c); - } - if (c.x < 0 || c.x > length) { - throw new IllegalArgumentException("Invalid CG position " + c.x); - } - if (c.weight < 0) { - throw new IllegalArgumentException("Negative mass " + c.weight); - } - } - - if (type != Motor.Type.SINGLE && type != Motor.Type.RELOAD && - type != Motor.Type.HYBRID && type != Motor.Type.UNKNOWN) { - throw new IllegalArgumentException("Illegal motor type=" + type); - } - - - this.manufacturer = manufacturer; - this.designation = designation; - this.description = description; - this.type = type; - this.delays = delays.clone(); - this.diameter = diameter; - this.length = length; - this.time = time.clone(); - this.thrust = thrust.clone(); - this.cg = cg.clone(); - - computeStatistics(); - } - - - - /** - * Get the manufacturer of this motor. - * - * @return the manufacturer - */ - public Manufacturer getManufacturer() { - return manufacturer; - } - - - /** - * Return the array of time points for this thrust curve. - * @return an array of time points where the thrust is sampled - */ - public double[] getTimePoints() { - return time.clone(); - } - - /** - * Returns the array of thrust points for this thrust curve. - * @return an array of thrust samples - */ - public double[] getThrustPoints() { - return thrust.clone(); - } - - /** - * Returns the array of CG points for this thrust curve. - * @return an array of CG samples - */ - public Coordinate[] getCGPoints() { - return cg.clone(); - } - - /** - * Return a list of standard delays defined for this motor. - * @return a list of standard delays - */ - public double[] getStandardDelays() { - return delays.clone(); - } - - - /** - * {@inheritDoc} - *

- * NOTE: In most cases you want to examine the motor type of the ThrustCurveMotorSet, - * not the ThrustCurveMotor itself. - */ - @Override - public Type getMotorType() { - return type; - } - - - @Override - public String getDesignation() { - return designation; - } - - @Override - public String getDesignation(double delay) { - return designation + "-" + getDelayString(delay); - } - - - @Override - public String getDescription() { - return description; - } - - @Override - public double getDiameter() { - return diameter; - } - - @Override - public double getLength() { - return length; - } - - - @Override - public MotorInstance getInstance() { - return new ThrustCurveMotorInstance(); - } - - - @Override - public Coordinate getLaunchCG() { - return cg[0]; - } - - @Override - public Coordinate getEmptyCG() { - return cg[cg.length - 1]; - } - - - - - @Override - public double getBurnTimeEstimate() { - return burnTime; - } - - @Override - public double getAverageThrustEstimate() { - return averageThrust; - } - - @Override - public double getMaxThrustEstimate() { - return maxThrust; - } - - @Override - public double getTotalImpulseEstimate() { - return totalImpulse; - } - - @Override - public String getDigest() { - return digest; - } - - - /** - * Compute the general statistics of this motor. - */ - private void computeStatistics() { - - // Maximum thrust - maxThrust = 0; - for (double t : thrust) { - if (t > maxThrust) - maxThrust = t; - } - - - // Burn start time - double thrustLimit = maxThrust * MARGINAL_THRUST; - double burnStart, burnEnd; - - int pos; - for (pos = 1; pos < thrust.length; pos++) { - if (thrust[pos] >= thrustLimit) - break; - } - if (pos >= thrust.length) { - throw new BugException("Could not compute burn start time, maxThrust=" + maxThrust + - " limit=" + thrustLimit + " thrust=" + Arrays.toString(thrust)); - } - if (MathUtil.equals(thrust[pos - 1], thrust[pos])) { - // For safety - burnStart = (time[pos - 1] + time[pos]) / 2; - } else { - burnStart = MathUtil.map(thrustLimit, thrust[pos - 1], thrust[pos], time[pos - 1], time[pos]); - } - - - // Burn end time - for (pos = thrust.length - 2; pos >= 0; pos--) { - if (thrust[pos] >= thrustLimit) - break; - } - if (pos < 0) { - throw new BugException("Could not compute burn end time, maxThrust=" + maxThrust + - " limit=" + thrustLimit + " thrust=" + Arrays.toString(thrust)); - } - if (MathUtil.equals(thrust[pos], thrust[pos + 1])) { - // For safety - burnEnd = (time[pos] + time[pos + 1]) / 2; - } else { - burnEnd = MathUtil.map(thrustLimit, thrust[pos], thrust[pos + 1], - time[pos], time[pos + 1]); - } - - - // Burn time - burnTime = Math.max(burnEnd - burnStart, 0); - - - // Total impulse and average thrust - totalImpulse = 0; - averageThrust = 0; - - for (pos = 0; pos < time.length - 1; pos++) { - double t0 = time[pos]; - double t1 = time[pos + 1]; - double f0 = thrust[pos]; - double f1 = thrust[pos + 1]; - - totalImpulse += (t1 - t0) * (f0 + f1) / 2; - - if (t0 < burnStart && t1 > burnStart) { - double fStart = MathUtil.map(burnStart, t0, t1, f0, f1); - averageThrust += (fStart + f1) / 2 * (t1 - burnStart); - } else if (t0 >= burnStart && t1 <= burnEnd) { - averageThrust += (f0 + f1) / 2 * (t1 - t0); - } else if (t0 < burnEnd && t1 > burnEnd) { - double fEnd = MathUtil.map(burnEnd, t0, t1, f0, f1); - averageThrust += (f0 + fEnd) / 2 * (burnEnd - t0); - } - } - - if (burnTime > 0) { - averageThrust /= burnTime; - } else { - averageThrust = 0; - } - - } - - - ////////// Static methods - - /** - * Return a String representation of a delay time. If the delay is {@link #PLUGGED}, - * returns "P". - * - * @param delay the delay time. - * @return the String representation. - */ - public static String getDelayString(double delay) { - return getDelayString(delay, "P"); - } - - /** - * Return a String representation of a delay time. If the delay is {@link #PLUGGED}, - * plugged is returned. - * - * @param delay the delay time. - * @param plugged the return value if there is no ejection charge. - * @return the String representation. - */ - public static String getDelayString(double delay, String plugged) { - if (delay == PLUGGED) - return plugged; - delay = Math.rint(delay * 10) / 10; - if (MathUtil.equals(delay, Math.rint(delay))) - return "" + ((int) delay); - return "" + delay; - } - - - - //////// Motor instance implementation //////// - private class ThrustCurveMotorInstance implements MotorInstance { - - private int position; - - // Previous time step value - private double prevTime; - - // Average thrust during previous step - private double stepThrust; - // Instantaneous thrust at current time point - private double instThrust; - - // Average CG during previous step - private Coordinate stepCG; - // Instantaneous CG at current time point - private Coordinate instCG; - - private final double unitRotationalInertia; - private final double unitLongitudinalInertia; - private final Motor parentMotor; - - private int modID = 0; - - public ThrustCurveMotorInstance() { - log.debug("ThrustCurveMotor: Creating motor instance of " + ThrustCurveMotor.this); - position = 0; - prevTime = 0; - instThrust = 0; - stepThrust = 0; - instCG = cg[0]; - stepCG = cg[0]; - unitRotationalInertia = Inertia.filledCylinderRotational(getDiameter() / 2); - unitLongitudinalInertia = Inertia.filledCylinderLongitudinal(getDiameter() / 2, getLength()); - parentMotor = ThrustCurveMotor.this; - } - - @Override - public Motor getParentMotor(){ - return parentMotor; - } - - @Override - public double getTime() { - return prevTime; - } - - @Override - public Coordinate getCG() { - return stepCG; - } - - @Override - public double getLongitudinalInertia() { - return unitLongitudinalInertia * stepCG.weight; - } - - @Override - public double getRotationalInertia() { - return unitRotationalInertia * stepCG.weight; - } - - @Override - public double getThrust() { - return stepThrust; - } - - @Override - public boolean isActive() { - return prevTime < time[time.length - 1]; - } - - @Override - public void step(double nextTime, double acceleration, AtmosphericConditions cond) { - - if (!(nextTime >= prevTime)) { - // Also catches NaN - throw new IllegalArgumentException("Stepping backwards in time, current=" + - prevTime + " new=" + nextTime); - } - if (MathUtil.equals(prevTime, nextTime)) { - return; - } - - modID++; - - if (position >= time.length - 1) { - // Thrust has ended - prevTime = nextTime; - stepThrust = 0; - instThrust = 0; - stepCG = cg[cg.length - 1]; - return; - } - - - // Compute average & instantaneous thrust - if (nextTime < time[position + 1]) { - - // Time step between time points - double nextF = MathUtil.map(nextTime, time[position], time[position + 1], - thrust[position], thrust[position + 1]); - stepThrust = (instThrust + nextF) / 2; - instThrust = nextF; - - } else { - - // Portion of previous step - stepThrust = (instThrust + thrust[position + 1]) / 2 * (time[position + 1] - prevTime); - - // Whole steps - position++; - while ((position < time.length - 1) && (nextTime >= time[position + 1])) { - stepThrust += (thrust[position] + thrust[position + 1]) / 2 * - (time[position + 1] - time[position]); - position++; - } - - // End step - if (position < time.length - 1) { - instThrust = MathUtil.map(nextTime, time[position], time[position + 1], - thrust[position], thrust[position + 1]); - stepThrust += (thrust[position] + instThrust) / 2 * - (nextTime - time[position]); - } else { - // Thrust ended during this step - instThrust = 0; - } - - stepThrust /= (nextTime - prevTime); - - } - - // Compute average and instantaneous CG (simple average between points) - Coordinate nextCG; - if (position < time.length - 1) { - nextCG = MathUtil.map(nextTime, time[position], time[position + 1], - cg[position], cg[position + 1]); - } else { - nextCG = cg[cg.length - 1]; - } - stepCG = instCG.add(nextCG).multiply(0.5); - instCG = nextCG; - - // Update time - prevTime = nextTime; - } - - @Override - public MotorInstance clone() { - try { - return (MotorInstance) super.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException", e); - } - } - - @Override - public int getModID() { - return modID; - } - } - - - - @Override - public int compareTo(ThrustCurveMotor other) { - - int value; - - // 1. Manufacturer - value = COLLATOR.compare(this.manufacturer.getDisplayName(), - ((ThrustCurveMotor) other).manufacturer.getDisplayName()); - if (value != 0) - return value; - - // 2. Designation - value = DESIGNATION_COMPARATOR.compare(this.getDesignation(), other.getDesignation()); - if (value != 0) - return value; - - // 3. Diameter - value = (int) ((this.getDiameter() - other.getDiameter()) * 1000000); - if (value != 0) - return value; - - // 4. Length - value = (int) ((this.getLength() - other.getLength()) * 1000000); - return value; - - } - - -} diff --git a/core/src/net/sf/openrocket/motor/ThrustCurveMotorPlaceholder.java b/core/src/net/sf/openrocket/motor/ThrustCurveMotorPlaceholder.java deleted file mode 100644 index db6b112b..00000000 --- a/core/src/net/sf/openrocket/motor/ThrustCurveMotorPlaceholder.java +++ /dev/null @@ -1,186 +0,0 @@ -package net.sf.openrocket.motor; - -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; - -public class ThrustCurveMotorPlaceholder implements Motor { - - private final Motor.Type type; - private final String manufacturer; - private final String designation; - private final double diameter; - private final double length; - private final String digest; - private final double delay; - private final double launchMass; - private final double emptyMass; - - - public ThrustCurveMotorPlaceholder(Type type, String manufacturer, String designation, double diameter, double length, - String digest, double delay, double launchMass, double emptyMass) { - this.type = type; - this.manufacturer = manufacturer; - this.designation = designation; - this.diameter = diameter; - this.length = length; - this.digest = digest; - this.delay = delay; - this.launchMass = launchMass; - this.emptyMass = emptyMass; - } - - - @Override - public Type getMotorType() { - return type; - } - - public String getManufacturer() { - return manufacturer; - } - - @Override - public String getDesignation() { - return designation; - } - - @Override - public String getDesignation(double designationDelay) { - return designation + "-" + ThrustCurveMotor.getDelayString(designationDelay); - } - - @Override - public String getDescription() { - return ""; - } - - @Override - public double getDiameter() { - return diameter; - } - - @Override - public double getLength() { - return length; - } - - @Override - public String getDigest() { - return digest; - } - - public double getDelay() { - return delay; - } - - @Override - public MotorInstance getInstance() { - throw new BugException("Called getInstance on PlaceholderMotor"); - } - - @Override - public Coordinate getLaunchCG() { - return new Coordinate(length / 2, 0, 0, launchMass); - } - - @Override - public Coordinate getEmptyCG() { - return new Coordinate(length / 2, 0, 0, emptyMass); - } - - @Override - public double getBurnTimeEstimate() { - return Double.NaN; - } - - @Override - public double getAverageThrustEstimate() { - return Double.NaN; - } - - @Override - public double getMaxThrustEstimate() { - return Double.NaN; - } - - @Override - public double getTotalImpulseEstimate() { - return Double.NaN; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits(delay); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result - + ((designation == null) ? 0 : designation.hashCode()); - temp = Double.doubleToLongBits(diameter); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result + ((digest == null) ? 0 : digest.hashCode()); - temp = Double.doubleToLongBits(emptyMass); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(launchMass); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(length); - result = prime * result + (int) (temp ^ (temp >>> 32)); - result = prime * result - + ((manufacturer == null) ? 0 : manufacturer.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ThrustCurveMotorPlaceholder other = (ThrustCurveMotorPlaceholder) obj; - if (Double.doubleToLongBits(delay) != Double - .doubleToLongBits(other.delay)) - return false; - if (designation == null) { - if (other.designation != null) - return false; - } else if (!designation.equals(other.designation)) - return false; - if (Double.doubleToLongBits(diameter) != Double - .doubleToLongBits(other.diameter)) - return false; - if (digest == null) { - if (other.digest != null) - return false; - } else if (!digest.equals(other.digest)) - return false; - if (Double.doubleToLongBits(emptyMass) != Double - .doubleToLongBits(other.emptyMass)) - return false; - if (Double.doubleToLongBits(launchMass) != Double - .doubleToLongBits(other.launchMass)) - return false; - if (Double.doubleToLongBits(length) != Double - .doubleToLongBits(other.length)) - return false; - if (manufacturer == null) { - if (other.manufacturer != null) - return false; - } else if (!manufacturer.equals(other.manufacturer)) - return false; - if (type != other.type) - return false; - return true; - } - - - @Override - public String toString() { - return "ThrustCurveMotorPlaceholder [manufacturer=" + manufacturer - + ", designation=" + designation + "]"; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/general/Function.java b/core/src/net/sf/openrocket/optimization/general/Function.java deleted file mode 100644 index a7be5668..00000000 --- a/core/src/net/sf/openrocket/optimization/general/Function.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.sf.openrocket.optimization.general; - -/** - * An interface defining an optimizable function. - *

- * Some function optimizers require that the function is thread-safe. - * - * @author Sampo Niskanen - */ -public interface Function { - - /** - * Evaluate the function at the specified point. - *

- * If the function evaluation is slow, then this method should abort the computation if - * the thread is interrupted. - * - * @param point the point at which to evaluate the function. - * @return the function value. - * @throws InterruptedException if the thread was interrupted before function evaluation was completed. - * @throws OptimizationException if an error occurs that prevents the optimization - */ - public double evaluate(Point point) throws InterruptedException, OptimizationException; - -} diff --git a/core/src/net/sf/openrocket/optimization/general/FunctionCache.java b/core/src/net/sf/openrocket/optimization/general/FunctionCache.java deleted file mode 100644 index 69c42d79..00000000 --- a/core/src/net/sf/openrocket/optimization/general/FunctionCache.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.sf.openrocket.optimization.general; - -/** - * A storage of cached values of a function. The purpose of this class is to - * cache function values between optimization runs. Subinterfaces may provide - * additional functionality. - * - * @author Sampo Niskanen - */ -public interface FunctionCache { - - /** - * Compute and return the value of the function at the specified point. - * - * @param point the point at which to evaluate. - * @return the value of the function at that point. - */ - public double getValue(Point point); - - /** - * Clear the cache. - */ - public void clearCache(); - - /** - * Return the function that is evaluated by this cache implementation. - * - * @return the function that is being evaluated. - */ - public Function getFunction(); - - /** - * Set the function that is evaluated by this cache implementation. - * - * @param function the function that is being evaluated. - */ - public void setFunction(Function function); - -} diff --git a/core/src/net/sf/openrocket/optimization/general/FunctionOptimizer.java b/core/src/net/sf/openrocket/optimization/general/FunctionOptimizer.java deleted file mode 100644 index 485843f9..00000000 --- a/core/src/net/sf/openrocket/optimization/general/FunctionOptimizer.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.optimization.general; - -/** - * An interface for a function optimization algorithm. The function is evaluated - * via a function cache. - * - * @author Sampo Niskanen - */ -public interface FunctionOptimizer { - - /** - * Perform optimization on the function. The optimization control is called to control - * when optimization is stopped. - * - * @param initial the initial start point of the optimization. - * @param control the optimization control. - * @throws OptimizationException if an error occurs that prevents optimization - */ - public void optimize(Point initial, OptimizationController control) throws OptimizationException; - - - /** - * Return the optimum point computed by {@link #optimize(Point, OptimizationController)}. - * - * @return the optimum point value. - * @throws IllegalStateException if {@link #optimize(Point, OptimizationController)} has not been called. - */ - public Point getOptimumPoint(); - - /** - * Return the function value at the optimum point. - * - * @return the value at the optimum point. - * @throws IllegalStateException if {@link #optimize(Point, OptimizationController)} has not been called. - */ - public double getOptimumValue(); - - - /** - * Return the function cache used by this optimization algorithm. - * - * @return the function cache. - */ - public FunctionCache getFunctionCache(); - - /** - * Set the function cache that provides the function values for this algorithm. - * Some algorithms may require the function cache to be an instance of - * ParallelFunctionCache. - * - * @param functionCache the function cache. - */ - public void setFunctionCache(FunctionCache functionCache); - - -} diff --git a/core/src/net/sf/openrocket/optimization/general/OptimizationController.java b/core/src/net/sf/openrocket/optimization/general/OptimizationController.java deleted file mode 100644 index c91689cb..00000000 --- a/core/src/net/sf/openrocket/optimization/general/OptimizationController.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.sf.openrocket.optimization.general; - -public interface OptimizationController { - - /** - * Control for whether to continue the optimization. This method is called after - * every full step taken by the optimization algorithm. - * - * @param oldPoint the old position. - * @param oldValue the value of the function at the old position. - * @param newPoint the new position. - * @param newValue the value of the function at the new position. - * @param stepSize the step length that is used to search for smaller function values when applicable, or NaN. - * @return true to continue optimization, false to stop. - */ - public boolean stepTaken(Point oldPoint, double oldValue, Point newPoint, double newValue, - double stepSize); - -} diff --git a/core/src/net/sf/openrocket/optimization/general/OptimizationControllerDelegator.java b/core/src/net/sf/openrocket/optimization/general/OptimizationControllerDelegator.java deleted file mode 100644 index a0a455e9..00000000 --- a/core/src/net/sf/openrocket/optimization/general/OptimizationControllerDelegator.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.optimization.general; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * An OptimizationController that delegates control actions to multiple other controllers. - * The optimization is stopped if any of the controllers stops it. - * - * @author Sampo Niskanen - */ -public class OptimizationControllerDelegator implements OptimizationController { - - private final List controllers = new ArrayList(); - - /** - * Construct the controlled based on an array of controllers. - * - * @param controllers the controllers to use. - */ - public OptimizationControllerDelegator(OptimizationController... controllers) { - for (OptimizationController c : controllers) { - this.controllers.add(c); - } - } - - /** - * Construct the controller based on a collection of controllers. - * - * @param controllers the controllers to use. - */ - public OptimizationControllerDelegator(Collection controllers) { - this.controllers.addAll(controllers); - } - - - /** - * Control whether to continue optimization. This method returns false if any of the - * used controllers returns false. However, all controllers will be called even if - * an earlier one stops the optimization. - */ - @Override - public boolean stepTaken(Point oldPoint, double oldValue, Point newPoint, double newValue, double stepSize) { - boolean ret = true; - - for (OptimizationController c : controllers) { - if (!c.stepTaken(oldPoint, oldValue, newPoint, newValue, stepSize)) { - ret = false; - } - } - - return ret; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/general/OptimizationException.java b/core/src/net/sf/openrocket/optimization/general/OptimizationException.java deleted file mode 100644 index 7c0c0674..00000000 --- a/core/src/net/sf/openrocket/optimization/general/OptimizationException.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.optimization.general; - -/** - * An exception that prevents optimization from continuing. - * - * @author Sampo Niskanen - */ -public class OptimizationException extends Exception { - - public OptimizationException(String message) { - super(message); - } - - public OptimizationException(Throwable cause) { - super(cause); - } - - public OptimizationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/optimization/general/ParallelExecutorCache.java b/core/src/net/sf/openrocket/optimization/general/ParallelExecutorCache.java deleted file mode 100644 index 67154da5..00000000 --- a/core/src/net/sf/openrocket/optimization/general/ParallelExecutorCache.java +++ /dev/null @@ -1,303 +0,0 @@ -package net.sf.openrocket.optimization.general; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import net.sf.openrocket.util.BugException; - -/** - * An implementation of a ParallelFunctionCache that evaluates function values - * in parallel and caches them. This allows pre-calculating possibly required - * function values beforehand. If values are not required after all, the - * computation can be aborted assuming the function evaluation supports it. - *

- * Note that while this class handles threads and abstracts background execution, - * the public methods themselves are NOT thread-safe and should be called from - * only one thread at a time. - * - * @author Sampo Niskanen - */ -public class ParallelExecutorCache implements ParallelFunctionCache { - - private final Map functionCache = new HashMap(); - private final Map> futureMap = new HashMap>(); - - private ExecutorService executor; - - private Function function; - - - /** - * Construct a cache that uses the same number of computational threads as there are - * processors available. - */ - public ParallelExecutorCache() { - this(Runtime.getRuntime().availableProcessors()); - } - - /** - * Construct a cache that uses the specified number of computational threads for background - * computation. The threads that are created are marked as daemon threads. - * - * @param threadCount the number of threads to use in the executor. - */ - public ParallelExecutorCache(int threadCount) { - this(new ThreadPoolExecutor(threadCount, threadCount, 60, TimeUnit.SECONDS, - new LinkedBlockingQueue(), - new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - })); - } - - /** - * Construct a cache that uses the specified ExecutorService for managing - * computational threads. - * - * @param executor the executor to use for function evaluations. - */ - public ParallelExecutorCache(ExecutorService executor) { - this.executor = executor; - } - - - - @Override - public void compute(Collection points) { - for (Point p : points) { - compute(p); - } - } - - - @Override - public void compute(Point point) { - - if (isOutsideRange(point)) { - // Point is outside of range - return; - } - - if (functionCache.containsKey(point)) { - // Function has already been evaluated at the point - return; - } - - if (futureMap.containsKey(point)) { - // Function is being evaluated at the point - return; - } - - // Submit point for evaluation - FunctionCallable callable = new FunctionCallable(function, point); - Future future = executor.submit(callable); - futureMap.put(point, future); - } - - - @Override - public void waitFor(Collection points) throws InterruptedException, OptimizationException { - for (Point p : points) { - waitFor(p); - } - } - - - @Override - public void waitFor(Point point) throws InterruptedException, OptimizationException { - if (isOutsideRange(point)) { - return; - } - - if (functionCache.containsKey(point)) { - return; - } - - Future future = futureMap.get(point); - if (future == null) { - throw new IllegalStateException("waitFor called for " + point + " but it is not being computed"); - } - - try { - double value = future.get(); - functionCache.put(point, value); - } catch (ExecutionException e) { - Throwable cause = e.getCause(); - if (cause instanceof InterruptedException) { - throw (InterruptedException) cause; - } - if (cause instanceof OptimizationException) { - throw (OptimizationException) cause; - } - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; - } - - throw new BugException("Function threw unknown exception while processing", e); - } - } - - - - @Override - public List abort(Collection points) { - List computed = new ArrayList(Math.min(points.size(), 10)); - - for (Point p : points) { - if (abort(p)) { - computed.add(p); - } - } - - return computed; - } - - - - @Override - public boolean abort(Point point) { - if (isOutsideRange(point)) { - return false; - } - - if (functionCache.containsKey(point)) { - return true; - } - - Future future = futureMap.remove(point); - if (future == null) { - throw new IllegalStateException("abort called for " + point + " but it is not being computed"); - } - - if (future.isDone()) { - // Evaluation has been completed, store value in cache - try { - double value = future.get(); - functionCache.put(point, value); - return true; - } catch (Exception e) { - return false; - } - } else { - // Cancel the evaluation - future.cancel(true); - return false; - } - } - - - @Override - public void abortAll() { - Iterator iterator = futureMap.keySet().iterator(); - while (iterator.hasNext()) { - Point point = iterator.next(); - Future future = futureMap.get(point); - iterator.remove(); - - if (future.isDone()) { - // Evaluation has been completed, store value in cache - try { - double value = future.get(); - functionCache.put(point, value); - } catch (Exception e) { - // Ignore - } - } else { - // Cancel the evaluation - future.cancel(true); - } - } - } - - - @Override - public double getValue(Point point) { - if (isOutsideRange(point)) { - return Double.MAX_VALUE; - } - - Double d = functionCache.get(point); - if (d == null) { - throw new IllegalStateException(point + " is not in function cache. " + - "functionCache=" + functionCache + " futureMap=" + futureMap); - } - return d; - } - - - @Override - public Function getFunction() { - return function; - } - - @Override - public void setFunction(Function function) { - this.function = function; - clearCache(); - } - - @Override - public void clearCache() { - List list = new ArrayList(futureMap.keySet()); - abort(list); - functionCache.clear(); - } - - - public ExecutorService getExecutor() { - return executor; - } - - - /** - * Check whether a point is outside of the valid optimization range. - */ - private boolean isOutsideRange(Point p) { - int n = p.dim(); - for (int i = 0; i < n; i++) { - double d = p.get(i); - // Include NaN in disallowed range - if (!(d >= 0.0 && d <= 1.0)) { - return true; - } - } - return false; - } - - - /** - * A Callable that evaluates a function at a specific point and returns the result. - */ - private class FunctionCallable implements Callable { - private final Function calledFunction; - private final Point point; - - public FunctionCallable(Function function, Point point) { - this.calledFunction = function; - this.point = point; - } - - @Override - public Double call() throws InterruptedException, OptimizationException { - return calledFunction.evaluate(point); - } - } - - -} diff --git a/core/src/net/sf/openrocket/optimization/general/ParallelFunctionCache.java b/core/src/net/sf/openrocket/optimization/general/ParallelFunctionCache.java deleted file mode 100644 index 1c8a35f6..00000000 --- a/core/src/net/sf/openrocket/optimization/general/ParallelFunctionCache.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.optimization.general; - -import java.util.Collection; -import java.util.List; - -/** - * A FunctionCache that allows scheduling points to be computed in the background, - * waiting for specific points to become computed or aborting the computation of - * points. - * - * @author Sampo Niskanen - */ -public interface ParallelFunctionCache extends FunctionCache { - - /** - * Schedule a list of function evaluations at the specified points. - * The points are added to the end of the computation queue in the order - * they are returned by the iterator. - * - * @param points the points at which to evaluate the function. - */ - public void compute(Collection points); - - /** - * Schedule function evaluation for the specified point. The point is - * added to the end of the computation queue. - * - * @param point the point at which to evaluate the function. - */ - public void compute(Point point); - - /** - * Wait for a collection of points to be computed. After calling this method - * the function values are available by calling {@link #getValue(Point)}. - * - * @param points the points to wait for. - * @throws InterruptedException if this thread or the computing thread was interrupted while waiting. - * @throws OptimizationException if an error preventing continuing the optimization occurs. - */ - public void waitFor(Collection points) throws InterruptedException, OptimizationException; - - /** - * Wait for a point to be computed. After calling this method - * the function value is available by calling {@link #getValue(Point)}. - * - * @param point the point to wait for. - * @throws InterruptedException if this thread or the computing thread was interrupted while waiting. - * @throws OptimizationException if an error preventing continuing the optimization occurs. - */ - public void waitFor(Point point) throws InterruptedException, OptimizationException; - - - /** - * Abort the computation of the specified points. If computation has ended, - * the result is stored in the function cache anyway. - * - * @param points the points to abort. - * @return a list of the points that have been computed anyway - */ - public List abort(Collection points); - - - /** - * Abort the computation of the specified point. If computation has ended, - * the result is stored in the function cache anyway. - * - * @param point the point to abort. - * @return true if the point has been computed anyway, false if not. - */ - public boolean abort(Point point); - - - /** - * Abort the computation of all still unexecuted points. - */ - public void abortAll(); -} diff --git a/core/src/net/sf/openrocket/optimization/general/Point.java b/core/src/net/sf/openrocket/optimization/general/Point.java deleted file mode 100644 index 9b2bece8..00000000 --- a/core/src/net/sf/openrocket/optimization/general/Point.java +++ /dev/null @@ -1,207 +0,0 @@ -package net.sf.openrocket.optimization.general; - -import java.util.Arrays; - -import net.sf.openrocket.util.MathUtil; - -/** - * An immutable n-dimensional coordinate point. - * - * @author Sampo Niskanen - */ -public final class Point { - - private final double[] point; - private double length = -1; - private double length2 = -1; - - - /** - * Create a new point with all values zero. - * - * @param dim the dimensionality of the point - */ - public Point(int dim) { - if (dim <= 0) { - throw new IllegalArgumentException("Invalid dimensionality " + dim); - } - point = new double[dim]; - } - - - /** - * Create a new point filled with a specific value. - * - * @param dim the dimensionality of the point - * @param value the value for all dimensions - */ - public Point(int dim, double value) { - this(dim); - Arrays.fill(point, value); - } - - - /** - * Create a new point with specific values. - * - * @param value the values of the dimensions. - */ - public Point(double... value) { - if (value.length == 0) { - throw new IllegalArgumentException("Zero-dimensional point not allowed"); - } - point = value.clone(); - } - - - /** - * Create a copy of a point. Used locally to create copies. - * - * @param p the point to copy. - */ - private Point(Point p) { - point = p.point.clone(); - } - - - - /** - * Return the point dimensionality. - * - * @return the point dimensionality - */ - public int dim() { - return point.length; - } - - - - public double get(int i) { - return point[i]; - } - - public Point set(int i, double v) { - Point p = new Point(this); - p.point[i] = v; - return p; - } - - - /** - * Return a new point that is the sum of two points. - * - * @param other the point to add to this point. - * @return the sum of these points. - */ - public Point add(Point other) { - Point p = new Point(this); - for (int i = 0; i < point.length; i++) { - p.point[i] += other.point[i]; - } - return p; - } - - - /** - * Return a new point that is the subtraction of two points. - * - * @param other the point to subtract from this point. - * @return the value of this - other. - */ - public Point sub(Point other) { - Point p = new Point(this); - for (int i = 0; i < point.length; i++) { - p.point[i] -= other.point[i]; - } - return p; - } - - - /** - * Return this point multiplied by a scalar value. - * - * @param v the scalar to multiply with - * @return the scaled point - */ - public Point mul(double v) { - Point p = new Point(this); - for (int i = 0; i < point.length; i++) { - p.point[i] *= v; - } - return p; - } - - - /** - * Return the length of this coordinate. - * - * @return the length. - */ - public double length() { - if (length < 0) { - length = MathUtil.safeSqrt(length2()); - } - return length; - } - - - /** - * Return the squared length of this coordinate. - * - * @return the square of the length of thie coordinate. - */ - public double length2() { - if (length2 < 0) { - length2 = 0; - for (double p : point) { - length2 += p * p; - } - } - return length2; - } - - - - /** - * Return the point as an array. - * - * @return the point as an array. - */ - public double[] asArray() { - return point.clone(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - - if (!(obj instanceof Point)) - return false; - - Point other = (Point) obj; - if (this.point.length != other.point.length) - return false; - - for (int i = 0; i < point.length; i++) { - if (!MathUtil.equals(this.point[i], other.point[i])) - return false; - } - return true; - } - - @Override - public int hashCode() { - int n = 0; - for (double d : point) { - n *= 37; - n += (int) (d * 1000); - } - return n; - } - - @Override - public String toString() { - return "Point" + Arrays.toString(point); - } -} diff --git a/core/src/net/sf/openrocket/optimization/general/multidim/FunctionCacheComparator.java b/core/src/net/sf/openrocket/optimization/general/multidim/FunctionCacheComparator.java deleted file mode 100644 index 16a2fbcc..00000000 --- a/core/src/net/sf/openrocket/optimization/general/multidim/FunctionCacheComparator.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.optimization.general.multidim; - -import java.util.Comparator; - -import net.sf.openrocket.optimization.general.FunctionCache; -import net.sf.openrocket.optimization.general.Point; - -/** - * A comparator that orders Points in a function value order, smallest first. - * - * @author Sampo Niskanen - */ -public class FunctionCacheComparator implements Comparator { - - private final FunctionCache cache; - - public FunctionCacheComparator(FunctionCache cache) { - this.cache = cache; - } - - @Override - public int compare(Point o1, Point o2) { - double v1 = cache.getValue(o1); - double v2 = cache.getValue(o2); - - return Double.compare(v1, v2); - } - -} diff --git a/core/src/net/sf/openrocket/optimization/general/multidim/MultidirectionalSearchOptimizer.java b/core/src/net/sf/openrocket/optimization/general/multidim/MultidirectionalSearchOptimizer.java deleted file mode 100644 index d4d04fc9..00000000 --- a/core/src/net/sf/openrocket/optimization/general/multidim/MultidirectionalSearchOptimizer.java +++ /dev/null @@ -1,324 +0,0 @@ -package net.sf.openrocket.optimization.general.multidim; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.FunctionCache; -import net.sf.openrocket.optimization.general.FunctionOptimizer; -import net.sf.openrocket.optimization.general.OptimizationController; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.ParallelFunctionCache; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Statistics; - -/** - * A customized implementation of the parallel multidirectional search algorithm by Dennis and Torczon. - *

- * This is a parallel pattern search optimization algorithm. The function evaluations are performed - * using an ExecutorService. By default a ThreadPoolExecutor is used that has as many thread defined - * as the system has processors. - *

- * The optimization can be aborted by interrupting the current thread. - */ -public class MultidirectionalSearchOptimizer implements FunctionOptimizer, Statistics { - private static final LogHelper log = Application.getLogger(); - - private List simplex = new ArrayList(); - - private ParallelFunctionCache functionExecutor; - - private boolean useExpansion = false; - private boolean useCoordinateSearch = false; - - private int stepCount = 0; - private int reflectionAcceptance = 0; - private int expansionAcceptance = 0; - private int coordinateAcceptance = 0; - private int reductionFallback = 0; - - - public MultidirectionalSearchOptimizer() { - // No-op - } - - public MultidirectionalSearchOptimizer(ParallelFunctionCache functionCache) { - this.functionExecutor = functionCache; - } - - - - @Override - public void optimize(Point initial, OptimizationController control) throws OptimizationException { - FunctionCacheComparator comparator = new FunctionCacheComparator(functionExecutor); - - final List pattern = SearchPattern.square(initial.dim()); - log.info("Starting optimization at " + initial + " with pattern " + pattern); - - try { - - boolean simplexComputed = false; - double step = 0.5; - - // Set up the current simplex - simplex.clear(); - simplex.add(initial); - for (Point p : pattern) { - simplex.add(initial.add(p.mul(step))); - } - - // Normal iterations - List reflection = new ArrayList(simplex.size()); - List expansion = new ArrayList(simplex.size()); - List coordinateSearch = new ArrayList(simplex.size()); - Point current; - double currentValue; - boolean continueOptimization = true; - while (continueOptimization) { - - log.debug("Starting optimization step with simplex " + simplex + - (simplexComputed ? "" : " (not computed)")); - stepCount++; - - if (!simplexComputed) { - // TODO: Could something be computed in parallel? - functionExecutor.compute(simplex); - functionExecutor.waitFor(simplex); - Collections.sort(simplex, comparator); - simplexComputed = true; - } - - current = simplex.get(0); - currentValue = functionExecutor.getValue(current); - - /* - * Compute and queue the next points in likely order of usefulness. - * Expansion is unlikely as we're mainly dealing with bounded optimization. - */ - createReflection(simplex, reflection); - if (useCoordinateSearch) - createCoordinateSearch(current, step, coordinateSearch); - if (useExpansion) - createExpansion(simplex, expansion); - - functionExecutor.compute(reflection); - if (useCoordinateSearch) - functionExecutor.compute(coordinateSearch); - if (useExpansion) - functionExecutor.compute(expansion); - - // Check reflection acceptance - log.debug("Computing reflection"); - functionExecutor.waitFor(reflection); - - if (accept(reflection, currentValue)) { - - log.debug("Reflection was successful, aborting coordinate search, " + - (useExpansion ? "computing" : "skipping") + " expansion"); - - if (useCoordinateSearch) - functionExecutor.abort(coordinateSearch); - - simplex.clear(); - simplex.add(current); - simplex.addAll(reflection); - Collections.sort(simplex, comparator); - - if (useExpansion) { - - /* - * Assume expansion to be unsuccessful, queue next reflection while computing expansion. - */ - createReflection(simplex, reflection); - - functionExecutor.compute(reflection); - functionExecutor.waitFor(expansion); - - if (accept(expansion, currentValue)) { - log.debug("Expansion was successful, aborting reflection"); - functionExecutor.abort(reflection); - - simplex.clear(); - simplex.add(current); - simplex.addAll(expansion); - step *= 2; - Collections.sort(simplex, comparator); - expansionAcceptance++; - } else { - log.debug("Expansion failed"); - reflectionAcceptance++; - } - - } else { - reflectionAcceptance++; - } - - } else { - - log.debug("Reflection was unsuccessful, aborting expansion, computing coordinate search"); - - functionExecutor.abort(expansion); - - /* - * Assume coordinate search to be unsuccessful, queue contraction step while computing. - */ - halveStep(simplex); - functionExecutor.compute(simplex); - - if (useCoordinateSearch) { - functionExecutor.waitFor(coordinateSearch); - - if (accept(coordinateSearch, currentValue)) { - - log.debug("Coordinate search successful, reseting simplex"); - List toAbort = new LinkedList(simplex); - simplex.clear(); - simplex.add(current); - for (Point p : pattern) { - simplex.add(current.add(p.mul(step))); - } - toAbort.removeAll(simplex); - functionExecutor.abort(toAbort); - simplexComputed = false; - coordinateAcceptance++; - - } else { - log.debug("Coordinate search unsuccessful, halving step."); - step /= 2; - simplexComputed = false; - reductionFallback++; - } - } else { - log.debug("Coordinate search not used, halving step."); - step /= 2; - simplexComputed = false; - reductionFallback++; - } - - } - - log.debug("Ending optimization step with simplex " + simplex); - - continueOptimization = control.stepTaken(current, currentValue, simplex.get(0), - functionExecutor.getValue(simplex.get(0)), step); - - if (Thread.interrupted()) { - throw new InterruptedException(); - } - - } - - } catch (InterruptedException e) { - log.info("Optimization was interrupted with InterruptedException"); - } - - log.info("Finishing optimization at point " + simplex.get(0) + " value = " + - functionExecutor.getValue(simplex.get(0))); - log.info("Optimization statistics: " + getStatistics()); - } - - - - private void createReflection(List base, List reflection) { - Point current = base.get(0); - reflection.clear(); - - /* new = - (old - current) + current = 2*current - old */ - for (int i = 1; i < base.size(); i++) { - Point p = base.get(i); - p = current.mul(2).sub(p); - reflection.add(p); - } - } - - private void createExpansion(List base, List expansion) { - Point current = base.get(0); - expansion.clear(); - for (int i = 1; i < base.size(); i++) { - Point p = current.mul(3).sub(base.get(i).mul(2)); - expansion.add(p); - } - } - - private void halveStep(List base) { - Point current = base.get(0); - for (int i = 1; i < base.size(); i++) { - Point p = base.get(i); - - /* new = (old - current)*0.5 + current = old*0.5 + current*0.5 = (old + current)*0.5 */ - - p = p.add(current).mul(0.5); - base.set(i, p); - } - } - - private void createCoordinateSearch(Point current, double step, List coordinateDirections) { - coordinateDirections.clear(); - for (int i = 0; i < current.dim(); i++) { - Point p = new Point(current.dim()); - p = p.set(i, step); - coordinateDirections.add(current.add(p)); - coordinateDirections.add(current.sub(p)); - } - } - - - private boolean accept(List points, double currentValue) { - for (Point p : points) { - if (functionExecutor.getValue(p) < currentValue) { - return true; - } - } - return false; - } - - - - @Override - public Point getOptimumPoint() { - if (simplex.size() == 0) { - throw new IllegalStateException("Optimization has not been called, simplex is empty"); - } - return simplex.get(0); - } - - @Override - public double getOptimumValue() { - return functionExecutor.getValue(getOptimumPoint()); - } - - @Override - public FunctionCache getFunctionCache() { - return functionExecutor; - } - - @Override - public void setFunctionCache(FunctionCache functionCache) { - if (!(functionCache instanceof ParallelFunctionCache)) { - throw new IllegalArgumentException("Function cache needs to be a ParallelFunctionCache: " + functionCache); - } - this.functionExecutor = (ParallelFunctionCache) functionCache; - } - - @Override - public String getStatistics() { - return "MultidirectionalSearchOptimizer[stepCount=" + stepCount + - ", reflectionAcceptance=" + reflectionAcceptance + - ", expansionAcceptance=" + expansionAcceptance + - ", coordinateAcceptance=" + coordinateAcceptance + - ", reductionFallback=" + reductionFallback; - } - - @Override - public void resetStatistics() { - stepCount = 0; - reflectionAcceptance = 0; - expansionAcceptance = 0; - coordinateAcceptance = 0; - reductionFallback = 0; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/general/multidim/SearchPattern.java b/core/src/net/sf/openrocket/optimization/general/multidim/SearchPattern.java deleted file mode 100644 index 1a7df333..00000000 --- a/core/src/net/sf/openrocket/optimization/general/multidim/SearchPattern.java +++ /dev/null @@ -1,95 +0,0 @@ -package net.sf.openrocket.optimization.general.multidim; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.util.MathUtil; - -/** - * A helper class to create search patterns. - * - * @author Sampo Niskanen - */ -public class SearchPattern { - - /** - * Create a square search pattern with the specified dimensionality. - * - * @param dimensionality the dimensionality - */ - public static List square(int dimensionality) { - List pattern = new ArrayList(dimensionality); - - for (int i = 0; i < dimensionality; i++) { - double[] p = new double[dimensionality]; - p[i] = 1.0; - pattern.add(new Point(p)); - } - return pattern; - } - - - - /** - * Create a regular simplex search pattern with the specified dimensionality. - * - * @param dimensionality the dimensionality - */ - public static List regularSimplex(int dimensionality) { - if (dimensionality <= 0) { - throw new IllegalArgumentException("Illegal dimensionality " + dimensionality); - } - - List pattern = new ArrayList(dimensionality); - - double[] coordinates = new double[dimensionality]; - double dot = -1.0 / dimensionality; - - /* - * First construct an origin-centered regular simplex. - * http://en.wikipedia.org/wiki/Simplex#Cartesian_coordinates_for_regular_n-dimensional_simplex_in_Rn - */ - - for (int i = 0; i < dimensionality; i++) { - // Compute the next point coordinate - double value = 1; - - for (int j = 0; j < i; j++) { - value -= MathUtil.pow2(coordinates[j]); - } - value = MathUtil.safeSqrt(value); - - coordinates[i] = value; - pattern.add(new Point(coordinates)); - - // Compute the i-coordinate for all next points - value = dot; - for (int j = 0; j < i; j++) { - value -= MathUtil.pow2(coordinates[j]); - } - value = value / coordinates[i]; - - coordinates[i] = value; - } - - // Minimum point - Point min = pattern.get(dimensionality - 1); - min = min.set(dimensionality - 1, -min.get(dimensionality - 1)); - - - /* - * Shift simplex to have a corner at the origin and scale to unit length. - */ - if (dimensionality > 1) { - double scale = 1.0 / (pattern.get(1).sub(pattern.get(0)).length()); - for (int i = 0; i < dimensionality; i++) { - Point p = pattern.get(i); - p = p.sub(min).mul(scale); - pattern.set(i, p); - } - } - - return pattern; - } -} diff --git a/core/src/net/sf/openrocket/optimization/general/onedim/GoldenSectionSearchOptimizer.java b/core/src/net/sf/openrocket/optimization/general/onedim/GoldenSectionSearchOptimizer.java deleted file mode 100644 index 906eea57..00000000 --- a/core/src/net/sf/openrocket/optimization/general/onedim/GoldenSectionSearchOptimizer.java +++ /dev/null @@ -1,272 +0,0 @@ -package net.sf.openrocket.optimization.general.onedim; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.FunctionCache; -import net.sf.openrocket.optimization.general.FunctionOptimizer; -import net.sf.openrocket.optimization.general.OptimizationController; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.ParallelFunctionCache; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Statistics; - -/** - * An implementation of a one-dimensional golden section search method - * (see e.g. Nonlinear programming, Bazaraa, Sherall, Shetty, 2nd edition, p. 270) - *

- * This implementation attempts to guess future evaluations and computes them in parallel - * with the next point. - *

- * The optimization can be aborted by interrupting the current thread. - */ -public class GoldenSectionSearchOptimizer implements FunctionOptimizer, Statistics { - private static final LogHelper log = Application.getLogger(); - - private static final double ALPHA = (Math.sqrt(5) - 1) / 2.0; - - - private ParallelFunctionCache functionExecutor; - - private Point current = null; - - private int guessSuccess = 0; - private int guessFailure = 0; - - - /** - * Construct an optimizer with no function executor. - */ - public GoldenSectionSearchOptimizer() { - // No-op - } - - /** - * Construct an optimizer. - * - * @param functionExecutor the function executor. - */ - public GoldenSectionSearchOptimizer(ParallelFunctionCache functionExecutor) { - super(); - this.functionExecutor = functionExecutor; - } - - @Override - public void optimize(Point initial, OptimizationController control) throws OptimizationException { - - if (initial.dim() != 1) { - throw new IllegalArgumentException("Only single-dimensional optimization supported, dim=" + - initial.dim()); - } - - log.info("Starting golden section search for optimization"); - - Point guessAC = null; - Point guessBD = null; - - try { - boolean guessedAC; - - Point previous = p(0); - double previousValue = Double.NaN; - current = previous; - double currentValue = Double.NaN; - - /* - * Initialize the points + computation. - */ - Point a = p(0); - Point d = p(1.0); - Point b = section1(a, d); - Point c = section2(a, d); - - functionExecutor.compute(a); - functionExecutor.compute(d); - functionExecutor.compute(b); - functionExecutor.compute(c); - - // Wait for points a and d, which normally are already precomputed - functionExecutor.waitFor(a); - functionExecutor.waitFor(d); - - boolean continueOptimization = true; - while (continueOptimization) { - - /* - * Get values at A & D for guessing. - * These are pre-calculated except during the first step. - */ - double fa, fd; - fa = functionExecutor.getValue(a); - fd = functionExecutor.getValue(d); - - - /* - * Start calculating possible two next points. The order of evaluation - * is selected based on the function values at A and D. - */ - guessAC = section1(a, c); - guessBD = section2(b, d); - if (Double.isNaN(fd) || fa < fd) { - guessedAC = true; - functionExecutor.compute(guessAC); - functionExecutor.compute(guessBD); - } else { - guessedAC = false; - functionExecutor.compute(guessBD); - functionExecutor.compute(guessAC); - } - - - /* - * Get values at B and C. - */ - double fb, fc; - functionExecutor.waitFor(b); - functionExecutor.waitFor(c); - fb = functionExecutor.getValue(b); - fc = functionExecutor.getValue(c); - - double min = MathUtil.min(fa, fb, fc, fd); - if (Double.isNaN(min)) { - throw new OptimizationException("Unable to compute initial function values"); - } - - - /* - * Update previous and current values for step control. - */ - previousValue = currentValue; - currentValue = min; - previous = current; - if (min == fa) { - current = a; - } else if (min == fb) { - current = b; - } else if (min == fc) { - current = c; - } else { - current = d; - } - - - /* - * Select next positions. These are already being calculated in the background - * as guessAC and guessBD. - */ - if (min == fa || min == fb) { - d = c; - c = b; - b = guessAC; - functionExecutor.abort(guessBD); - guessBD = null; - log.debug("Selecting A-C region, a=" + a.get(0) + " c=" + c.get(0)); - if (guessedAC) { - guessSuccess++; - } else { - guessFailure++; - } - } else { - a = b; - b = c; - c = guessBD; - functionExecutor.abort(guessAC); - guessAC = null; - log.debug("Selecting B-D region, b=" + b.get(0) + " d=" + d.get(0)); - if (!guessedAC) { - guessSuccess++; - } else { - guessFailure++; - } - } - - - /* - * Check optimization control. - */ - continueOptimization = control.stepTaken(previous, previousValue, - current, currentValue, c.get(0) - a.get(0)); - - if (Thread.interrupted()) { - throw new InterruptedException(); - } - - } - - - } catch (InterruptedException e) { - log.info("Optimization was interrupted with InterruptedException"); - } - - if (guessAC != null) { - functionExecutor.abort(guessAC); - } - if (guessBD != null) { - functionExecutor.abort(guessBD); - } - - - log.info("Finishing optimization at point " + getOptimumPoint() + " value " + getOptimumValue()); - log.info("Optimization statistics: " + getStatistics()); - } - - - private Point p(double v) { - return new Point(v); - } - - - private Point section1(Point a, Point b) { - double va = a.get(0); - double vb = b.get(0); - return p(va + (1 - ALPHA) * (vb - va)); - } - - private Point section2(Point a, Point b) { - double va = a.get(0); - double vb = b.get(0); - return p(va + ALPHA * (vb - va)); - } - - - - @Override - public Point getOptimumPoint() { - return current; - } - - - @Override - public double getOptimumValue() { - if (getOptimumPoint() == null) { - return Double.NaN; - } - return functionExecutor.getValue(getOptimumPoint()); - } - - @Override - public FunctionCache getFunctionCache() { - return functionExecutor; - } - - @Override - public void setFunctionCache(FunctionCache functionCache) { - if (!(functionCache instanceof ParallelFunctionCache)) { - throw new IllegalArgumentException("Function cache needs to be a ParallelFunctionCache: " + functionCache); - } - this.functionExecutor = (ParallelFunctionCache) functionCache; - } - - @Override - public String getStatistics() { - return String.format("Guess hit rate %d/%d = %.3f", guessSuccess, guessSuccess + guessFailure, - ((double) guessSuccess) / (guessSuccess + guessFailure)); - } - - @Override - public void resetStatistics() { - guessSuccess = 0; - guessFailure = 0; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/OptimizableParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/OptimizableParameter.java deleted file mode 100644 index 2acdb049..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/OptimizableParameter.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.unit.UnitGroup; - -/** - * A parameter of a rocket or simulation that can be optimized - * (for example max. altitude or velocity). - * - * @author Sampo Niskanen - */ -public interface OptimizableParameter { - - /** - * Return the label name for this optimization parameter. - * - * @return the name for the optimization parameter (e.g. "Flight altitude") - */ - public String getName(); - - /** - * Compute the value for this optimization parameter for the simulation. - * The return value can be any double value. - *

- * This method can return NaN in case of a problem computing - * - * @param simulation the simulation - * @return the parameter value (any double value) - * @throws OptimizationException if an error occurs preventing the optimization from continuing - */ - public double computeValue(Simulation simulation) throws OptimizationException, InterruptedException; - - - /** - * Return the unit group associated with the computed value. - * @return the unit group of the computed value. - */ - public UnitGroup getUnitGroup(); - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/OptimizationGoal.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/OptimizationGoal.java deleted file mode 100644 index f7884046..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/OptimizationGoal.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -/** - * A goal for an optimization process, for example minimizing, maximizing or seeking - * a specific parameter value. - * - * @author Sampo Niskanen - */ -public interface OptimizationGoal { - - /** - * Compute a value which, when minimized, yields the desired goal of the - * optimization problem. - * - * @param value the function actual value - * @return the value to minimize to reach the goal - */ - double getMinimizationParameter(double value); - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/RocketOptimizationFunction.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/RocketOptimizationFunction.java deleted file mode 100644 index 2f224269..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/RocketOptimizationFunction.java +++ /dev/null @@ -1,186 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.Function; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.Pair; - -/** - * A Function that optimizes a specific RocketOptimizationParameter to some goal - * by modifying a base simulation using SimulationModifiers. - * - * @author Sampo Niskanen - */ -public class RocketOptimizationFunction implements Function { - private static final LogHelper log = Application.getLogger(); - - private static final double OUTSIDE_DOMAIN_SCALE = 1.0e200; - - /* - * NOTE: This class must be thread-safe!!! - */ - - private final Simulation baseSimulation; - private final OptimizableParameter parameter; - private final OptimizationGoal goal; - private final SimulationDomain domain; - private final SimulationModifier[] modifiers; - - - private final List listeners = new ArrayList(); - - - /** - * Sole constructor. - *

- * The dimensionality of the resulting function is the same as the length of the - * modifiers array. - * - * @param baseSimulation the base simulation to modify - * @param parameter the rocket parameter to optimize - * @param goal the goal of the rocket parameter - * @param modifiers the modifiers that modify the simulation - */ - public RocketOptimizationFunction(Simulation baseSimulation, OptimizableParameter parameter, - OptimizationGoal goal, SimulationDomain domain, SimulationModifier... modifiers) { - this.baseSimulation = baseSimulation; - this.parameter = parameter; - this.goal = goal; - this.domain = domain; - this.modifiers = modifiers.clone(); - if (modifiers.length == 0) { - throw new IllegalArgumentException("No SimulationModifiers specified"); - } - } - - - @Override - public double evaluate(Point point) throws InterruptedException, OptimizationException { - - /* - * parameterValue is the computed parameter value (e.g. altitude) - * goalValue is the value that needs to be minimized - */ - double goalValue, parameterValue; - - log.debug("Computing optimization function value at point " + point); - - // Create the new simulation based on the point - double[] p = point.asArray(); - if (p.length != modifiers.length) { - throw new IllegalArgumentException("Point has length " + p.length + " while function has " + - modifiers.length + " simulation modifiers"); - } - - Simulation simulation = newSimulationInstance(baseSimulation); - for (int i = 0; i < modifiers.length; i++) { - modifiers[i].modify(simulation, p[i]); - } - - - // Check whether the point is within the simulation domain - Pair d = domain.getDistanceToDomain(simulation); - double distance = d.getU(); - Value referenceValue = d.getV(); - if (distance > 0 || Double.isNaN(distance)) { - if (Double.isNaN(distance)) { - goalValue = Double.MAX_VALUE; - } else { - goalValue = (distance + 1) * OUTSIDE_DOMAIN_SCALE; - } - log.debug("Optimization point is outside of domain, distance=" + distance + " goal function value=" + goalValue); - - fireEvent(simulation, point, referenceValue, null, goalValue); - - return goalValue; - } - - - // Compute the optimization value - parameterValue = parameter.computeValue(simulation); - goalValue = goal.getMinimizationParameter(parameterValue); - - if (Double.isNaN(goalValue)) { - log.warn("Computed goal value was NaN, baseSimulation=" + baseSimulation + " parameter=" + parameter + - " goal=" + goal + " modifiers=" + Arrays.toString(modifiers) + " simulation=" + simulation + - " parameter value=" + parameterValue); - goalValue = Double.MAX_VALUE; - } - - log.verbose("Parameter value at point " + point + " is " + parameterValue + ", goal function value=" + goalValue); - - fireEvent(simulation, point, referenceValue, new Value(parameterValue, parameter.getUnitGroup().getDefaultUnit()), - goalValue); - - return goalValue; - } - - - - - - /** - * Returns a new deep copy of the simulation and rocket. This methods performs - * synchronization on the simulation for thread protection. - *

- * Note: This method is package-private for unit testing purposes. - * - * @return a new deep copy of the simulation and rocket - */ - Simulation newSimulationInstance(Simulation simulation) { - synchronized (baseSimulation) { - Rocket newRocket = simulation.getRocket().copyWithOriginalID(); - Simulation newSimulation = simulation.duplicateSimulation(newRocket); - return newSimulation; - } - } - - - /** - * Add a listener to this function. The listener will be notified each time the - * function is successfully evaluated. - *

- * Note that the listener may be called from other threads and must be thread-safe! - * - * @param listener the listener to add. - */ - public void addRocketOptimizationListener(RocketOptimizationListener listener) { - listeners.add(listener); - } - - public void removeRocketOptimizationListener(RocketOptimizationListener listener) { - listeners.remove(listener); - } - - - - private void fireEvent(Simulation simulation, Point p, Value domainReference, Value parameterValue, double goalValue) - throws OptimizationException { - - if (listeners.isEmpty()) { - return; - } - - - Value[] values = new Value[p.dim()]; - for (int i = 0; i < values.length; i++) { - double value = modifiers[i].getCurrentSIValue(simulation); - UnitGroup unit = modifiers[i].getUnitGroup(); - values[i] = new Value(value, unit.getDefaultUnit()); - } - - for (RocketOptimizationListener l : listeners) { - l.evaluated(p, values, domainReference, parameterValue, goalValue); - } - } -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/RocketOptimizationListener.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/RocketOptimizationListener.java deleted file mode 100644 index 05fc429b..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/RocketOptimizationListener.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.unit.Value; - -/** - * A listener for the progress of rocket optimization. - * - * @author Sampo Niskanen - */ -public interface RocketOptimizationListener { - - /** - * Called after successful function evaluation. - * - * @param point the optimization point. - * @param state the values to which the rocket has been modified in SI units, in the order of "point". - * @param domainReference the domain reference description (or null if unavailable) - * @param parameterValue the parameter value (or NaN if unavailable) - * @param goalValue the goal value (return value of the function) - */ - public void evaluated(Point point, Value[] state, Value domainReference, Value parameterValue, double goalValue); - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/SimulationDomain.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/SimulationDomain.java deleted file mode 100644 index d2a204ec..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/SimulationDomain.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.Pair; - -/** - * An interface defining a function domain which limits allowed function values. - * - * @author Sampo Niskanen - */ -public interface SimulationDomain { - - /** - * Return a value determining whether the simulation is within the domain limits - * of an optimization process. If the returned value is negative or zero, the - * simulation is within the domain; if the value is positive, the returned value - * is an indication of how far from the domain the value is; if the returned value - * is NaN, the simulation is outside of the domain. - * - * @param simulation the simulation to check. - * @return A pair indicating the status. The first element is the reference value, - * a negative value or zero if the simulation is in the domain, - * a positive value or NaN if not. The second is the value - * indication of the domain (may be null). - */ - public Pair getDistanceToDomain(Simulation simulation); - - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/SimulationModifier.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/SimulationModifier.java deleted file mode 100644 index 6ed85a6e..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/SimulationModifier.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.ChangeSource; - -/** - * An interface what modifies a single parameter in a rocket simulation - * based on a double value in the range [0...1]. - *

- * The implementation must fire change events when the minimum and maximum ranges - * are modified, NOT when the actual modified value changes. - * - * @author Sampo Niskanen - */ -public interface SimulationModifier extends ChangeSource { - - /** - * Return a short name describing this modifier. - * @return a name describing this modifier. - */ - public String getName(); - - /** - * Return a longer description describing this modifiers. - * @return a description of the modifier. - */ - public String getDescription(); - - /** - * Return the object this modifier is related to. This is for example the - * rocket component this modifier is modifying. This object can be used by a - * UI to group related modifiers. - * - * @return the object this modifier is related to, or null. - */ - public Object getRelatedObject(); - - - /** - * Return the current value of the modifier in SI units. - * @return the current value of this parameter in SI units. - * @throws OptimizationException if fetching the current value fails - */ - public double getCurrentSIValue(Simulation simulation) throws OptimizationException; - - - /** - * Return the minimum value (corresponding to scaled value 0) in SI units. - * @return the value corresponding to scaled value 0. - */ - public double getMinValue(); - - /** - * Set the minimum value (corresponding to scaled value 0) in SI units. - * @param value the value corresponding to scaled value 0. - */ - public void setMinValue(double value); - - - /** - * Return the maximum value (corresponding to scaled value 1) in SI units. - * @return the value corresponding to scaled value 1. - */ - public double getMaxValue(); - - /** - * Set the maximum value (corresponding to scaled value 1) in SI units. - * @param value the value corresponding to scaled value 1. - */ - public void setMaxValue(double value); - - - /** - * Return the unit group used for the values returned by {@link #getCurrentSIValue(Simulation)} etc. - * @return the unit group - */ - public UnitGroup getUnitGroup(); - - - /** - * Return the current scaled value. This is normally within the range [0...1], but - * can be outside the range if the current value is outside of the min and max values. - * - * @return the current value of this parameter (normally between [0 ... 1]) - * @throws OptimizationException if fetching the current value fails - */ - public double getCurrentScaledValue(Simulation simulation) throws OptimizationException; - - - - /** - * Modify the specified simulation to the corresponding parameter value. - * - * @param simulation the simulation to modify - * @param scaledValue the scaled value in the range [0...1] - * @throws OptimizationException if the modification fails - */ - public void modify(Simulation simulation, double scaledValue) throws OptimizationException; - - - /** - * Compare whether this SimulationModifier is equivalent to another simulation modifier. - * "Equivalent" means that the simulation modifier corresponds to the same modification in - * another rocket instance (e.g. the same modification on another rocket component that - * has the same component ID). - */ - public boolean equals(Object obj); -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/domains/IdentitySimulationDomain.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/domains/IdentitySimulationDomain.java deleted file mode 100644 index fac678ea..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/domains/IdentitySimulationDomain.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.domains; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.rocketoptimization.SimulationDomain; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.Pair; - -/** - * A simulation domain that includes all points in the domain. - * - * @author Sampo Niskanen - */ -public class IdentitySimulationDomain implements SimulationDomain { - - @Override - public Pair getDistanceToDomain(Simulation simulation) { - return new Pair(-1.0, null); - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/domains/StabilityDomain.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/domains/StabilityDomain.java deleted file mode 100644 index 631b45c9..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/domains/StabilityDomain.java +++ /dev/null @@ -1,139 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.domains; - -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.optimization.rocketoptimization.SimulationDomain; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Pair; - -/** - * A simulation domain that limits the required stability of the rocket. - * - * @author Sampo Niskanen - */ -public class StabilityDomain implements SimulationDomain { - - private final double minimum; - private final boolean minAbsolute; - private final double maximum; - private final boolean maxAbsolute; - - - /** - * Sole constructor. - * - * @param minimum minimum stability requirement (or NaN for no limit) - * @param minAbsolute true if minimum is an absolute SI measurement, - * false if it is relative to the rocket caliber - * @param maximum maximum stability requirement (or NaN for no limit) - * @param maxAbsolute true if maximum is an absolute SI measurement, - * false if it is relative to the rocket caliber - */ - public StabilityDomain(double minimum, boolean minAbsolute, double maximum, boolean maxAbsolute) { - super(); - this.minimum = minimum; - this.minAbsolute = minAbsolute; - this.maximum = maximum; - this.maxAbsolute = maxAbsolute; - } - - - - - @Override - public Pair getDistanceToDomain(Simulation simulation) { - Coordinate cp, cg; - double cpx, cgx; - double absolute; - double relative; - - /* - * These are instantiated each time because this class must be thread-safe. - * Caching would in any case be inefficient since the rocket changes all the time. - */ - AerodynamicCalculator aerodynamicCalculator = new BarrowmanCalculator(); - MassCalculator massCalculator = new BasicMassCalculator(); - - - Configuration configuration = simulation.getConfiguration(); - FlightConditions conditions = new FlightConditions(configuration); - conditions.setMach(Application.getPreferences().getDefaultMach()); - conditions.setAOA(0); - conditions.setRollRate(0); - - // TODO: HIGH: This re-calculates the worst theta value every time - cp = aerodynamicCalculator.getWorstCP(configuration, conditions, null); - cg = massCalculator.getCG(configuration, MassCalcType.LAUNCH_MASS); - - if (cp.weight > 0.000001) - cpx = cp.x; - else - cpx = Double.NaN; - - if (cg.weight > 0.000001) - cgx = cg.x; - else - cgx = Double.NaN; - - - // Calculate the reference (absolute or relative) - absolute = cpx - cgx; - - double diameter = 0; - for (RocketComponent c : configuration) { - if (c instanceof SymmetricComponent) { - double d1 = ((SymmetricComponent) c).getForeRadius() * 2; - double d2 = ((SymmetricComponent) c).getAftRadius() * 2; - diameter = MathUtil.max(diameter, d1, d2); - } - } - relative = absolute / diameter; - - - Value desc; - if (minAbsolute && maxAbsolute) { - desc = new Value(absolute, UnitGroup.UNITS_LENGTH); - } else { - desc = new Value(relative, UnitGroup.UNITS_STABILITY_CALIBERS); - } - - double ref; - if (minAbsolute) { - ref = minimum - absolute; - if (ref > 0) { - return new Pair(ref, desc); - } - } else { - ref = minimum - relative; - if (ref > 0) { - return new Pair(ref, desc); - } - } - - if (maxAbsolute) { - ref = absolute - maximum; - if (ref > 0) { - return new Pair(ref, desc); - } - } else { - ref = relative - maximum; - if (ref > 0) { - return new Pair(ref, desc); - } - } - - return new Pair(0.0, desc); - } -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/MaximizationGoal.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/MaximizationGoal.java deleted file mode 100644 index e9576eea..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/MaximizationGoal.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.goals; - -import net.sf.openrocket.optimization.rocketoptimization.OptimizationGoal; - -/** - * An optimization goal that maximizes a function value. The method simply - * returns the opposite of the function value. - * - * @author Sampo Niskanen - */ -public class MaximizationGoal implements OptimizationGoal { - - @Override - public double getMinimizationParameter(double value) { - return -value; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/MinimizationGoal.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/MinimizationGoal.java deleted file mode 100644 index c6f8fc60..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/MinimizationGoal.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.goals; - -import net.sf.openrocket.optimization.rocketoptimization.OptimizationGoal; - -/** - * An optimization goal that minimizes a function value. The method simply - * returns the function value. - * - * @author Sampo Niskanen - */ -public class MinimizationGoal implements OptimizationGoal { - - @Override - public double getMinimizationParameter(double value) { - return value; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/ValueSeekGoal.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/ValueSeekGoal.java deleted file mode 100644 index 34d433ab..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/goals/ValueSeekGoal.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.goals; - -import net.sf.openrocket.optimization.rocketoptimization.OptimizationGoal; - - -/** - * An optimization goal that seeks for a specific function value. - * The method returns the Euclidic distance from the desired value. - * - * @author Sampo Niskanen - */ -public class ValueSeekGoal implements OptimizationGoal { - - private final double goal; - - /** - * Sole constructor. - * - * @param goal the function value to optimize towards. - */ - public ValueSeekGoal(double goal) { - this.goal = goal; - } - - @Override - public double getMinimizationParameter(double value) { - return Math.abs(value - goal); - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/AbstractSimulationModifier.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/AbstractSimulationModifier.java deleted file mode 100644 index 1d8c0fd1..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/AbstractSimulationModifier.java +++ /dev/null @@ -1,211 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.modifiers; - -import java.util.ArrayList; -import java.util.EventListener; -import java.util.EventObject; -import java.util.List; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.StateChangeListener; - -/** - * An abstract implementation of the SimulationModifier interface. An implementation - * needs only to implement the {@link #getCurrentSIValue(Simulation)} and - * {@link #modify(net.sf.openrocket.document.Simulation, double)} methods. - * - * @author Sampo Niskanen - */ -public abstract class AbstractSimulationModifier implements SimulationModifier { - - private final String name; - private final String description; - private final Object relatedObject; - private final UnitGroup unitGroup; - - private double minValue = 0.0; - private double maxValue = 1.0; - - private final List listeners = new ArrayList(); - - - /** - * Sole constructor. - * - * @param modifierName the name of this modifier (returned by {@link #getName()}) - * @param modifierDescription the description of this modifier (returned by {@link #getDescription()}) - * @param relatedObject the related object (returned by {@link #getRelatedObject()}) - * @param unitGroup the unit group (returned by {@link #getUnitGroup()}) - */ - public AbstractSimulationModifier(String modifierName, String modifierDescription, Object relatedObject, - UnitGroup unitGroup) { - this.name = modifierName; - this.description = modifierDescription; - this.relatedObject = relatedObject; - this.unitGroup = unitGroup; - - if (this.name == null || this.description == null || this.relatedObject == null || this.unitGroup == null) { - throw new IllegalArgumentException("null value provided:" + - " name=" + this.name + " description=" + description + " relatedObject=" + relatedObject + - " unitGroup=" + unitGroup); - } - } - - - @Override - public String getName() { - return name; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public Object getRelatedObject() { - return relatedObject; - } - - @Override - public double getCurrentScaledValue(Simulation simulation) throws OptimizationException { - double value = getCurrentSIValue(simulation); - return toScaledValue(value); - } - - - - /** - * Returns the scaled value (normally within [0...1]). If the min...max range is singular, - * this method returns 0.0, 1.0 or 0.5 depending on whether the value is less than, - * greater than or equal to the limit. - * - * @param value the value in SI units - * @return the value in scaled range (normally within [0...1]) - */ - protected double toScaledValue(double value) { - if (MathUtil.equals(minValue, maxValue)) { - if (value > maxValue) - return 1.0; - if (value < minValue) - return 0.0; - return 0.5; - } - - return MathUtil.map(value, minValue, maxValue, 0.0, 1.0); - } - - - /** - * Returns the base value (in SI units). - * - * @param value the value in scaled range (normally within [0...1]) - * @return the value in SI units - */ - protected double toBaseValue(double value) { - return MathUtil.map(value, 0.0, 1.0, minValue, maxValue); - } - - - - @Override - public double getMinValue() { - return minValue; - } - - @Override - public void setMinValue(double value) { - if (MathUtil.equals(minValue, value)) - return; - this.minValue = value; - if (maxValue < minValue) - maxValue = minValue; - fireChangeEvent(); - } - - @Override - public double getMaxValue() { - return maxValue; - } - - @Override - public void setMaxValue(double value) { - if (MathUtil.equals(maxValue, value)) - return; - this.maxValue = value; - if (minValue > maxValue) - minValue = maxValue; - fireChangeEvent(); - } - - @Override - public UnitGroup getUnitGroup() { - return unitGroup; - } - - - @Override - public void addChangeListener(EventListener listener) { - listeners.add(listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - listeners.remove(listener); - } - - - /** - * Fire a change event to the listeners. - */ - protected void fireChangeEvent() { - EventObject event = new EventObject(this); - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] list = listeners.toArray(new EventListener[0]); - for (EventListener l : list) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(event); - } - } - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - - AbstractSimulationModifier other = (AbstractSimulationModifier) obj; - if (!this.description.equals(other.description)) - return false; - if (!this.name.equals(other.name)) - return false; - if (!this.relatedObject.equals(other.relatedObject)) - return false; - if (!this.unitGroup.equals(other.unitGroup)) - return false; - - return true; - } - - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (description.hashCode()); - result = prime * result + (name.hashCode()); - result = prime * result + (relatedObject.hashCode()); - result = prime * result + (unitGroup.hashCode()); - return result; - } - - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericComponentModifier.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericComponentModifier.java deleted file mode 100644 index bd80889a..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericComponentModifier.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.modifiers; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.unit.UnitGroup; - -/** - * A generic simulation modifier that modifies a value of a certain RocketComponent - * based on the component's ID and the value name. - * - * @author Sampo Niskanen - */ -public class GenericComponentModifier extends GenericModifier { - - private final Class componentClass; - private final String componentId; - - /** - * Sole constructor. - * - * @param modifierName the name of this modifier (returned by {@link #getName()}) - * @param modifierDescription the description of this modifier (returned by {@link #getDescription()}) - * @param relatedObject the related object (returned by {@link #getRelatedObject()}) - * @param unitGroup the unit group (returned by {@link #getUnitGroup()}) - * @param multiplier the multiplier by which the value returned by the getter is multiplied - * to obtain the desired value - * @param componentClass the RocketComponent class type that is being modified - * @param componentId the ID of the component to modify - * @param methodName the base name of the getter/setter methods (without "get"/"set") - */ - public GenericComponentModifier(String modifierName, String modifierDescription, Object relatedObject, UnitGroup unitGroup, - double multiplier, Class componentClass, String componentId, String methodName) { - super(modifierName, modifierDescription, relatedObject, unitGroup, multiplier, componentClass, methodName); - - this.componentClass = componentClass; - this.componentId = componentId; - } - - @Override - protected RocketComponent getModifiedObject(Simulation simulation) throws OptimizationException { - RocketComponent c = simulation.getRocket().findComponent(componentId); - if (c == null) { - throw new OptimizationException("Could not find component of type " + componentClass.getSimpleName() - + " with correct ID"); - } - return c; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java deleted file mode 100644 index b5e2eaee..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java +++ /dev/null @@ -1,108 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.modifiers; - -import java.util.Locale; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Reflection.Method; - -/** - * A generic SimulationModifier that uses reflection to get and set a double value. - * Implementations need to implement the {@link #getModifiedObject(Simulation)} method - * to return which object is modified. - * - * @author Sampo Niskanen - */ -public abstract class GenericModifier extends AbstractSimulationModifier { - private static final LogHelper log = Application.getLogger(); - - private final double multiplier; - - private final Class modifiedClass; - private final String methodName; - - private final Method getter; - private final Method setter; - - - /** - * Sole constructor. - * - * @param modifierName the name of this modifier (returned by {@link #getName()}) - * @param modifierDescription the description of this modifier (returned by {@link #getDescription()}) - * @param relatedObject the related object (returned by {@link #getRelatedObject()}) - * @param unitGroup the unit group (returned by {@link #getUnitGroup()}) - * @param multiplier the multiplier by which the value returned by the getter is multiplied - * to obtain the desired value - * @param modifiedClass the class type that {@link #getModifiedObject(Simulation)} returns - * @param methodName the base name of the getter/setter methods (without "get"/"set") - */ - public GenericModifier(String modifierName, String modifierDescription, Object relatedObject, UnitGroup unitGroup, - double multiplier, Class modifiedClass, String methodName) { - super(modifierName, modifierDescription, relatedObject, unitGroup); - this.multiplier = multiplier; - - this.modifiedClass = modifiedClass; - this.methodName = methodName; - - if (MathUtil.equals(multiplier, 0)) { - throw new IllegalArgumentException("multiplier is zero"); - } - - try { - methodName = methodName.substring(0, 1).toUpperCase(Locale.ENGLISH) + methodName.substring(1); - getter = new Method(modifiedClass.getMethod("get" + methodName)); - setter = new Method(modifiedClass.getMethod("set" + methodName, double.class)); - } catch (SecurityException e) { - throw new BugException("Trying to find method get/set" + methodName + " in class " + modifiedClass, e); - } catch (NoSuchMethodException e) { - throw new BugException("Trying to find method get/set" + methodName + " in class " + modifiedClass, e); - } - } - - - - @Override - public double getCurrentSIValue(Simulation simulation) throws OptimizationException { - T modifiable = getModifiedObject(simulation); - if (modifiable == null) { - throw new OptimizationException("BUG: getModifiedObject() returned null"); - } - return ((Double) getter.invoke(modifiable)) * multiplier; - } - - - @Override - public void modify(Simulation simulation, double scaledValue) throws OptimizationException { - T modifiable = getModifiedObject(simulation); - if (modifiable == null) { - throw new OptimizationException("BUG: getModifiedObject() returned null"); - } - double siValue = toBaseValue(scaledValue) / multiplier; - log.verbose("Setting setter=" + setter + " modifiable=" + modifiable + " siValue=" + siValue + "scaledValue=" + scaledValue); - setter.invoke(modifiable, siValue); - } - - - /** - * Return the object from the simulation that will be modified. - * @param simulation the simulation - * @return the object to modify - * - * @throws OptimizationException if the object cannot be found - */ - protected abstract T getModifiedObject(Simulation simulation) throws OptimizationException; - - - - @Override - public String toString() { - return "GenericModifier[modifiedClass=" + modifiedClass.getCanonicalName() + ", methodName=" + methodName + ", multiplier=" + multiplier + "]"; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/DeploymentVelocityParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/DeploymentVelocityParameter.java deleted file mode 100644 index 0add6648..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/DeploymentVelocityParameter.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.system.RecoveryDeviceDeploymentEndListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the total flight time. - * - * @author Sampo Niskanen - */ -public class DeploymentVelocityParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected SimulationListener[] getSimulationListeners() { - return new SimulationListener[] { new RecoveryDeviceDeploymentEndListener() }; - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getLast(FlightDataType.TYPE_VELOCITY_TOTAL); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_VELOCITY; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/GroundHitVelocityParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/GroundHitVelocityParameter.java deleted file mode 100644 index 4effe72b..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/GroundHitVelocityParameter.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the speed the rocket hits the ground. - * - * @author Sampo Niskanen - */ -public class GroundHitVelocityParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getLast(FlightDataType.TYPE_VELOCITY_TOTAL); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_VELOCITY; - } - - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/LandingDistanceParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/LandingDistanceParameter.java deleted file mode 100644 index cb387d71..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/LandingDistanceParameter.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the distance where a rocket lands. - * - * @author Sampo Niskanen - */ -public class LandingDistanceParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getLast(FlightDataType.TYPE_POSITION_XY); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_DISTANCE; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumAccelerationParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumAccelerationParameter.java deleted file mode 100644 index eb6e7a61..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumAccelerationParameter.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the maximum acceleration during a simulated flight. - * - * @author Sampo Niskanen - */ -public class MaximumAccelerationParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected SimulationListener[] getSimulationListeners() { - return new SimulationListener[] { new ApogeeEndListener() }; - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getMaximum(FlightDataType.TYPE_ACCELERATION_TOTAL); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_ACCELERATION; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumAltitudeParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumAltitudeParameter.java deleted file mode 100644 index f427d7fc..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumAltitudeParameter.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the maximum altitude of a simulated flight. - * - * @author Sampo Niskanen - */ -public class MaximumAltitudeParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected SimulationListener[] getSimulationListeners() { - return new SimulationListener[] { new ApogeeEndListener() }; - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getMaximum(FlightDataType.TYPE_ALTITUDE); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_DISTANCE; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumVelocityParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumVelocityParameter.java deleted file mode 100644 index 3062e4b8..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/MaximumVelocityParameter.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the maximum velocity during a simulated flight. - * - * @author Sampo Niskanen - */ -public class MaximumVelocityParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected SimulationListener[] getSimulationListeners() { - return new SimulationListener[] { new ApogeeEndListener() }; - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getMaximum(FlightDataType.TYPE_VELOCITY_TOTAL); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_VELOCITY; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/SimulationBasedParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/SimulationBasedParameter.java deleted file mode 100644 index e814dd30..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/SimulationBasedParameter.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import java.util.Arrays; - -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.exception.MotorIgnitionException; -import net.sf.openrocket.simulation.exception.SimulationCalculationException; -import net.sf.openrocket.simulation.exception.SimulationCancelledException; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.exception.SimulationLaunchException; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.simulation.listeners.system.InterruptListener; -import net.sf.openrocket.startup.Application; - -/** - * An abstract optimization parameter that simulates a rocket flight and obtains - * a value from the simulation result. - * - * @author Sampo Niskanen - */ -public abstract class SimulationBasedParameter implements OptimizableParameter { - - private static final LogHelper log = Application.getLogger(); - - @Override - public double computeValue(Simulation simulation) throws OptimizationException, InterruptedException { - try { - log.debug("Running simulation for " + getName()); - - SimulationListener[] listeners = getSimulationListeners(); - listeners = Arrays.copyOf(listeners, listeners.length + 1); - listeners[listeners.length - 1] = new InterruptListener(); - simulation.simulate(listeners); - - double value = getResultValue(simulation.getSimulatedData()); - log.debug("Parameter '" + getName() + " was " + value); - return value; - } catch (MotorIgnitionException e) { - // A problem with motor ignition will cause optimization to fail - throw new OptimizationException(e); - } catch (SimulationLaunchException e) { - // Other launch exceptions result in illegal value - return Double.NaN; - } catch (SimulationCalculationException e) { - // Calculation errors result in illegal value - return Double.NaN; - } catch (SimulationCancelledException e) { - // Simulation cancellation stops the optimization - throw (InterruptedException) new InterruptedException("Optimization was interrupted").initCause(e); - } catch (SimulationException e) { - // Other exceptions fail - throw new OptimizationException(e); - } - } - - - /** - * Return the optimization parameter from the simulation flight data. - * - * @param simulatedData the simulated data. - * @return the optimization parameter. - */ - protected abstract double getResultValue(FlightData simulatedData); - - /** - * Return an array of simulation listeners to provide to the simulation. - * This may include a listener that stops the simulation after the necessary value - * has been computed. - *

- * This array should NOT contain InterruptListener, it will be added implicitly. - * - * @return an array of simulation listeners to include. - */ - protected SimulationListener[] getSimulationListeners() { - return new SimulationListener[0]; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/StabilityParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/StabilityParameter.java deleted file mode 100644 index 1d46f753..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/StabilityParameter.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -/** - * An optimization parameter that computes either the absolute or relative stability of a rocket. - * - * @author Sampo Niskanen - */ -public class StabilityParameter implements OptimizableParameter { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - private final boolean absolute; - - public StabilityParameter(boolean absolute) { - this.absolute = absolute; - } - - - @Override - public String getName() { - return trans.get("name") + " (" + getUnitGroup().getDefaultUnit().getUnit() + ")"; - } - - @Override - public double computeValue(Simulation simulation) throws OptimizationException { - Coordinate cp, cg; - double cpx, cgx; - double stability; - - log.debug("Calculating stability of simulation, absolute=" + absolute); - - /* - * These are instantiated each time because this class must be thread-safe. - * Caching would in any case be inefficient since the rocket changes all the time. - */ - AerodynamicCalculator aerodynamicCalculator = new BarrowmanCalculator(); - MassCalculator massCalculator = new BasicMassCalculator(); - - - Configuration configuration = simulation.getConfiguration(); - FlightConditions conditions = new FlightConditions(configuration); - conditions.setMach(Application.getPreferences().getDefaultMach()); - conditions.setAOA(0); - conditions.setRollRate(0); - - cp = aerodynamicCalculator.getWorstCP(configuration, conditions, null); - cg = massCalculator.getCG(configuration, MassCalcType.LAUNCH_MASS); - - if (cp.weight > 0.000001) - cpx = cp.x; - else - cpx = Double.NaN; - - if (cg.weight > 0.000001) - cgx = cg.x; - else - cgx = Double.NaN; - - - // Calculate the reference (absolute or relative) - stability = cpx - cgx; - - if (!absolute) { - double diameter = 0; - for (RocketComponent c : configuration) { - if (c instanceof SymmetricComponent) { - double d1 = ((SymmetricComponent) c).getForeRadius() * 2; - double d2 = ((SymmetricComponent) c).getAftRadius() * 2; - diameter = MathUtil.max(diameter, d1, d2); - } - } - stability = stability / diameter; - } - - log.debug("Resulting stability is " + stability + ", absolute=" + absolute); - - return stability; - } - - @Override - public UnitGroup getUnitGroup() { - if (absolute) { - return UnitGroup.UNITS_LENGTH; - } else { - return UnitGroup.UNITS_STABILITY_CALIBERS; - } - } - -} diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/TotalFlightTimeParameter.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/TotalFlightTimeParameter.java deleted file mode 100644 index 560227a2..00000000 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/parameters/TotalFlightTimeParameter.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.parameters; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * An optimization parameter that computes the total flight time. - * - * @author Sampo Niskanen - */ -public class TotalFlightTimeParameter extends SimulationBasedParameter { - - private static final Translator trans = Application.getTranslator(); - - @Override - public String getName() { - return trans.get("name"); - } - - @Override - protected double getResultValue(FlightData simulatedData) { - return simulatedData.getBranch(0).getLast(FlightDataType.TYPE_TIME); - } - - @Override - public UnitGroup getUnitGroup() { - return UnitGroup.UNITS_FLIGHT_TIME; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/services/DefaultOptimizableParameterService.java b/core/src/net/sf/openrocket/optimization/services/DefaultOptimizableParameterService.java deleted file mode 100644 index 7eadfb6a..00000000 --- a/core/src/net/sf/openrocket/optimization/services/DefaultOptimizableParameterService.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.optimization.services; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.DeploymentVelocityParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.GroundHitVelocityParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.LandingDistanceParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.MaximumAccelerationParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.MaximumAltitudeParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.MaximumVelocityParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.StabilityParameter; -import net.sf.openrocket.optimization.rocketoptimization.parameters.TotalFlightTimeParameter; - -/** - * Default implementation for optimization parameter service. - * - * @author Sampo Niskanen - */ -public class DefaultOptimizableParameterService implements OptimizableParameterService { - - @Override - public Collection getParameters(OpenRocketDocument document) { - List list = new ArrayList(); - - list.add(new MaximumAltitudeParameter()); - list.add(new MaximumVelocityParameter()); - list.add(new MaximumAccelerationParameter()); - list.add(new StabilityParameter(false)); - list.add(new StabilityParameter(true)); - list.add(new GroundHitVelocityParameter()); - list.add(new LandingDistanceParameter()); - list.add(new TotalFlightTimeParameter()); - list.add(new DeploymentVelocityParameter()); - - return list; - } - -} diff --git a/core/src/net/sf/openrocket/optimization/services/DefaultSimulationModifierService.java b/core/src/net/sf/openrocket/optimization/services/DefaultSimulationModifierService.java deleted file mode 100644 index cf77e3c5..00000000 --- a/core/src/net/sf/openrocket/optimization/services/DefaultSimulationModifierService.java +++ /dev/null @@ -1,330 +0,0 @@ -package net.sf.openrocket.optimization.services; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.optimization.rocketoptimization.modifiers.GenericComponentModifier; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.InternalComponent; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RecoveryDevice.DeployEvent; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Reflection; -import net.sf.openrocket.util.Reflection.Method; - -public class DefaultSimulationModifierService implements SimulationModifierService { - - private static final Translator trans = Application.getTranslator(); - - private static final double DEFAULT_RANGE_MULTIPLIER = 2.0; - - - private static final Map, List> definitions = new HashMap, List>(); - static { - //addModifier("optimization.modifier.", unitGroup, multiplier, componentClass, methodName); - - /* - * Note: Each component type must contain only mutually exclusive variables. - * For example, body tube does not have inner diameter definition because it is - * defined by the outer diameter and thickness. - */ - - addModifier("optimization.modifier.nosecone.length", UnitGroup.UNITS_LENGTH, 1.0, NoseCone.class, "Length"); - addModifier("optimization.modifier.nosecone.diameter", UnitGroup.UNITS_LENGTH, 2.0, NoseCone.class, "AftRadius", "isAftRadiusAutomatic"); - addModifier("optimization.modifier.nosecone.thickness", UnitGroup.UNITS_LENGTH, 1.0, NoseCone.class, "Thickness", "isFilled"); - - addModifier("optimization.modifier.transition.length", UnitGroup.UNITS_LENGTH, 1.0, Transition.class, "Length"); - addModifier("optimization.modifier.transition.forediameter", UnitGroup.UNITS_LENGTH, 2.0, Transition.class, "ForeRadius", "isForeRadiusAutomatic"); - addModifier("optimization.modifier.transition.aftdiameter", UnitGroup.UNITS_LENGTH, 2.0, Transition.class, "AftRadius", "isAftRadiusAutomatic"); - addModifier("optimization.modifier.transition.thickness", UnitGroup.UNITS_LENGTH, 1.0, Transition.class, "Thickness", "isFilled"); - - addModifier("optimization.modifier.bodytube.length", UnitGroup.UNITS_LENGTH, 1.0, BodyTube.class, "Length"); - addModifier("optimization.modifier.bodytube.outerDiameter", UnitGroup.UNITS_LENGTH, 2.0, BodyTube.class, "OuterRadius", "isOuterRadiusAutomatic"); - addModifier("optimization.modifier.bodytube.thickness", UnitGroup.UNITS_LENGTH, 1.0, BodyTube.class, "Thickness", "isFilled"); - - addModifier("optimization.modifier.trapezoidfinset.rootChord", UnitGroup.UNITS_LENGTH, 1.0, TrapezoidFinSet.class, "RootChord"); - addModifier("optimization.modifier.trapezoidfinset.tipChord", UnitGroup.UNITS_LENGTH, 1.0, TrapezoidFinSet.class, "TipChord"); - addModifier("optimization.modifier.trapezoidfinset.sweep", UnitGroup.UNITS_LENGTH, 1.0, TrapezoidFinSet.class, "Sweep"); - addModifier("optimization.modifier.trapezoidfinset.height", UnitGroup.UNITS_LENGTH, 1.0, TrapezoidFinSet.class, "Height"); - addModifier("optimization.modifier.finset.cant", UnitGroup.UNITS_ANGLE, 1.0, TrapezoidFinSet.class, "CantAngle"); - - addModifier("optimization.modifier.ellipticalfinset.length", UnitGroup.UNITS_LENGTH, 1.0, EllipticalFinSet.class, "Length"); - addModifier("optimization.modifier.ellipticalfinset.height", UnitGroup.UNITS_LENGTH, 1.0, EllipticalFinSet.class, "Height"); - addModifier("optimization.modifier.finset.cant", UnitGroup.UNITS_ANGLE, 1.0, EllipticalFinSet.class, "CantAngle"); - - addModifier("optimization.modifier.finset.cant", UnitGroup.UNITS_ANGLE, 1.0, FreeformFinSet.class, "CantAngle"); - - addModifier("optimization.modifier.launchlug.length", UnitGroup.UNITS_LENGTH, 1.0, LaunchLug.class, "Length"); - addModifier("optimization.modifier.launchlug.outerDiameter", UnitGroup.UNITS_LENGTH, 2.0, LaunchLug.class, "OuterRadius"); - addModifier("optimization.modifier.launchlug.thickness", UnitGroup.UNITS_LENGTH, 1.0, LaunchLug.class, "Thickness"); - - - addModifier("optimization.modifier.masscomponent.mass", UnitGroup.UNITS_MASS, 1.0, MassComponent.class, "ComponentMass"); - - addModifier("optimization.modifier.parachute.diameter", UnitGroup.UNITS_LENGTH, 1.0, Parachute.class, "Diameter"); - addModifier("optimization.modifier.parachute.coefficient", UnitGroup.UNITS_NONE, 1.0, Parachute.class, "CD"); - - addModifier("optimization.modifier.streamer.length", UnitGroup.UNITS_LENGTH, 1.0, Streamer.class, "StripLength"); - addModifier("optimization.modifier.streamer.width", UnitGroup.UNITS_LENGTH, 1.0, Streamer.class, "StripWidth"); - addModifier("optimization.modifier.streamer.aspectRatio", UnitGroup.UNITS_NONE, 1.0, Streamer.class, "AspectRatio"); - addModifier("optimization.modifier.streamer.coefficient", UnitGroup.UNITS_NONE, 1.0, Streamer.class, "CD", "isCDAutomatic"); - - } - - private static void addModifier(String modifierNameKey, UnitGroup unitGroup, double multiplier, - Class componentClass, String methodName) { - addModifier(modifierNameKey, unitGroup, multiplier, componentClass, methodName, null); - } - - private static void addModifier(String modifierNameKey, UnitGroup unitGroup, double multiplier, - Class componentClass, String methodName, String autoMethod) { - - String modifierDescriptionKey = modifierNameKey + ".desc"; - - List list = definitions.get(componentClass); - if (list == null) { - list = new ArrayList(); - definitions.put(componentClass, list); - } - - ModifierDefinition definition = new ModifierDefinition(modifierNameKey, modifierDescriptionKey, unitGroup, - multiplier, componentClass, methodName, autoMethod); - list.add(definition); - } - - - - - @Override - public Collection getModifiers(OpenRocketDocument document) { - List modifiers = new ArrayList(); - - Rocket rocket = document.getRocket(); - - // Simulation is used to calculate default min/max values - Simulation simulation = new Simulation(rocket); - simulation.getConfiguration().setMotorConfigurationID(null); - - for (RocketComponent c : rocket) { - - // Attribute modifiers - List list = definitions.get(c.getClass()); - if (list != null) { - for (ModifierDefinition def : list) { - - // Ignore modifier if value is set to automatic - if (def.autoMethod != null) { - Method m = Reflection.findMethod(c.getClass(), def.autoMethod); - if ((Boolean) m.invoke(c)) { - continue; - } - } - - SimulationModifier mod = new GenericComponentModifier( - trans.get(def.modifierNameKey), trans.get(def.modifierDescriptionKey), c, def.unitGroup, - def.multiplier, def.componentClass, c.getID(), def.methodName); - setDefaultMinMax(mod, simulation); - modifiers.add(mod); - } - } - - - // Add override modifiers if mass/CG is overridden - if (c.isMassOverridden()) { - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.rocketcomponent.overrideMass"), - trans.get("optimization.modifier.rocketcomponent.overrideMass.desc"), - c, UnitGroup.UNITS_MASS, - 1.0, c.getClass(), c.getID(), "OverrideMass"); - setDefaultMinMax(mod, simulation); - modifiers.add(mod); - } - if (c.isCGOverridden()) { - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.rocketcomponent.overrideCG"), - trans.get("optimization.modifier.rocketcomponent.overrideCG.desc"), - c, UnitGroup.UNITS_LENGTH, - 1.0, c.getClass(), c.getID(), "OverrideCGX"); - mod.setMinValue(0); - mod.setMaxValue(c.getLength()); - modifiers.add(mod); - } - - - // Conditional motor mount parameters - if (c instanceof MotorMount) { - MotorMount mount = (MotorMount) c; - if (mount.isMotorMount()) { - - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.motormount.overhang"), - trans.get("optimization.modifier.motormount.overhang.desc"), - c, UnitGroup.UNITS_LENGTH, - 1.0, c.getClass(), c.getID(), "MotorOverhang"); - setDefaultMinMax(mod, simulation); - modifiers.add(mod); - - mod = new GenericComponentModifier( - trans.get("optimization.modifier.motormount.delay"), - trans.get("optimization.modifier.motormount.delay.desc"), - c, UnitGroup.UNITS_SHORT_TIME, - 1.0, c.getClass(), c.getID(), "IgnitionDelay"); - mod.setMinValue(0); - mod.setMaxValue(5); - modifiers.add(mod); - - } - } - - - // Inner component positioning - if (c instanceof InternalComponent) { - RocketComponent parent = c.getParent(); - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.internalcomponent.position"), - trans.get("optimization.modifier.internalcomponent.position.desc"), - c, UnitGroup.UNITS_LENGTH, - 1.0, c.getClass(), c.getID(), "PositionValue"); - mod.setMinValue(0); - mod.setMaxValue(parent.getLength()); - modifiers.add(mod); - } - - - // Custom min/max for fin set position - if (c instanceof FinSet) { - RocketComponent parent = c.getParent(); - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.finset.position"), - trans.get("optimization.modifier.finset.position.desc"), - c, UnitGroup.UNITS_LENGTH, - 1.0, c.getClass(), c.getID(), "PositionValue"); - mod.setMinValue(0); - mod.setMaxValue(parent.getLength()); - modifiers.add(mod); - } - - - // Custom min/max for launch lug position - if (c instanceof LaunchLug) { - RocketComponent parent = c.getParent(); - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.launchlug.position"), - trans.get("optimization.modifier.launchlug.position.desc"), - c, UnitGroup.UNITS_LENGTH, - 1.0, c.getClass(), c.getID(), "PositionValue"); - mod.setMinValue(0); - mod.setMaxValue(parent.getLength()); - modifiers.add(mod); - } - - - // Recovery device deployment altitude and delay - if (c instanceof RecoveryDevice) { - RecoveryDevice device = (RecoveryDevice) c; - - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier.recoverydevice.deployDelay"), - trans.get("optimization.modifier.recoverydevice.deployDelay.desc"), - c, UnitGroup.UNITS_SHORT_TIME, - 1.0, c.getClass(), c.getID(), "DeployDelay"); - mod.setMinValue(0); - mod.setMaxValue(10); - modifiers.add(mod); - - if (device.getDeployEvent() == DeployEvent.ALTITUDE) { - mod = new GenericComponentModifier( - trans.get("optimization.modifier.recoverydevice.deployAltitude"), - trans.get("optimization.modifier.recoverydevice.deployAltitude.desc"), - c, UnitGroup.UNITS_DISTANCE, - 1.0, c.getClass(), c.getID(), "DeployAltitude"); - setDefaultMinMax(mod, simulation); - modifiers.add(mod); - } - } - - - // Conditional shape parameter of Transition - if (c instanceof Transition) { - Transition transition = (Transition) c; - Transition.Shape shape = transition.getType(); - if (shape.usesParameter()) { - SimulationModifier mod = new GenericComponentModifier( - trans.get("optimization.modifier." + c.getClass().getSimpleName().toLowerCase(Locale.ENGLISH) + ".shapeparameter"), - trans.get("optimization.modifier." + c.getClass().getSimpleName().toLowerCase(Locale.ENGLISH) + ".shapeparameter.desc"), - c, UnitGroup.UNITS_NONE, - 1.0, c.getClass(), c.getID(), "ShapeParameter"); - mod.setMinValue(shape.minParameter()); - mod.setMaxValue(shape.maxParameter()); - modifiers.add(mod); - } - } - } - - return modifiers; - } - - - private void setDefaultMinMax(SimulationModifier mod, Simulation simulation) { - try { - double current = mod.getCurrentSIValue(simulation); - mod.setMinValue(current / DEFAULT_RANGE_MULTIPLIER); - mod.setMaxValue(current * DEFAULT_RANGE_MULTIPLIER); - } catch (OptimizationException e) { - throw new BugException("Simulation modifier threw exception", e); - } - } - - - /* - * String modifierName, Object relatedObject, UnitGroup unitGroup, - double multiplier, Class componentClass, String componentId, String methodName - */ - - private static class ModifierDefinition { - private final String modifierNameKey; - private final String modifierDescriptionKey; - private final UnitGroup unitGroup; - private final double multiplier; - private final Class componentClass; - private final String methodName; - private final String autoMethod; - - - public ModifierDefinition(String modifierNameKey, String modifierDescriptionKey, UnitGroup unitGroup, - double multiplier, Class componentClass, String methodName, String autoMethod) { - this.modifierNameKey = modifierNameKey; - this.modifierDescriptionKey = modifierDescriptionKey; - this.unitGroup = unitGroup; - this.multiplier = multiplier; - this.componentClass = componentClass; - this.methodName = methodName; - this.autoMethod = autoMethod; - } - - } -} diff --git a/core/src/net/sf/openrocket/optimization/services/OptimizableParameterService.java b/core/src/net/sf/openrocket/optimization/services/OptimizableParameterService.java deleted file mode 100644 index d7842e4d..00000000 --- a/core/src/net/sf/openrocket/optimization/services/OptimizableParameterService.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.sf.openrocket.optimization.services; - -import java.util.Collection; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; - -/** - * A service for generating rocket optimization parameters. - * - * @author Sampo Niskanen - */ -public interface OptimizableParameterService { - - /** - * Return all available rocket optimization parameters for this document. - * These should be new instances unless the parameter implementation is stateless. - * - * @param document the design document - * @return a collection of the rocket optimization parameters. - */ - public Collection getParameters(OpenRocketDocument document); - - -} diff --git a/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java b/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java deleted file mode 100644 index ad2d6401..00000000 --- a/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.sf.openrocket.optimization.services; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.ServiceLoader; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; - -public final class OptimizationServiceHelper { - - private OptimizationServiceHelper() { - // Prevent instantiation - } - - /** - * Return the simulation modifiers for an OpenRocketDocument. This queries the - * getModifiers() method from all available services and returns a collection of all - * the modifiers. - * - * @param document the OpenRocketDocument. - * @return a collection of all simulation modifiers applicable to the document. - */ - public static Collection getSimulationModifiers(OpenRocketDocument document) { - List list = new ArrayList(); - - ServiceLoader loader = ServiceLoader.load(SimulationModifierService.class); - for (SimulationModifierService service : loader) { - list.addAll(service.getModifiers(document)); - } - - return list; - } - - - - /** - * Return the optimization parameters for an OpenRocketDocument. This queries the - * getParameters() method from all available services and returns a collection of all - * the modifiers. - * - * @param document the OpenRocketDocument. - * @return a collection of all optimization parameters applicable to the document. - */ - public static Collection getOptimizableParameters(OpenRocketDocument document) { - List list = new ArrayList(); - - ServiceLoader loader = ServiceLoader.load(OptimizableParameterService.class); - for (OptimizableParameterService service : loader) { - list.addAll(service.getParameters(document)); - } - - return list; - } - - -} diff --git a/core/src/net/sf/openrocket/optimization/services/SimulationModifierService.java b/core/src/net/sf/openrocket/optimization/services/SimulationModifierService.java deleted file mode 100644 index 3f386379..00000000 --- a/core/src/net/sf/openrocket/optimization/services/SimulationModifierService.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.optimization.services; - -import java.util.Collection; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; - -/** - * A service for generating simulation modifiers. - * - * @author Sampo Niskanen - */ -public interface SimulationModifierService { - - /** - * Return all available simulation modifiers for this document. - * - * @param document the design document - * @return a collection of the rocket optimization parameters. - */ - public Collection getModifiers(OpenRocketDocument document); - - -} diff --git a/core/src/net/sf/openrocket/plugin/Configurable.java b/core/src/net/sf/openrocket/plugin/Configurable.java deleted file mode 100644 index b8ebf6e2..00000000 --- a/core/src/net/sf/openrocket/plugin/Configurable.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.plugin; - -public interface Configurable { - - - /** - * Return the plugin ID. This is a text string uniquely identifying this plugin. - * The recommended format is similar to the fully-qualified class name of the - * plugin, though a shorter format starting with the developer's domain name - * is also possible for future compatibility. - * - * @return the plugin ID - */ - public String getPluginID(); - - /** - * Test whether this plugin provides functionality corresponding to the specified - * plugin ID. This provides backwards compatibility if the plugin ID should change. - * - * @param pluginID the plugin ID to test - * @return whether this plugin provides the requested functionality - */ - public boolean isCompatible(String pluginID); - - public void loadFromXML(Object... objects); - - public void saveToXML(Object... objects); - -} diff --git a/core/src/net/sf/openrocket/plugin/SwingConfigurator.java b/core/src/net/sf/openrocket/plugin/SwingConfigurator.java deleted file mode 100644 index 86ba323e..00000000 --- a/core/src/net/sf/openrocket/plugin/SwingConfigurator.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.sf.openrocket.plugin; - -import java.awt.Component; - -import net.xeoh.plugins.base.Plugin; - -/** - * Interface that defined a Swing configurator for a plugin. - * The implemeting class should be a plugin that provides the - * capability ":config" where is the - * plugin ID of the plugin to configure. - *

- * - * @param

The plugin class that is being configured - * @author Sampo Niskanen - */ -public interface SwingConfigurator

extends Plugin { - - /** - * Return whether this plugin is configurable or not. - * - * @param plugin the plugin to test. - * @return whether the plugin has a configuration component. - */ - public boolean isConfigurable(P plugin); - - /** - * Return the configuration component for configuring the - * provided plugin. - * - * @param plugin the plugin to configure. - * @return a Swing component for configuring the plugin. - */ - public Component getConfigurationComponent(P plugin); - - -} diff --git a/core/src/net/sf/openrocket/plugin/example/AirStartSimulationExtension.java b/core/src/net/sf/openrocket/plugin/example/AirStartSimulationExtension.java deleted file mode 100644 index 7d14f5fd..00000000 --- a/core/src/net/sf/openrocket/plugin/example/AirStartSimulationExtension.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.plugin.example; - -import java.awt.Component; - -public class AirStartSimulationExtension extends OpenRocketSimulationListener { - - @Override - public String getName() { - return "Air-start"; - } - - @Override - public String[] getMenuPosition() { - return null; - } - - @Override - public void loadFromXML(Object... objects) { - // TODO Auto-generated method stub - - } - - @Override - public void saveToXML(Object... objects) { - // TODO Auto-generated method stub - - } - - @Override - public boolean isConfigurable() { - // TODO Auto-generated method stub - return false; - } - - @Override - public Component getConfigurationComponent() { - // TODO Auto-generated method stub - return null; - } - - -} diff --git a/core/src/net/sf/openrocket/plugin/example/ExampleMain.java b/core/src/net/sf/openrocket/plugin/example/ExampleMain.java deleted file mode 100644 index aea94be6..00000000 --- a/core/src/net/sf/openrocket/plugin/example/ExampleMain.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.plugin.example; - -import net.sf.openrocket.plugin.framework.JSPFPluginFactory; -import net.sf.openrocket.plugin.framework.PluginFactory; - -public class ExampleMain { - - - public static void main(String[] args) { - PluginFactory factory = new JSPFPluginFactory(); - - System.out.println("Plugins:"); - System.out.println("---------"); - for (ExamplePluginInterface plugin : factory.getPlugins(ExamplePluginInterface.class)) { - plugin.print(); - } - System.out.println("---------"); - } - - -} diff --git a/core/src/net/sf/openrocket/plugin/example/ExamplePlugin.java b/core/src/net/sf/openrocket/plugin/example/ExamplePlugin.java deleted file mode 100644 index 4579f9e3..00000000 --- a/core/src/net/sf/openrocket/plugin/example/ExamplePlugin.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.sf.openrocket.plugin.example; - - -public class ExamplePlugin implements ExamplePluginInterface { - - private final String str; - - public ExamplePlugin(String str) { - this.str = str; - } - - @Override - public void print() { - System.out.println("ExamplePlugin: " + str); - } - -} diff --git a/core/src/net/sf/openrocket/plugin/example/ExamplePluginInterface.java b/core/src/net/sf/openrocket/plugin/example/ExamplePluginInterface.java deleted file mode 100644 index ddf157dc..00000000 --- a/core/src/net/sf/openrocket/plugin/example/ExamplePluginInterface.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.sf.openrocket.plugin.example; - -import net.xeoh.plugins.base.Plugin; - -public interface ExamplePluginInterface extends Plugin { - - public void print(); - -} diff --git a/core/src/net/sf/openrocket/plugin/example/ExampleService.java b/core/src/net/sf/openrocket/plugin/example/ExampleService.java deleted file mode 100644 index 8a6317b3..00000000 --- a/core/src/net/sf/openrocket/plugin/example/ExampleService.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.plugin.example; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.plugin.framework.AbstractService; -import net.xeoh.plugins.base.annotations.PluginImplementation; - -@PluginImplementation -public class ExampleService extends AbstractService { - - protected ExampleService() { - super(ExamplePluginInterface.class); - } - - @Override - protected List getPlugins(Object... args) { - List plugins = new ArrayList(); - plugins.add(new ExamplePlugin("a")); - plugins.add(new ExamplePlugin("b")); - return plugins; - } - -} diff --git a/core/src/net/sf/openrocket/plugin/example/ExampleSingletonPlugin.java b/core/src/net/sf/openrocket/plugin/example/ExampleSingletonPlugin.java deleted file mode 100644 index aa015180..00000000 --- a/core/src/net/sf/openrocket/plugin/example/ExampleSingletonPlugin.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.sf.openrocket.plugin.example; - -import net.xeoh.plugins.base.annotations.PluginImplementation; - -@PluginImplementation -public class ExampleSingletonPlugin implements ExamplePluginInterface { - - @Override - public void print() { - System.out.println("ExampleSingletonPlugin"); - } - -} diff --git a/core/src/net/sf/openrocket/plugin/example/OpenRocketSimulationListener.java b/core/src/net/sf/openrocket/plugin/example/OpenRocketSimulationListener.java deleted file mode 100644 index ea178c09..00000000 --- a/core/src/net/sf/openrocket/plugin/example/OpenRocketSimulationListener.java +++ /dev/null @@ -1,88 +0,0 @@ -package net.sf.openrocket.plugin.example; - -import java.awt.Component; -import java.util.Arrays; -import java.util.List; - -import net.sf.openrocket.plugin.Configurable; -import net.sf.openrocket.plugin.SwingConfigurator; -import net.sf.openrocket.plugin.framework.Service; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.util.BugException; -import net.xeoh.plugins.base.Plugin; -import net.xeoh.plugins.base.annotations.Capabilities; - -public abstract class OpenRocketSimulationListener extends AbstractSimulationListener - implements Plugin, Service, SwingConfigurator, Configurable { - - private final String[] ids; - private final String[] capabilities; - - public OpenRocketSimulationListener(String... ids) { - if (ids.length == 0) { - ids = new String[] { this.getClass().getCanonicalName() }; - } - - this.ids = ids.clone(); - this.capabilities = new String[ids.length * 2]; - for (int i = 0; i < ids.length; i++) { - capabilities[i * 2] = ids[i] + ":service"; - capabilities[i * 2 + 1] = ids[i] + ":config"; - } - - } - - @Capabilities - public String[] capabilities() { - return capabilities.clone(); - } - - @SuppressWarnings("unchecked") - @Override - public List getPlugins(Class e, Object... args) { - if (e != this.getClass()) { - throw new BugException("Attempting to get plugin of type " + e + " but I am of type " + this.getClass()); - } - try { - return (List) Arrays.asList(this.getClass().newInstance()); - } catch (IllegalAccessException e1) { - throw new BugException("Could not instantiate new object of type " + this.getClass(), e1); - } catch (InstantiationException e2) { - throw new BugException("Could not instantiate new object of type " + this.getClass(), e2); - } - } - - - @Override - public boolean isConfigurable(OpenRocketSimulationListener plugin) { - return plugin.isConfigurable(); - } - - @Override - public Component getConfigurationComponent(OpenRocketSimulationListener plugin) { - return plugin.getConfigurationComponent(); - } - - public abstract boolean isConfigurable(); - - public abstract Component getConfigurationComponent(); - - - - @Override - public String getPluginID() { - return ids[0]; - } - - @Override - public boolean isCompatible(String pluginID) { - for (String id : ids) { - if (pluginID.equals(id)) { - return true; - } - } - return false; - } - - -} diff --git a/core/src/net/sf/openrocket/plugin/example/stuff.txt b/core/src/net/sf/openrocket/plugin/example/stuff.txt deleted file mode 100644 index e4a4fc3c..00000000 --- a/core/src/net/sf/openrocket/plugin/example/stuff.txt +++ /dev/null @@ -1,135 +0,0 @@ - - - -Plugin: - -foo() -bar() -getValue() -setValue() - - - -Service: - -getPlugins(args...) -capabilities() -> "pluginid:service" - - - -SwingConfigurator: - -getConfigurationComponent(plugin) -capabilities() -> "pluginid:config" - - - - -OpenRocketSimulationListener extends SimulationListener implements Service, SwingConfigurator: - - -constructor: - pluginid = class name - - -getPlugins(): - return new this - -capabilities: pluginid:service, pluginid:config - -getConfigurationComponent(plugin) - plugin.getConfigurationComponent() - -abstract getConfigurationComponent() - - - - - -Types of plugins: - - -AtmosphericModel - - Name -> dropdown - - Config component -> dialog window (or button) - - stateful, non-dynamic - - stored - - -SimulationListener - - Name + menu position -> Add extension menu - - Config component -> dialog after edit button - - stateful, (dynamic?) - - stored - - -OptimizationModifier - - contains its own name, description, related object - - config N/A - - stateful, dynamic - - not stored - - -OptimizationParameter - - name - - config N/A - - stateful, (dynamic?) - - not stored - - -PluginDialogWindow - - name + menu position -> Menu - - stateful, non-dynamic - - not stored - - -Motor - - Name -> Config tab - - Config component -> tab contents ???? - - or a separate configuration interface? - - stored - - - -Name is common - out, instead have name separately in plugin interfaces? -Menu position used twice - out - -Leave common configuration out - -> :config supported by those that make sense - -> may have separate interface from SwingConfigurator (e.g. SwingMotorConfigurator) - -Motor - -> :loader separately? for injecting placeholders - or store data and call loaders later - - - - - - 100.0 - - Gold - bulk - 16000 - - - - - - 100.0 - - Gold - bulk - 16000 - - - - - - - - - - - - diff --git a/core/src/net/sf/openrocket/plugin/framework/AbstractService.java b/core/src/net/sf/openrocket/plugin/framework/AbstractService.java deleted file mode 100644 index eca8a2a0..00000000 --- a/core/src/net/sf/openrocket/plugin/framework/AbstractService.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.sf.openrocket.plugin.framework; - -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.util.BugException; - -/** - * An abstract service implementation that returns plugins of type P. - * - * @param

the plugin type that this service returns. - * @author Sampo Niskanen - */ -public abstract class AbstractService

implements Service { - - private final Class

type; - - protected AbstractService(Class

type) { - this.type = type; - } - - @SuppressWarnings("unchecked") - @Override - public List getPlugins(Class e, Object... args) { - - if (e != type) { - return Collections.emptyList(); - } - - List

plugins = getPlugins(args); - - // Check list content types to avoid mysterious bugs later on - for (P p : plugins) { - if (!type.isInstance(p)) { - throw new BugException("Requesting plugins of type " + type + " but received " + - ((p != null) ? p.getClass() : "null")); - } - } - - return (List) plugins; - } - - protected abstract List

getPlugins(Object... args); - -} diff --git a/core/src/net/sf/openrocket/plugin/framework/JSPFPluginFactory.java b/core/src/net/sf/openrocket/plugin/framework/JSPFPluginFactory.java deleted file mode 100644 index f75cf36c..00000000 --- a/core/src/net/sf/openrocket/plugin/framework/JSPFPluginFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.sf.openrocket.plugin.framework; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.util.BugException; -import net.xeoh.plugins.base.Plugin; -import net.xeoh.plugins.base.PluginManager; -import net.xeoh.plugins.base.impl.PluginManagerFactory; -import net.xeoh.plugins.base.util.JSPFProperties; -import net.xeoh.plugins.base.util.PluginManagerUtil; - -public class JSPFPluginFactory implements PluginFactory { - - private final PluginManager pluginManager; - - public JSPFPluginFactory() { - - final JSPFProperties props = new JSPFProperties(); - - // props.setProperty(PluginManager.class, "cache.enabled", "true"); - // props.setProperty(PluginManager.class, "cache.mode", "weak"); //optional - // props.setProperty(PluginManager.class, "cache.file", "jspf.cache"); - - try { - pluginManager = PluginManagerFactory.createPluginManager(props); - pluginManager.addPluginsFrom(new URI("classpath://*")); - } catch (URISyntaxException e) { - throw new BugException(e); - } - } - - @Override - public List getPlugins(Class e, Object... args) { - - List plugins = new ArrayList(); - - PluginManagerUtil pluginManagerUtil = new PluginManagerUtil(pluginManager); - plugins.addAll(pluginManagerUtil.getPlugins(e)); - - for (Service s : pluginManagerUtil.getPlugins(Service.class)) { - plugins.addAll(s.getPlugins(e, args)); - } - - return plugins; - - } -} diff --git a/core/src/net/sf/openrocket/plugin/framework/PluginFactory.java b/core/src/net/sf/openrocket/plugin/framework/PluginFactory.java deleted file mode 100644 index 25b6cbfd..00000000 --- a/core/src/net/sf/openrocket/plugin/framework/PluginFactory.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.sf.openrocket.plugin.framework; - -import java.util.List; - -import net.xeoh.plugins.base.Plugin; - -public interface PluginFactory { - - public List getPlugins(Class e, Object... args); - -} diff --git a/core/src/net/sf/openrocket/plugin/framework/Service.java b/core/src/net/sf/openrocket/plugin/framework/Service.java deleted file mode 100644 index ee56b8e4..00000000 --- a/core/src/net/sf/openrocket/plugin/framework/Service.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.plugin.framework; - -import java.util.List; - -import net.xeoh.plugins.base.Plugin; - -/** - * A discovery service that returns plugins of a specified type with - * provided arguments. - * - * @author Sampo Niskanen - */ -public interface Service extends Plugin { - - /** - * Return the plugins that match the provided type and are applicable - * for the arguments. The arguments depend on the class type. - *

- * This method may return different plugins for different arguments. - * For example, if the arguments contain the OpenRocketDocument, the - * service may return only plugins applicable for the specified document. - * - * @param type the plugin interface type - * @param args arguments for the interface. - * @return the plugin instances applicable. - */ - public List getPlugins(Class type, Object... args); - - -} diff --git a/core/src/net/sf/openrocket/preset/ComponentPreset.java b/core/src/net/sf/openrocket/preset/ComponentPreset.java deleted file mode 100644 index 6e7bd7aa..00000000 --- a/core/src/net/sf/openrocket/preset/ComponentPreset.java +++ /dev/null @@ -1,377 +0,0 @@ -package net.sf.openrocket.preset; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.Transition.Shape; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.TextUtil; - - -/** - * A model for a preset component. - *

- * A preset component contains a component class type, manufacturer information, - * part information, and a method that returns a prototype of the preset component. - * - * @author Sampo Niskanen - */ -public class ComponentPreset implements Comparable { - - private final TypedPropertyMap properties = new TypedPropertyMap(); - - private String digest = ""; - - public enum Type { - BODY_TUBE(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.INNER_DIAMETER, - ComponentPreset.OUTER_DIAMETER, - ComponentPreset.LENGTH }), - - NOSE_CONE(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.SHAPE, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.AFT_SHOULDER_DIAMETER, - ComponentPreset.AFT_SHOULDER_LENGTH, - ComponentPreset.LENGTH }), - - TRANSITION(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.SHAPE, - ComponentPreset.FORE_OUTER_DIAMETER, - ComponentPreset.FORE_SHOULDER_DIAMETER, - ComponentPreset.FORE_SHOULDER_LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.AFT_SHOULDER_DIAMETER, - ComponentPreset.AFT_SHOULDER_LENGTH, - ComponentPreset.LENGTH }), - - TUBE_COUPLER(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.OUTER_DIAMETER, - ComponentPreset.INNER_DIAMETER, - ComponentPreset.LENGTH }), - - BULK_HEAD(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.OUTER_DIAMETER, - ComponentPreset.LENGTH }), - - CENTERING_RING(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.INNER_DIAMETER, - ComponentPreset.OUTER_DIAMETER, - ComponentPreset.LENGTH }), - - ENGINE_BLOCK(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.INNER_DIAMETER, - ComponentPreset.OUTER_DIAMETER, - ComponentPreset.LENGTH }), - - LAUNCH_LUG(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.INNER_DIAMETER, - ComponentPreset.OUTER_DIAMETER, - ComponentPreset.LENGTH }), - - STREAMER(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.LENGTH, - ComponentPreset.WIDTH, - ComponentPreset.THICKNESS, - ComponentPreset.MATERIAL }), - - PARACHUTE(new TypedKey[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DESCRIPTION, - ComponentPreset.DIAMETER, - ComponentPreset.SIDES, - ComponentPreset.LINE_COUNT, - ComponentPreset.LINE_LENGTH, - ComponentPreset.LINE_MATERIAL, - ComponentPreset.MATERIAL }); - - TypedKey[] displayedColumns; - - Type(TypedKey[] displayedColumns) { - this.displayedColumns = displayedColumns; - } - - public List getCompatibleTypes() { - return compatibleTypeMap.get(Type.this); - } - - public TypedKey[] getDisplayedColumns() { - return displayedColumns; - } - - private static Map> compatibleTypeMap = new HashMap>(); - - static { - compatibleTypeMap.put(BODY_TUBE, Arrays.asList(BODY_TUBE, TUBE_COUPLER, LAUNCH_LUG)); - compatibleTypeMap.put(TUBE_COUPLER, Arrays.asList(BODY_TUBE, TUBE_COUPLER, LAUNCH_LUG)); - compatibleTypeMap.put(LAUNCH_LUG, Arrays.asList(BODY_TUBE, TUBE_COUPLER, LAUNCH_LUG)); - compatibleTypeMap.put(CENTERING_RING, Arrays.asList(CENTERING_RING, ENGINE_BLOCK)); - compatibleTypeMap.put(NOSE_CONE, Arrays.asList(NOSE_CONE, TRANSITION)); - } - - } - - public final static TypedKey MANUFACTURER = new TypedKey("Manufacturer", Manufacturer.class); - public final static TypedKey PARTNO = new TypedKey("PartNo", String.class); - public final static TypedKey DESCRIPTION = new TypedKey("Description", String.class); - public final static TypedKey TYPE = new TypedKey("Type", Type.class); - public final static TypedKey LENGTH = new TypedKey("Length", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey WIDTH = new TypedKey("Width", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey INNER_DIAMETER = new TypedKey("InnerDiameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey OUTER_DIAMETER = new TypedKey("OuterDiameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey FORE_SHOULDER_LENGTH = new TypedKey("ForeShoulderLength", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey FORE_SHOULDER_DIAMETER = new TypedKey("ForeShoulderDiameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey FORE_OUTER_DIAMETER = new TypedKey("ForeOuterDiameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey AFT_SHOULDER_LENGTH = new TypedKey("AftShoulderLength", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey AFT_SHOULDER_DIAMETER = new TypedKey("AftShoulderDiameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey AFT_OUTER_DIAMETER = new TypedKey("AftOuterDiameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey SHAPE = new TypedKey("Shape", Shape.class); - public final static TypedKey MATERIAL = new TypedKey("Material", Material.class); - public final static TypedKey FINISH = new TypedKey("Finish", Finish.class); - public final static TypedKey THICKNESS = new TypedKey("Thickness", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey FILLED = new TypedKey("Filled", Boolean.class); - public final static TypedKey MASS = new TypedKey("Mass", Double.class, UnitGroup.UNITS_MASS); - public final static TypedKey DIAMETER = new TypedKey("Diameter", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey SIDES = new TypedKey("Sides", Integer.class); - public final static TypedKey LINE_COUNT = new TypedKey("LineCount", Integer.class); - public final static TypedKey LINE_LENGTH = new TypedKey("LineLength", Double.class, UnitGroup.UNITS_LENGTH); - public final static TypedKey LINE_MATERIAL = new TypedKey("LineMaterial", Material.class); - public final static TypedKey IMAGE = new TypedKey("Image", byte[].class); - - public final static List> ORDERED_KEY_LIST = Collections.unmodifiableList(Arrays.> asList( - MANUFACTURER, - PARTNO, - DESCRIPTION, - OUTER_DIAMETER, - FORE_OUTER_DIAMETER, - AFT_OUTER_DIAMETER, - INNER_DIAMETER, - LENGTH, - WIDTH, - AFT_SHOULDER_DIAMETER, - AFT_SHOULDER_LENGTH, - FORE_SHOULDER_DIAMETER, - FORE_SHOULDER_LENGTH, - SHAPE, - THICKNESS, - FILLED, - DIAMETER, - SIDES, - LINE_COUNT, - LINE_LENGTH, - LINE_MATERIAL, - MASS, - FINISH, - MATERIAL - )); - - - // package scope constructor to encourage use of factory. - ComponentPreset() { - } - - /** - * Convenience method to retrieve the Type of this ComponentPreset. - * - * @return - */ - public Type getType() { - return properties.get(TYPE); - } - - /** - * Convenience method to retrieve the Manufacturer of this ComponentPreset. - * @return - */ - public Manufacturer getManufacturer() { - return properties.get(MANUFACTURER); - } - - /** - * Convenience method to retrieve the PartNo of this ComponentPreset. - * @return - */ - public String getPartNo() { - return properties.get(PARTNO); - } - - public String getDigest() { - return digest; - } - - public boolean has(Object key) { - return properties.containsKey(key); - } - - /** - * Package scope so the ComponentPresetFactory can call it. - * @param other - */ - void putAll(TypedPropertyMap other) { - if (other == null) { - return; - } - properties.putAll(other); - } - - /** - * Package scope so the ComponentPresetFactory can call it. - * @param key - * @param value - */ - void put(TypedKey key, T value) { - properties.put(key, value); - } - - public T get(TypedKey key) { - T value = properties.get(key); - if (value == null) { - throw new BugException("Preset did not contain key " + key + " " + properties.toString()); - } - return value; - } - - @Override - public int compareTo(ComponentPreset p2) { - int manuCompare = this.getManufacturer().getSimpleName().compareTo(p2.getManufacturer().getSimpleName()); - if (manuCompare != 0) - return manuCompare; - - int partNoCompare = this.getPartNo().compareTo(p2.getPartNo()); - return partNoCompare; - } - - @Override - public String toString() { - return get(PARTNO); - } - - public String preferenceKey() { - return get(MANUFACTURER).toString() + "|" + get(PARTNO); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - ComponentPreset that = (ComponentPreset) o; - - if (digest != null ? !digest.equals(that.digest) : that.digest != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - return digest != null ? digest.hashCode() : 0; - } - - /** - * Package scope so the factory can call it. - */ - void computeDigest() { - - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - DataOutputStream os = new DataOutputStream(bos); - - List> keys = new ArrayList>(properties.keySet()); - - Collections.sort(keys, new Comparator>() { - @Override - public int compare(TypedKey a, TypedKey b) { - return a.getName().compareTo(b.getName()); - } - }); - - for (TypedKey key : keys) { - - Object value = properties.get(key); - - os.writeBytes(key.getName()); - - if (key.getType() == Double.class) { - Double d = (Double) value; - os.writeDouble(d); - } else if (key.getType() == String.class) { - String s = (String) value; - os.writeBytes(s); - } else if (key.getType() == Manufacturer.class) { - String s = ((Manufacturer) value).getSimpleName(); - os.writeBytes(s); - } else if (key.getType() == Finish.class) { - String s = ((Finish) value).name(); - os.writeBytes(s); - } else if (key.getType() == Type.class) { - String s = ((Type) value).name(); - os.writeBytes(s); - } else if (key.getType() == Boolean.class) { - Boolean b = (Boolean) value; - os.writeBoolean(b); - } else if (key.getType() == Material.class) { - double d = ((Material) value).getDensity(); - os.writeDouble(d); - } else if (key.getType() == Shape.class) { - // this is ugly to use the ordinal but what else? - int i = ((Shape) value).ordinal(); - os.writeInt(i); - } - - } - - MessageDigest md5 = MessageDigest.getInstance("MD5"); - digest = TextUtil.hexString(md5.digest(bos.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - throw new BugException(e); - } - } - -} diff --git a/core/src/net/sf/openrocket/preset/ComponentPresetFactory.java b/core/src/net/sf/openrocket/preset/ComponentPresetFactory.java deleted file mode 100644 index 7d2677b3..00000000 --- a/core/src/net/sf/openrocket/preset/ComponentPresetFactory.java +++ /dev/null @@ -1,280 +0,0 @@ -package net.sf.openrocket.preset; - -import static net.sf.openrocket.preset.ComponentPreset.*; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Transition; - -public abstract class ComponentPresetFactory { - - public static ComponentPreset create(TypedPropertyMap props) throws InvalidComponentPresetException { - - InvalidComponentPresetException exceptions = new InvalidComponentPresetException("Invalid preset specification."); - - ComponentPreset preset = new ComponentPreset(); - // First do validation. - if (!props.containsKey(MANUFACTURER)) { - exceptions.addInvalidParameter(MANUFACTURER, "No Manufacturer specified"); - } - if (!props.containsKey(PARTNO)) { - exceptions.addInvalidParameter(PARTNO, "No PartNo specified"); - } - if (!props.containsKey(TYPE)) { - exceptions.addInvalidParameter(TYPE, "No Type specified"); - // We can't do anything else without TYPE so throw immediately. - throw exceptions; - } - - - preset.putAll(props); - - // Should check for various bits of each of the types. - Type t = props.get(TYPE); - switch (t) { - case BODY_TUBE: { - makeBodyTube(exceptions, preset); - break; - } - case NOSE_CONE: { - makeNoseCone(exceptions, preset); - break; - } - case TRANSITION: { - makeTransition(exceptions, preset); - break; - } - case BULK_HEAD: { - makeBulkHead(exceptions, preset); - break; - } - case TUBE_COUPLER: { - // For now TUBE_COUPLER is the same as BODY_TUBE - makeBodyTube(exceptions, preset); - break; - } - case CENTERING_RING: { - makeCenteringRing(exceptions, preset); - break; - } - case ENGINE_BLOCK: { - makeEngineBlock(exceptions, preset); - break; - } - case LAUNCH_LUG: { - // Same processing as BODY_TUBE - makeBodyTube(exceptions, preset); - break; - } - case STREAMER: { - makeStreamer(exceptions, preset); - break; - } - case PARACHUTE: { - makeParachute(exceptions, preset); - break; - } - } - - if (exceptions.hasProblems()) { - throw exceptions; - } - - preset.computeDigest(); - - return preset; - - } - - private static void makeBodyTube(InvalidComponentPresetException exceptions, ComponentPreset preset) throws InvalidComponentPresetException { - - checkRequiredFields(exceptions, preset, LENGTH); - - checkDiametersAndThickness(exceptions, preset); - - double volume = computeVolumeOfTube(preset); - - // Need to translate Mass to Density. - if (preset.has(MASS)) { - String materialName = "TubeCustom"; - if (preset.has(MATERIAL)) { - materialName = preset.get(MATERIAL).getName(); - } - Material m = Databases.findMaterial(Material.Type.BULK, materialName, preset.get(MASS) / volume); - preset.put(MATERIAL, m); - } - - - } - - private static void makeNoseCone(InvalidComponentPresetException exceptions, ComponentPreset preset) { - - checkRequiredFields(exceptions, preset, LENGTH, SHAPE, AFT_OUTER_DIAMETER); - - if (preset.has(MASS)) { - // compute a density for this component - double mass = preset.get(MASS); - NoseCone nc = new NoseCone(); - nc.loadPreset(preset); - double density = mass / nc.getComponentVolume(); - - String materialName = "NoseConeCustom"; - if (preset.has(MATERIAL)) { - materialName = preset.get(MATERIAL).getName(); - } - - Material m = Databases.findMaterial(Material.Type.BULK, materialName, density); - preset.put(MATERIAL, m); - - } - - } - - private static void makeTransition(InvalidComponentPresetException exceptions, ComponentPreset preset) { - checkRequiredFields(exceptions, preset, LENGTH, AFT_OUTER_DIAMETER, FORE_OUTER_DIAMETER); - - if (preset.has(MASS)) { - // compute a density for this component - double mass = preset.get(MASS); - Transition tr = new Transition(); - tr.loadPreset(preset); - double density = mass / tr.getComponentVolume(); - - String materialName = "TransitionCustom"; - if (preset.has(MATERIAL)) { - materialName = preset.get(MATERIAL).getName(); - } - - Material m = Databases.findMaterial(Material.Type.BULK, materialName, density); - preset.put(MATERIAL, m); - - } - - } - - private static void makeBulkHead(InvalidComponentPresetException exceptions, ComponentPreset preset) { - checkRequiredFields(exceptions, preset, LENGTH, OUTER_DIAMETER); - - if (preset.has(MASS)) { - // compute a density for this component - double mass = preset.get(MASS); - - double volume = computeVolumeOfTube(preset); - double density = mass / volume; - - String materialName = "BulkHeadCustom"; - if (preset.has(MATERIAL)) { - materialName = preset.get(MATERIAL).getName(); - } - - Material m = Databases.findMaterial(Material.Type.BULK, materialName, density); - preset.put(MATERIAL, m); - - } - - } - - private static void makeCenteringRing(InvalidComponentPresetException exceptions, ComponentPreset preset) throws InvalidComponentPresetException { - checkRequiredFields(exceptions, preset, LENGTH); - - checkDiametersAndThickness(exceptions, preset); - - double volume = computeVolumeOfTube(preset); - - // Need to translate Mass to Density. - if (preset.has(MASS)) { - String materialName = "CenteringRingCustom"; - if (preset.has(MATERIAL)) { - materialName = preset.get(MATERIAL).getName(); - } - Material m = Databases.findMaterial(Material.Type.BULK, materialName, preset.get(MASS) / volume); - preset.put(MATERIAL, m); - } - - } - - private static void makeEngineBlock(InvalidComponentPresetException exceptions, ComponentPreset preset) throws InvalidComponentPresetException { - checkRequiredFields(exceptions, preset, LENGTH); - - checkDiametersAndThickness(exceptions, preset); - - double volume = computeVolumeOfTube(preset); - - // Need to translate Mass to Density. - if (preset.has(MASS)) { - String materialName = "EngineBlockCustom"; - if (preset.has(MATERIAL)) { - materialName = preset.get(MATERIAL).getName(); - } - Material m = Databases.findMaterial(Material.Type.BULK, materialName, preset.get(MASS) / volume); - preset.put(MATERIAL, m); - } - - } - - private static void makeStreamer(InvalidComponentPresetException exceptions, ComponentPreset preset) { - checkRequiredFields(exceptions, preset, LENGTH, WIDTH); - } - - private static void makeParachute(InvalidComponentPresetException exceptions, ComponentPreset preset) { - checkRequiredFields(exceptions, preset, DIAMETER, LINE_COUNT, LINE_LENGTH); - } - - - private static void checkRequiredFields(InvalidComponentPresetException exceptions, ComponentPreset preset, TypedKey... keys) { - for (TypedKey key : keys) { - if (!preset.has(key)) { - exceptions.addInvalidParameter(key, "No " + key.getName() + " specified"); - } - } - } - - private static void checkDiametersAndThickness(InvalidComponentPresetException exceptions, ComponentPreset preset) throws InvalidComponentPresetException { - // Need to verify contains 2 of OD, thickness, ID. Compute the third. - boolean hasOd = preset.has(OUTER_DIAMETER); - boolean hasId = preset.has(INNER_DIAMETER); - boolean hasThickness = preset.has(THICKNESS); - - double outerRadius; - double innerRadius; - double thickness; - - if (hasOd) { - outerRadius = preset.get(OUTER_DIAMETER) / 2.0; - thickness = 0; - if (hasId) { - innerRadius = preset.get(INNER_DIAMETER) / 2.0; - thickness = outerRadius - innerRadius; - } else if (hasThickness) { - thickness = preset.get(THICKNESS); - innerRadius = outerRadius - thickness; - } else { - exceptions.addMessage("Preset dimensions underspecified"); - throw exceptions; - } - } else { - if (!hasId || !hasThickness) { - exceptions.addMessage("Preset dimensions underspecified"); - throw exceptions; - } - innerRadius = preset.get(INNER_DIAMETER) / 2.0; - thickness = preset.get(THICKNESS); - outerRadius = innerRadius + thickness; - } - - preset.put(OUTER_DIAMETER, outerRadius * 2.0); - preset.put(INNER_DIAMETER, innerRadius * 2.0); - preset.put(THICKNESS, thickness); - - } - - private static double computeVolumeOfTube(ComponentPreset preset) { - double or = preset.get(OUTER_DIAMETER) / 2.0; - double ir = preset.has(INNER_DIAMETER) ? preset.get(INNER_DIAMETER) / 2.0 : 0.0; - double l = preset.get(LENGTH); - return Math.PI * (or * or - ir * ir) * l; - } - - -} diff --git a/core/src/net/sf/openrocket/preset/InvalidComponentPresetException.java b/core/src/net/sf/openrocket/preset/InvalidComponentPresetException.java deleted file mode 100644 index c28fb093..00000000 --- a/core/src/net/sf/openrocket/preset/InvalidComponentPresetException.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.preset; - -import java.util.ArrayList; -import java.util.List; - -public class InvalidComponentPresetException extends Exception { - - private List errors = new ArrayList(); - private List> invalidParameters = new ArrayList>(); - - public InvalidComponentPresetException() { - super(); - } - - public InvalidComponentPresetException(String message, Throwable cause) { - super(message, cause); - } - - public InvalidComponentPresetException(String message) { - super(message); - } - - public InvalidComponentPresetException(Throwable cause) { - super(cause); - } - - void addInvalidParameter(TypedKey key ) { - invalidParameters.add(key); - } - - void addInvalidParameter(TypedKey key, String message ) { - invalidParameters.add(key); - errors.add(message); - } - - void addMessage( String message ) { - errors.add(message); - } - - boolean hasProblems() { - return (invalidParameters.size() + errors.size()) > 0; - } - - public int problemCount() { - return Math.max( invalidParameters.size(), errors.size() ); - } - - public List getErrors() { - return errors; - } - - public List> getInvalidParameters() { - return invalidParameters; - } - -} diff --git a/core/src/net/sf/openrocket/preset/TypedKey.java b/core/src/net/sf/openrocket/preset/TypedKey.java deleted file mode 100644 index c3e44731..00000000 --- a/core/src/net/sf/openrocket/preset/TypedKey.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.sf.openrocket.preset; - -import net.sf.openrocket.unit.UnitGroup; - -public class TypedKey { - - private final String name; - private final Class type; - private final UnitGroup unitGroup; - - public TypedKey(String name, Class type) { - this(name, type, null); - } - - public TypedKey(String name, Class type, UnitGroup unitGroup) { - this.name = name; - this.type = type; - this.unitGroup = unitGroup; - } - - @Override - public String toString() { - return "TypedKey [name=" + name + "]"; - } - - public String getName() { - return name; - } - - public Class getType() { - return type; - } - - public UnitGroup getUnitGroup() { - return unitGroup; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - TypedKey other = (TypedKey) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; - } - -} diff --git a/core/src/net/sf/openrocket/preset/TypedPropertyMap.java b/core/src/net/sf/openrocket/preset/TypedPropertyMap.java deleted file mode 100644 index cb43f12c..00000000 --- a/core/src/net/sf/openrocket/preset/TypedPropertyMap.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.sf.openrocket.preset; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -public class TypedPropertyMap implements Cloneable { - - private final Map, Object> delegate; - - public TypedPropertyMap() { - delegate = new LinkedHashMap, Object>(); - } - - public int size() { - return delegate.size(); - } - - public boolean isEmpty() { - return delegate.isEmpty(); - } - - public boolean containsKey(Object key) { - return delegate.containsKey(key); - } - - public boolean containsValue(Object value) { - return delegate.containsValue(value); - } - - @SuppressWarnings("unchecked") - public T get(TypedKey key) { - return (T) delegate.get(key); - } - - @SuppressWarnings("unchecked") - public T put(TypedKey key, T value) { - return (T) delegate.put(key, value); - } - - public Object remove(Object key) { - return delegate.remove(key); - } - - public void putAll(TypedPropertyMap other) { - if (other == null) { - return; - } - delegate.putAll(other.delegate); - } - - public void clear() { - delegate.clear(); - } - - public Set> keySet() { - return delegate.keySet(); - } - - public Collection values() { - return delegate.values(); - } - - public Set, Object>> entrySet() { - return delegate.entrySet(); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder("TypedPropertyMap: { "); - for( Map.Entry, Object> e : delegate.entrySet() ) { - sb.append(e.getKey()).append(" => ").append(String.valueOf(e.getValue())); - } - sb.append("}"); - return sb.toString(); - } - - @Override - protected TypedPropertyMap clone() throws CloneNotSupportedException { - TypedPropertyMap clone = new TypedPropertyMap(); - clone.putAll(this); - return clone; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/BaseColumnParser.java b/core/src/net/sf/openrocket/preset/loader/BaseColumnParser.java deleted file mode 100644 index 9c95197f..00000000 --- a/core/src/net/sf/openrocket/preset/loader/BaseColumnParser.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import java.util.Locale; - -import net.sf.openrocket.preset.TypedPropertyMap; - - -public abstract class BaseColumnParser implements RocksimComponentFileColumnParser { - - protected String columnHeader; - protected boolean isConfigured = false; - protected int columnIndex; - - public BaseColumnParser(String columnHeader) { - super(); - this.columnHeader = columnHeader.toLowerCase(Locale.US); - } - - @Override - public void configure(String[] headers) { - if ( headers == null ) { - return; - } - for( int i =0; i< headers.length; i++ ) { - if ( columnHeader.equals(headers[i].toLowerCase(Locale.US))) { - columnIndex = i; - isConfigured = true; - return; - } - } - } - - @Override - final public void parse(String[] data, TypedPropertyMap props) { - if ( isConfigured ) { - doParse(data[columnIndex], data, props); - } - } - - protected abstract void doParse(String columnData, String[] data, TypedPropertyMap props ); - -} diff --git a/core/src/net/sf/openrocket/preset/loader/BaseComponentLoader.java b/core/src/net/sf/openrocket/preset/loader/BaseComponentLoader.java deleted file mode 100644 index d1782097..00000000 --- a/core/src/net/sf/openrocket/preset/loader/BaseComponentLoader.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -public abstract class BaseComponentLoader extends RocksimComponentFileLoader { - - List presets; - - public BaseComponentLoader(MaterialHolder materials, File theBasePathToLoadFrom) { - super(theBasePathToLoadFrom); - presets = new ArrayList(); - - fileColumns.add( new ManufacturerColumnParser() ); - fileColumns.add( new StringColumnParser("Part No.", ComponentPreset.PARTNO)); - fileColumns.add( new StringColumnParser("Desc.", ComponentPreset.DESCRIPTION)); - fileColumns.add(new MaterialColumnParser(materials)); - fileColumns.add(new MassColumnParser("Mass","Mass units")); - - } - - protected abstract ComponentPreset.Type getComponentPresetType(); - - public List getPresets() { - return presets; - } - - @Override - protected void postProcess(TypedPropertyMap props) { - try { - //Some Rocksim files don't contain description, so set it to the part no when not available. - if (!props.containsKey(ComponentPreset.DESCRIPTION)) { - props.put(ComponentPreset.DESCRIPTION, props.get(ComponentPreset.PARTNO)); - } - props.put(ComponentPreset.TYPE, getComponentPresetType()); - ComponentPreset preset = ComponentPresetFactory.create(props); - presets.add(preset); - } catch ( InvalidComponentPresetException ex ) { - System.err.println(ex.getMessage()); - System.err.println(props); - } - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/preset/loader/BaseUnitColumnParser.java b/core/src/net/sf/openrocket/preset/loader/BaseUnitColumnParser.java deleted file mode 100644 index 4cdb3986..00000000 --- a/core/src/net/sf/openrocket/preset/loader/BaseUnitColumnParser.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; - - -public abstract class BaseUnitColumnParser extends BaseColumnParser { - - protected String unitHeader; - protected int unitIndex; - protected boolean unitConfigured; - - protected static Map rocksimUnits; - - static { - rocksimUnits = new HashMap(); - rocksimUnits.put("0", UnitGroup.UNITS_LENGTH.getUnit("in")); - rocksimUnits.put("1", UnitGroup.UNITS_LENGTH.getUnit("mm")); - } - - protected String mungeUnitNameString( String name ) { - String newString = name.toLowerCase(Locale.US); - return newString.replace(".", ""); - } - - public BaseUnitColumnParser(String columnHeader, String unitHeader) { - super(columnHeader); - this.unitHeader = unitHeader.toLowerCase(Locale.US); - } - - @Override - public void configure(String[] headers) { - // super configure will set columnIndex; - super.configure(headers); - - // This indicates the actual dimension column was found. - if ( isConfigured ) { - // Look for the unit column proceeding it - for( int i=columnIndex-1; i>=0; i-- ) { - if ( unitHeader.equals(headers[i].toLowerCase(Locale.US))) { - unitConfigured = true; - unitIndex = i; - return; - } - } - } - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/BodyTubeLoader.java b/core/src/net/sf/openrocket/preset/loader/BodyTubeLoader.java deleted file mode 100644 index dcb7ccc5..00000000 --- a/core/src/net/sf/openrocket/preset/loader/BodyTubeLoader.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; - -import java.io.File; - -public class BodyTubeLoader extends BaseComponentLoader { - - public BodyTubeLoader(MaterialHolder materials, File theBasePathToLoadFrom) { - super(materials, theBasePathToLoadFrom); - fileColumns.add(new DoubleUnitColumnParser("ID","Units",ComponentPreset.INNER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("OD","Units",ComponentPreset.OUTER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Length","Units",ComponentPreset.LENGTH)); - - } - - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.BODY_TUBE; - } - - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.BODY_TUBE; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/BulkHeadLoader.java b/core/src/net/sf/openrocket/preset/loader/BulkHeadLoader.java deleted file mode 100644 index b9d01066..00000000 --- a/core/src/net/sf/openrocket/preset/loader/BulkHeadLoader.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.preset.TypedPropertyMap; - -import java.io.File; - -public class BulkHeadLoader extends BaseComponentLoader { - - public BulkHeadLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - fileColumns.add(new DoubleUnitColumnParser("OD","Units",ComponentPreset.OUTER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Length","Units",ComponentPreset.LENGTH)); - - } - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.BULK_HEAD; - } - - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.BULKHEAD; - } - - @Override - protected void postProcess(TypedPropertyMap props) { - props.put(ComponentPreset.FILLED, true); - super.postProcess(props); - } - - -} diff --git a/core/src/net/sf/openrocket/preset/loader/CenteringRingLoader.java b/core/src/net/sf/openrocket/preset/loader/CenteringRingLoader.java deleted file mode 100644 index ad465694..00000000 --- a/core/src/net/sf/openrocket/preset/loader/CenteringRingLoader.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; - -import java.io.File; - -public class CenteringRingLoader extends BodyTubeLoader { - - public CenteringRingLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - } - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.CENTERING_RING; - } - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.CENTERING_RING; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/DoubleColumnParser.java b/core/src/net/sf/openrocket/preset/loader/DoubleColumnParser.java deleted file mode 100644 index e4f54134..00000000 --- a/core/src/net/sf/openrocket/preset/loader/DoubleColumnParser.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class DoubleColumnParser extends BaseColumnParser { - - private TypedKey propKey; - - public DoubleColumnParser(String columnHeader, TypedKey propKey) { - super(columnHeader); - this.propKey = propKey; - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - double value = Double.valueOf(columnData); - props.put(propKey, value); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/DoubleUnitColumnParser.java b/core/src/net/sf/openrocket/preset/loader/DoubleUnitColumnParser.java deleted file mode 100644 index bd9a5c18..00000000 --- a/core/src/net/sf/openrocket/preset/loader/DoubleUnitColumnParser.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; - -public class DoubleUnitColumnParser extends BaseUnitColumnParser { - - private TypedKey propKey; - - public DoubleUnitColumnParser(String columnHeader, String unitHeader, - TypedKey propKey) { - super(columnHeader, unitHeader); - this.propKey = propKey; - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - try { - if (columnData == null || "".equals(columnData) ) { - return; - } - double value = Double.valueOf(columnData); - - if ( unitConfigured ) { - String unitName = data[unitIndex]; - - Unit unit = rocksimUnits.get(unitName); - if ( unit == null ) { - if ( unitName == null || "" .equals(unitName) || "?".equals(unitName)) { - // Hmm no data... Lets assume SI - if ( propKey.getUnitGroup() == UnitGroup.UNITS_LENGTH ) { - unit = UnitGroup.UNITS_LENGTH.getUnit("in"); - } else { - unit= UnitGroup.UNITS_MASS.getUnit("oz"); - } - } else { - unitName = super.mungeUnitNameString(unitName); - UnitGroup group = propKey.getUnitGroup(); - unit = group.getUnit(unitName); - } - } - - value = unit.fromUnit(value); - } - - props.put(propKey, value); - } - catch ( NumberFormatException nex) { - } - catch ( IllegalArgumentException iae) { - } - } - - -} diff --git a/core/src/net/sf/openrocket/preset/loader/EngineBlockLoader.java b/core/src/net/sf/openrocket/preset/loader/EngineBlockLoader.java deleted file mode 100644 index 0fa6a6ec..00000000 --- a/core/src/net/sf/openrocket/preset/loader/EngineBlockLoader.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; - -import java.io.File; - -public class EngineBlockLoader extends BodyTubeLoader { - - public EngineBlockLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - } - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.ENGINE_BLOCK; - } - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.ENGINE_BLOCK; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/IntegerColumnParser.java b/core/src/net/sf/openrocket/preset/loader/IntegerColumnParser.java deleted file mode 100644 index d871be1c..00000000 --- a/core/src/net/sf/openrocket/preset/loader/IntegerColumnParser.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class IntegerColumnParser extends BaseColumnParser { - - private TypedKey propKey; - - public IntegerColumnParser(String columnHeader, TypedKey propKey) { - super(columnHeader); - this.propKey = propKey; - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - int value = Integer.valueOf(columnData); - props.put(propKey, value); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/LaunchLugLoader.java b/core/src/net/sf/openrocket/preset/loader/LaunchLugLoader.java deleted file mode 100644 index 8242e8f7..00000000 --- a/core/src/net/sf/openrocket/preset/loader/LaunchLugLoader.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; - -import java.io.File; - -public class LaunchLugLoader extends BaseComponentLoader { - - public LaunchLugLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - fileColumns.add(new DoubleUnitColumnParser("ID","Units",ComponentPreset.INNER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("OD","Units",ComponentPreset.OUTER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Length","Units",ComponentPreset.LENGTH)); - - } - - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.LAUNCH_LUG; - } - - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.LAUNCH_LUG; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/LineMaterialColumnParser.java b/core/src/net/sf/openrocket/preset/loader/LineMaterialColumnParser.java deleted file mode 100644 index 42a79722..00000000 --- a/core/src/net/sf/openrocket/preset/loader/LineMaterialColumnParser.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class LineMaterialColumnParser extends BaseColumnParser { - - private final MaterialHolder materialMap; - - private final TypedKey param; - - public LineMaterialColumnParser(MaterialHolder materialMap, String columnName, TypedKey param) { - super(columnName); - this.param = param; - this.materialMap = materialMap; - } - - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - - if (columnData == null || "".equals(columnData.trim())) { - return; - } - - Material.Line myMaterial = (Material.Line) Databases.findMaterial(Material.Type.LINE, columnData, 0.0); - - Material.Line m = materialMap.getLineMaterial(myMaterial); - props.put(param, m != null ? m : myMaterial); - - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/ManufacturerColumnParser.java b/core/src/net/sf/openrocket/preset/loader/ManufacturerColumnParser.java deleted file mode 100644 index 7d019c01..00000000 --- a/core/src/net/sf/openrocket/preset/loader/ManufacturerColumnParser.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class ManufacturerColumnParser extends BaseColumnParser { - - public ManufacturerColumnParser() { - super("Mfg."); - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - Manufacturer m = Manufacturer.getManufacturer(columnData); - props.put(ComponentPreset.MANUFACTURER, m); - - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/MassColumnParser.java b/core/src/net/sf/openrocket/preset/loader/MassColumnParser.java deleted file mode 100644 index ce382ec9..00000000 --- a/core/src/net/sf/openrocket/preset/loader/MassColumnParser.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedPropertyMap; - -/** - * Special DoubleUnitColumnParser for Mass column. Here we assume that if a mass of 0 is - * specified in the csv, then we should not put a mass explicitly in the preset but instead - * rely on the density to compute a mass value. - * - */ -public class MassColumnParser extends DoubleUnitColumnParser { - - public MassColumnParser(String columnHeader, String unitHeader) { - super(columnHeader, unitHeader, ComponentPreset.MASS); - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - if ( columnData == null || "".equals(columnData.trim()) || "?".equals(columnData.trim())) { - return; - } - double d = Double.valueOf(columnData); - if ( d == 0.0 ) { - return; - } - super.doParse(columnData, data, props); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/MaterialColumnParser.java b/core/src/net/sf/openrocket/preset/loader/MaterialColumnParser.java deleted file mode 100644 index 2d559bb7..00000000 --- a/core/src/net/sf/openrocket/preset/loader/MaterialColumnParser.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class MaterialColumnParser extends BaseColumnParser { - - private final MaterialHolder materialMap; - - private final TypedKey param; - - public MaterialColumnParser(MaterialHolder materialMap, String columnName, TypedKey param) { - super(columnName); - this.param = param; - this.materialMap = materialMap; - } - - public MaterialColumnParser(MaterialHolder materialMap) { - this(materialMap, "Material", ComponentPreset.MATERIAL); - } - - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - - if (columnData == null || "".equals(columnData.trim())) { - return; - } - - Material.Bulk tmpMaterial = (Material.Bulk) Databases.findMaterial(Material.Type.BULK, columnData, 0.0); - Material.Bulk m = materialMap.getBulkMaterial(tmpMaterial); - props.put(param, m != null ? m : tmpMaterial); - - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/MaterialHolder.java b/core/src/net/sf/openrocket/preset/loader/MaterialHolder.java deleted file mode 100644 index 7ab176b8..00000000 --- a/core/src/net/sf/openrocket/preset/loader/MaterialHolder.java +++ /dev/null @@ -1,134 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.database.Database; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.unit.UnitGroup; - -public class MaterialHolder { - - private final Map bulkMaterials = new HashMap(); - - private final Map surfaceMaterials = new HashMap(); - - private final Map lineMaterials = new HashMap(); - - public MaterialHolder() { - } - - public MaterialHolder(List materials) { - if (materials == null) { - return; - } - for (Material material : materials) { - this.put(material); - } - } - - public void put(Material material) { - switch (material.getType()) { - case BULK: - bulkMaterials.put(material.getName(), (Material.Bulk) material); - break; - case SURFACE: - surfaceMaterials.put(material.getName(), (Material.Surface) material); - break; - case LINE: - lineMaterials.put(material.getName(), (Material.Line) material); - break; - } - } - - public Material getMaterial(Material material) { - switch (material.getType()) { - case BULK: - return getBulkMaterial((Material.Bulk) material); - case SURFACE: - return getSurfaceMaterial((Material.Surface) material, null); - case LINE: - return getLineMaterial((Material.Line) material); - default: - return null; - } - } - - public Material.Bulk getBulkMaterial(Material.Bulk material) { - Material.Bulk m = bulkMaterials.get(material.getName()); - return m; - } - - public Material.Surface getSurfaceMaterial(Material.Surface material, Double thickness) { - Material.Surface m = surfaceMaterials.get(material.getName()); - if (m != null) { - return m; - } - // Try to see if we can convert a bulk material. - if (thickness == null) { - // if we have no thickness, there is nothing we can do - return null; - } - String thicknessName = UnitGroup.UNITS_LENGTH.getUnit("mm").toString(thickness); - String convertedMaterialName = material.getName() + "(" + thicknessName + ")"; - m = surfaceMaterials.get(convertedMaterialName); - if (m != null) { - return m; - } - Material.Bulk bulk = bulkMaterials.get(material.getName()); - - if (bulk == null) { - return null; - } - - // Ok, now we have a thickness and a bulk material of the correct name, - // we can make our own surface material. - - Material.Surface surface = (Material.Surface) Databases.findMaterial(Material.Type.SURFACE, convertedMaterialName, bulk.getDensity() * thickness); - - this.put(surface); - - return surface; - - } - - public Material.Line getLineMaterial(Material.Line material) { - Material.Line m = lineMaterials.get(material.getName()); - return m; - } - - public int size() { - return bulkMaterials.size() + surfaceMaterials.size() + lineMaterials.size(); - } - - public Collection values() { - - HashSet allMats = new HashSet(); - allMats.addAll(bulkMaterials.values()); - allMats.addAll(surfaceMaterials.values()); - allMats.addAll(lineMaterials.values()); - - return allMats; - - } - - public Database asDatabase(Material.Type theType) { - Database result = new Database(); - switch (theType) { - case LINE: - result.addAll(lineMaterials.values()); - break; - case SURFACE: - result.addAll(surfaceMaterials.values()); - break; - case BULK: - default: - result.addAll(bulkMaterials.values()); - } - return result; - } -} diff --git a/core/src/net/sf/openrocket/preset/loader/MaterialLoader.java b/core/src/net/sf/openrocket/preset/loader/MaterialLoader.java deleted file mode 100644 index b7ef55b4..00000000 --- a/core/src/net/sf/openrocket/preset/loader/MaterialLoader.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import java.io.File; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.util.BugException; - -public class MaterialLoader extends RocksimComponentFileLoader { - - private MaterialHolder materialMap = new MaterialHolder(); - - private final static TypedKey MATERIALNAME = new TypedKey("MaterialName", String.class); - private final static TypedKey UNITS = new TypedKey("Units", String.class); - private final static TypedKey DENSITY = new TypedKey("Density", Double.class); - - public MaterialLoader(File theBasePathToLoadFrom) { - super(theBasePathToLoadFrom); - fileColumns.add(new StringColumnParser("Material Name", MATERIALNAME)); - fileColumns.add(new StringColumnParser("Units", UNITS)); - fileColumns.add(new DoubleColumnParser("Density", DENSITY)); - } - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.MATERIAL; - } - - public MaterialHolder getMaterialMap() { - return materialMap; - } - - @Override - protected void postProcess(TypedPropertyMap props) { - String name = props.get(MATERIALNAME); - String unit = props.get(UNITS); - double density = props.get(DENSITY); - - String cleanedMaterialName = stripAll(name, '"').trim(); - - if ("g/cm".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.LINE, cleanedMaterialName, 0.1d * density)); - } else if ("g/cm2".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.SURFACE, cleanedMaterialName, 10.0d * density)); - } else if ("g/cm3".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.BULK, cleanedMaterialName, 1000.0d * density)); - } else if ("kg/m3".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.BULK, cleanedMaterialName, density)); - } else if ("lb/ft3".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.BULK, cleanedMaterialName, 16.0184634d * density)); - } else if ("oz/in".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.LINE, cleanedMaterialName, 1.11612296d * density)); - } else if ("oz/in2".equals(unit)) { - materialMap.put(Databases.findMaterial(Material.Type.SURFACE, cleanedMaterialName, 43.94184876d * density)); - } else { - throw new BugException("Unknown unit in Materials file: " + unit); - } - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/preset/loader/NoseConeLoader.java b/core/src/net/sf/openrocket/preset/loader/NoseConeLoader.java deleted file mode 100644 index 8c8f4077..00000000 --- a/core/src/net/sf/openrocket/preset/loader/NoseConeLoader.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.preset.TypedPropertyMap; - -import java.io.File; - -public class NoseConeLoader extends BaseComponentLoader { - - public NoseConeLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - fileColumns.add(new DoubleUnitColumnParser("Outer Dia","Units",ComponentPreset.AFT_OUTER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Length","Units",ComponentPreset.LENGTH)); - fileColumns.add(new DoubleUnitColumnParser("Insert Length","Units",ComponentPreset.AFT_SHOULDER_LENGTH)); - fileColumns.add(new DoubleUnitColumnParser("Insert OD","Units",ComponentPreset.AFT_SHOULDER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Thickness","Units",ComponentPreset.THICKNESS)); - fileColumns.add(new ShapeColumnParser() ); - } - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.NOSE_CONE; - } - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.NOSE_CONE; - } - - @Override - protected void postProcess(TypedPropertyMap props) { - - if ( props.containsKey( ComponentPreset.THICKNESS )) { - double thickness = props.get(ComponentPreset.THICKNESS); - if ( thickness == 0d ) { - props.remove( ComponentPreset.THICKNESS ); - props.put(ComponentPreset.FILLED, true); - } - } - super.postProcess(props); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/ParachuteLoader.java b/core/src/net/sf/openrocket/preset/loader/ParachuteLoader.java deleted file mode 100644 index 4f53e40e..00000000 --- a/core/src/net/sf/openrocket/preset/loader/ParachuteLoader.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.preset.TypedPropertyMap; - -import java.io.File; - -public class ParachuteLoader extends BaseComponentLoader { - - private final MaterialHolder materials; - - public ParachuteLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - this.materials = materials; - fileColumns.add(new IntegerColumnParser("n sides", ComponentPreset.SIDES)); - fileColumns.add(new DoubleUnitColumnParser("OD","Units",ComponentPreset.DIAMETER)); - fileColumns.add(new IntegerColumnParser("Shroud Count", ComponentPreset.LINE_COUNT)); - fileColumns.add(new DoubleUnitColumnParser("Shroud Len", "Units", ComponentPreset.LINE_LENGTH)); - fileColumns.add(new LineMaterialColumnParser(materials,"Shroud Material",ComponentPreset.LINE_MATERIAL)); - fileColumns.add(new DoubleUnitColumnParser("Chute Thickness", "Units", ComponentPreset.THICKNESS)); - fileColumns.add( new SurfaceMaterialColumnParser(materials,"Chute Material", ComponentPreset.MATERIAL)); - } - - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.PARACHUTE; - } - - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.PARACHUTE; - } - - - @Override - protected void postProcess(TypedPropertyMap props) { - super.postProcess(props); - - // Fix the material since some files use bulk materials for streamers. - Double thickness = props.get( ComponentPreset.THICKNESS ); - Material.Surface myMaterial = (Material.Surface) props.get( ComponentPreset.MATERIAL ); - - Material.Surface m = materials.getSurfaceMaterial(myMaterial, thickness); - props.put(ComponentPreset.MATERIAL, m!=null ? m : myMaterial); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileColumnParser.java b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileColumnParser.java deleted file mode 100644 index cfaf091d..00000000 --- a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileColumnParser.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.TypedPropertyMap; - -public interface RocksimComponentFileColumnParser { - - /** - * Examine the array of column headers and configure parsing for this type. - * - * @param headers - */ - public void configure( String[] headers ); - - /** - * Examine the data array, parse the appropriate data and push into props. - * - * @param data - * @param props - */ - public void parse( String[] data, TypedPropertyMap props ); - -} diff --git a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileLoader.java b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileLoader.java deleted file mode 100644 index c0ca293c..00000000 --- a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileLoader.java +++ /dev/null @@ -1,276 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import au.com.bytecode.opencsv.CSVReader; -import net.sf.openrocket.gui.print.PrintUnit; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.ArrayList; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.util.List; - -/** - * Primary entry point for parsing component CSV files that are in Rocksim format. - */ -public abstract class RocksimComponentFileLoader { - - private static final PrintStream LOGGER = System.err; - - private String basePath = ""; - - private File dir; - - protected List fileColumns = new ArrayList(); - - /** - * Constructor. - * - * @param theBasePathToLoadFrom base path - */ - public RocksimComponentFileLoader(File theBasePathToLoadFrom) { - dir = theBasePathToLoadFrom; - basePath = dir.getAbsolutePath(); - } - - /** - * Constructor. - * - * @param theBasePathToLoadFrom base path - */ - public RocksimComponentFileLoader(String theBasePathToLoadFrom) { - dir = new File(basePath); - basePath = theBasePathToLoadFrom; - } - - protected abstract RocksimComponentFileType getFileType(); - - public void load() { - try { - load(getFileType()); - } catch (FileNotFoundException fex ) { - LOGGER.println( fex.getLocalizedMessage() ); - } - } - - /** - * Read a comma separated component file and return the parsed contents as a list of string arrays. Not for - * production use - just here for smoke testing. - * - * @param type the type of component file to read; uses the default file name - * - * @return a list (guaranteed never to be null) of string arrays. Each element of the list represents a row in the - * component data file; the element in the list itself is an array of String, where each item in the array - * is a column (cell) in the row. The string array is in sequential order as it appeared in the file. - */ - private void load(RocksimComponentFileType type) throws FileNotFoundException { - if (!dir.exists()) { - throw new IllegalArgumentException(basePath + " does not exist"); - } - if (!dir.isDirectory()) { - throw new IllegalArgumentException(basePath + " is not directory"); - } - if (!dir.canRead()) { - throw new IllegalArgumentException(basePath + " is not readable"); - } - FileInputStream fis = new FileInputStream(new File(dir, type.getDefaultFileName())); - load(fis); - } - - /** - * Read a comma separated component file and return the parsed contents as a list of string arrays. - * - * @param file the file to read and parse - * - * @return a list (guaranteed never to be null) of string arrays. Each element of the list represents a row in the - * component data file; the element in the list itself is an array of String, where each item in the array - * is a column (cell) in the row. The string array is in sequential order as it appeared in the file. - */ - private void load(File file) throws FileNotFoundException { - load(new FileInputStream(file)); - } - - /** - * Read a comma separated component file and return the parsed contents as a list of string arrays. - * - * @param is the stream to read and parse - * - * @return a list (guaranteed never to be null) of string arrays. Each element of the list represents a row in the - * component data file; the element in the list itself is an array of String, where each item in the array - * is a column (cell) in the row. The string array is in sequential order as it appeared in the file. - */ - private void load(InputStream is) { - if (is == null) { - return; - } - InputStreamReader r = null; - try { - r = new InputStreamReader(is); - - // Create the CSV reader. Use comma separator. - CSVReader reader = new CSVReader(r, ',', '\'', '\\'); - - //Read and throw away the header row. - parseHeaders(reader.readNext()); - - String[] data = null; - while ((data = reader.readNext()) != null) { - // detect empty lines and skip: - if (data.length == 0) { - continue; - } - if (data.length == 1 && "".equals(data[0].trim())) { - continue; - } - parseData(data); - } - //Read the rest of the file as data rows. - return; - } - catch (IOException e) { - } - finally { - if (r != null) { - try { - r.close(); - } - catch (IOException e) { - } - } - } - - } - - protected void parseHeaders(String[] headers) { - for (RocksimComponentFileColumnParser column : fileColumns) { - column.configure(headers); - } - } - - protected void parseData(String[] data) { - if (data == null || data.length == 0) { - return; - } - TypedPropertyMap props = new TypedPropertyMap(); - - preProcess(data); - - for (RocksimComponentFileColumnParser column : fileColumns) { - column.parse(data, props); - } - postProcess(props); - } - - protected void preProcess(String[] data) { - for (int i = 0; i < data.length; i++) { - String d = data[i]; - if (d == null) { - continue; - } - d = d.trim(); - d = stripAll(d, '"'); - - data[i] = d; - } - } - - protected abstract void postProcess(TypedPropertyMap props); - - /** - * Rocksim CSV units are either inches or mm. A value of 0 or "in." indicate inches. A value of 1 or "mm" indicate - * millimeters. - * - * @param units the value from the file - * - * @return true if it's inches - */ - protected static boolean isInches(String units) { - String tmp = units.trim().toLowerCase(); - return "0".equals(tmp) || tmp.startsWith("in"); - } - - /** - * Convert inches or millimeters to meters. - * - * @param units a Rocksim CSV string representing the kind of units. - * @param value the original value within the CSV file - * - * @return the value in meters - */ - protected static double convertLength(String units, double value) { - if (isInches(units)) { - return PrintUnit.INCHES.toMeters(value); - } - else { - return PrintUnit.MILLIMETERS.toMeters(value); - } - } - - protected static double convertMass(String units, double value) { - if ("oz".equals(units)) { - Unit u = UnitGroup.UNITS_MASS.getUnit(2); - return u.fromUnit(value); - } - return value; - } - - /** - * Remove all occurrences of the given character. Note: this is done because some manufacturers embed double quotes - * in their descriptions or material names. Those are stripped away because they cause all sorts of matching/lookup - * issues. - * - * @param target the target string to be operated upon - * @param toBeRemoved the character to remove - * - * @return target, minus every occurrence of toBeRemoved - */ - protected static String stripAll(String target, Character toBeRemoved) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < target.length(); i++) { - Character c = target.charAt(i); - if (!c.equals(toBeRemoved)) { - sb.append(c); - } - } - return sb.toString(); - } - - /** - * Convert all words in a given string to Camel Case (first letter capitalized). Words are assumed to be separated - * by a space. Note: this is done because some manufacturers define their material name in Camel Case but the - * component part references the material in lower case. That causes matching/lookup issues that's easiest handled - * this way (rather than converting everything to lower case. - * - * @param target the target string to be operated upon - * - * @return target, with the first letter of each word in uppercase - */ - protected static String toCamelCase(String target) { - StringBuilder sb = new StringBuilder(); - String[] t = target.split("[ ]"); - if (t != null && t.length > 0) { - for (String aT : t) { - String s = aT; - s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); - sb.append(s).append(" "); - } - return sb.toString().trim(); - } - else { - return target; - } - } - -} - -//Errata: -//The oddities I've found thus far in the stock Rocksim data: -//1. BTDATA.CSV - Totally Tubular goofed up their part no. and description columns (They messed up TCDATA also) -//2. NCDATA.CSV - Estes Balsa nose cones are classified as G10 Fiberglass -//3. TRDATA.CSV - Apogee Saturn LEM Transition has no part number; Balsa Machining transitions have blank diameter diff --git a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileTranslator.java b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileTranslator.java deleted file mode 100644 index d84fa1d8..00000000 --- a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileTranslator.java +++ /dev/null @@ -1,150 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.xml.OpenRocketComponentSaver; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.Startup; -import net.sf.openrocket.util.ArrayList; - -import java.io.File; -import java.io.FileWriter; -import java.io.PrintStream; -import java.io.StringReader; -import java.util.List; - -public class RocksimComponentFileTranslator { - - private static PrintStream LOGGER = System.err; - - private static void printUsage() { - LOGGER.println("RocksimComponentFileLoader "); - LOGGER.println(" is base directory for a set of Rocksim component csv files"); - LOGGER.println(" is where the orc file is written"); - } - - public static void main(String[] args) throws Exception { - - // How to control logging? - - if (args.length < 2 || args.length > 2) { - printUsage(); - throw new IllegalArgumentException("Invalid Command Line Params"); - } - - List allPresets = new ArrayList(); - - LOGGER.println("Loading csv files from directory " + args[0]); - - Startup.initializeLogging(); - Application.setPreferences(new SwingPreferences()); - - MaterialHolder materialMap = loadAll(allPresets, new File(args[0])); - LOGGER.println("\tMarshalling to XML"); - String xml = new OpenRocketComponentSaver().marshalToOpenRocketComponent(new ArrayList(materialMap.values()), allPresets); - - // Try parsing the file - LOGGER.println("\tValidating XML"); - // Throw away the result, we're just parsing for validation. - new OpenRocketComponentSaver().unmarshalFromOpenRocketComponent(new StringReader(xml)); - - LOGGER.println("\tWriting to file " + args[1]); - File outfile = new File(args[1]); - FileWriter fos = new FileWriter(outfile); - fos.write(xml); - fos.flush(); - fos.close(); - } - - /** - * Set a print stream as a logger. Defaults to System.err. - * - * @param ps a stream to log to - */ - public static void setLogger(PrintStream ps) { - if (ps != null) { - LOGGER = ps; - } - } - - /** - * Load all presets. The loaded presets are added to the list parameter. The loaded materials are returned in the - * MaterialHolder instance. - * - * @param theAllPresets a list of ComponentPreset that gets populated as the result of loading; must not be null on - * invocation - * - * @return a holder of the materials loaded - */ - public static MaterialHolder loadAll(final List theAllPresets, File theBasePathToLoadFrom) { - MaterialLoader mats = new MaterialLoader(theBasePathToLoadFrom); - mats.load(); - - MaterialHolder materialMap = mats.getMaterialMap(); - LOGGER.println("\tMaterial types loaded: " + materialMap.size()); - - { - BodyTubeLoader bts = new BodyTubeLoader(materialMap, theBasePathToLoadFrom); - bts.load(); - theAllPresets.addAll(bts.getPresets()); - LOGGER.println("\tBody Tubes loaded: " + bts.getPresets().size()); - } - { - BulkHeadLoader bhs = new BulkHeadLoader(materialMap, theBasePathToLoadFrom); - bhs.load(); - theAllPresets.addAll(bhs.getPresets()); - LOGGER.println("\tBulkheads loaded: " + bhs.getPresets().size()); - } - { - CenteringRingLoader crs = new CenteringRingLoader(materialMap, theBasePathToLoadFrom); - crs.load(); - theAllPresets.addAll(crs.getPresets()); - LOGGER.println("\tCentering Rings loaded: " + crs.getPresets().size()); - } - { - TubeCouplerLoader tcs = new TubeCouplerLoader(materialMap, theBasePathToLoadFrom); - tcs.load(); - theAllPresets.addAll(tcs.getPresets()); - LOGGER.println("\tTube Couplers loaded: " + tcs.getPresets().size()); - } - { - EngineBlockLoader ebs = new EngineBlockLoader(materialMap, theBasePathToLoadFrom); - ebs.load(); - theAllPresets.addAll(ebs.getPresets()); - LOGGER.println("\tEngine Blocks loaded: " + ebs.getPresets().size()); - } - { - NoseConeLoader ncs = new NoseConeLoader(materialMap, theBasePathToLoadFrom); - ncs.load(); - theAllPresets.addAll(ncs.getPresets()); - LOGGER.println("\tNose Cones loaded: " + ncs.getPresets().size()); - } - { - TransitionLoader trs = new TransitionLoader(materialMap, theBasePathToLoadFrom); - trs.load(); - theAllPresets.addAll(trs.getPresets()); - LOGGER.println("\tTransitions loaded: " + trs.getPresets().size()); - } - { - LaunchLugLoader lls = new LaunchLugLoader(materialMap, theBasePathToLoadFrom); - lls.load(); - theAllPresets.addAll(lls.getPresets()); - LOGGER.println("\tLaunch Lugs loaded: " + lls.getPresets().size()); - } - { - StreamerLoader sts = new StreamerLoader(materialMap, theBasePathToLoadFrom); - sts.load(); - theAllPresets.addAll(sts.getPresets()); - LOGGER.println("\tStreamers loaded: " + sts.getPresets().size()); - } - { - ParachuteLoader pcs = new ParachuteLoader(materialMap, theBasePathToLoadFrom); - pcs.load(); - theAllPresets.addAll(pcs.getPresets()); - LOGGER.println("Parachutes loaded: " + pcs.getPresets().size()); - } - return materialMap; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileType.java b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileType.java deleted file mode 100644 index 13ac8620..00000000 --- a/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileType.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import java.util.Arrays; - -/** - * Definition of the typical Rocksim component files and their formats. - */ -public enum RocksimComponentFileType { - BODY_TUBE("BTDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "ID", "OD", "Length", "Material", "Engine"), - BULKHEAD("BHDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "ID", "OD", "Length", "Material", "Engine", "Engine", - "Engine", "Engine", "Engine", "Engine", "Engine", "Engine", "Engine", "Engine", "Engine"), - CENTERING_RING("CRDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "ID", "OD", "Length", "Material", "AutoSize"), - CUSTOM_FIN("CSDATA.CSV"), - ENGINE_BLOCK("EBDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "ID", "OD", "Length", "Material", "CG", "Mass Units", "Mass", "AutoSize"), - FIN("FSDATA.CSV"), - LAUNCH_LUG("LLDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "ID", "OD", "Length", "Material"), - MASS_OBJECT("MODATA.CSV", "Mfg.", "Part no", "Desc", "Units", "Name", "Type", "Length", "Material", "Mass units", "Mass"), - MATERIAL("MATERIAL.CSV", "Material Name", "Units", "Density", "Low", "High", "Class", "Rocketry Use", "Body Tubes", - "Fin Sets", "Launch Lugs", "Cords", "Nose", "Chute", "Stream", "Trans", "Ring", "Bulkhead", "Engine Block", "Sleeve", - "Tube Coupler", "spare", "spare", "spare", "spare", "spare", "spare", "spare", "Known Dim type", "Known Dim Units", "Known Dim Value"), - NOSE_CONE("NCDATA.CSV", "Mfg.","Part No.","Desc.","Units","Length","Outer Dia","L/D Ratio","Insert Length","Insert OD", - "Thickness","Shape","Config","Material","CG Loc","Mass Units","Mass","Base Ext. Len"), - PARACHUTE("PCDATA.CSV"), - SLEEVE("SLDATA.CSV"), - STREAMER("STDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "Length", "Width", "Thickness", "Count", "Material"), - TUBE_COUPLER("TCDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "ID", "OD", "Length", "Material", "Mass Units", "CG", "Mass", "AutoSize"), - TRANSITION("TRDATA.CSV", "Mfg.", "Part No.", "Desc.", "Units", "Front Insert Len", "Front Insert OD", "Front OD", "Length", - "Rear OD", "Core Dia.", "Rear Insert Len", "Rear Insert OD", "Thickness", "Config", "Material", "CG Loc", - "Mass Units", "Mass", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape", "Shape"); - - /** - * The default filename for the type of data. - */ - private final String defaultFileName; - - /** - * The column names. - */ - private final String[] columns; - - /** - * Constructor. - * - * @param theDefaultFileName the default filename - * @param theColumns the array of column names in the file - */ - private RocksimComponentFileType(final String theDefaultFileName, String... theColumns) { - defaultFileName = theDefaultFileName; - columns = theColumns; - } - - /** - * Get the typical file name used for this type of component data. - * - * @return a filename - */ - public String getDefaultFileName() { - return defaultFileName; - } - - /** - * Try to be omniscient and figure out what kind of data file it is given an array of header (column) names. - * - * @param headers an array of column names - * @return the data type of the file, or null if unable to match the header names - */ - public static RocksimComponentFileType determineType(String[] headers) { - RocksimComponentFileType[] types = values(); - for (int i = 0; i < types.length; i++) { - RocksimComponentFileType type = types[i]; - if (Arrays.equals(headers, type.columns)) { - return type; - } - } - return null; - } -} diff --git a/core/src/net/sf/openrocket/preset/loader/ShapeColumnParser.java b/core/src/net/sf/openrocket/preset/loader/ShapeColumnParser.java deleted file mode 100644 index 05ea4e88..00000000 --- a/core/src/net/sf/openrocket/preset/loader/ShapeColumnParser.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import java.util.Locale; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.Transition.Shape; -import net.sf.openrocket.util.BugException; - -public class ShapeColumnParser extends BaseColumnParser { - - public ShapeColumnParser() { - super("Shape"); - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - Transition.Shape shape = null; - String lc = columnData.toLowerCase(Locale.US); - if ( "ogive".equals(lc) ) { - shape = Shape.OGIVE; - } - if ( "conical".equals(lc) ) { - shape = Shape.CONICAL; - } - if ( "cone".equals(lc) ) { - shape = Shape.CONICAL; - } - if ( "elliptical".equals(lc) ) { - shape = Shape.ELLIPSOID; - } - if ( "parabolic".equals(lc) ) { - shape = Shape.PARABOLIC; - } - if ( "sears-haack".equals(lc) ) { - shape = Shape.HAACK; - } - if ( "power-series".equals(lc) ) { - shape = Shape.POWER; - } - // guessing at what "ps" means. I think it might be power series. - if ( "ps".equals(lc) ) { - shape = Shape.POWER; - } - if ( "1".equals(lc) ) { - shape = Shape.OGIVE; - } - if( "0". equals(lc) ) { - shape = Shape.CONICAL; - } - if( "". equals(lc) ) { - shape = Shape.CONICAL; - } - if ( "3".equals(lc) ) { - shape = Shape.ELLIPSOID; - } - if ( shape == null ) { - throw new BugException("Invalid shape parameter: " + columnData); - } - props.put(ComponentPreset.SHAPE, shape); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/StreamerLoader.java b/core/src/net/sf/openrocket/preset/loader/StreamerLoader.java deleted file mode 100644 index 403ea0f6..00000000 --- a/core/src/net/sf/openrocket/preset/loader/StreamerLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.preset.TypedPropertyMap; - -import java.io.File; - -public class StreamerLoader extends BaseComponentLoader { - - private final MaterialHolder materials; - - public StreamerLoader(MaterialHolder theMaterials, File theBasePath) { - super(theMaterials, theBasePath); - materials = theMaterials; - - //The base component loader adds a bulk material loader, which is incompatible with the surface loader - //for a streamer. Remove the file column parser here so we can set your own in the code that follows. - for (int i = 0; i < fileColumns.size(); i++) { - RocksimComponentFileColumnParser rocksimComponentFileColumnParser = fileColumns.get(i); - if (rocksimComponentFileColumnParser instanceof MaterialColumnParser) { - fileColumns.remove(rocksimComponentFileColumnParser); - } - } - - fileColumns.add(new SurfaceMaterialColumnParser(materials,"Material",ComponentPreset.MATERIAL)); - fileColumns.add(new DoubleUnitColumnParser("Length","Units",ComponentPreset.LENGTH)); - fileColumns.add(new DoubleUnitColumnParser("Width","Units",ComponentPreset.WIDTH)); - fileColumns.add(new DoubleUnitColumnParser("Thickness","Units",ComponentPreset.THICKNESS)); - } - - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.STREAMER; - } - - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.STREAMER; - } - - - @Override - protected void postProcess(TypedPropertyMap props) { - super.postProcess(props); - - // Fix the material since some files use bulk materials for streamers. - Double thickness = props.get( ComponentPreset.THICKNESS ); - Material.Surface myMaterial = (Material.Surface) props.get( ComponentPreset.MATERIAL ); - - Material.Surface m = materials.getSurfaceMaterial(myMaterial, thickness); - - props.put(ComponentPreset.MATERIAL, m!=null? m : myMaterial); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/StringColumnParser.java b/core/src/net/sf/openrocket/preset/loader/StringColumnParser.java deleted file mode 100644 index c4d96a70..00000000 --- a/core/src/net/sf/openrocket/preset/loader/StringColumnParser.java +++ /dev/null @@ -1,20 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class StringColumnParser extends BaseColumnParser { - - private TypedKey propKey; - - public StringColumnParser(String columnHeader, TypedKey propKey) { - super(columnHeader); - this.propKey = propKey; - } - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - props.put(propKey, columnData); - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/SurfaceMaterialColumnParser.java b/core/src/net/sf/openrocket/preset/loader/SurfaceMaterialColumnParser.java deleted file mode 100644 index 703d128c..00000000 --- a/core/src/net/sf/openrocket/preset/loader/SurfaceMaterialColumnParser.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.TypedKey; -import net.sf.openrocket.preset.TypedPropertyMap; - -public class SurfaceMaterialColumnParser extends BaseColumnParser { - - private final MaterialHolder materialMap; - - private final TypedKey param; - - public SurfaceMaterialColumnParser(MaterialHolder materialMap, String columnName, TypedKey param) { - super(columnName); - this.param = param; - this.materialMap = materialMap; - } - - - @Override - protected void doParse(String columnData, String[] data, TypedPropertyMap props) { - - if (columnData == null || "".equals(columnData.trim())) { - return; - } - - Material.Surface myMaterial = (Material.Surface) Databases.findMaterial(Material.Type.SURFACE, columnData, 0.0); - Material.Surface m = materialMap.getSurfaceMaterial(myMaterial, null); - props.put(param, m != null ? m : myMaterial); - - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/TransitionLoader.java b/core/src/net/sf/openrocket/preset/loader/TransitionLoader.java deleted file mode 100644 index a67695b5..00000000 --- a/core/src/net/sf/openrocket/preset/loader/TransitionLoader.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; - -import java.io.File; - -public class TransitionLoader extends NoseConeLoader { - - public TransitionLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - fileColumns.add(new DoubleUnitColumnParser("Front Insert Len","Units",ComponentPreset.FORE_SHOULDER_LENGTH)); - fileColumns.add(new DoubleUnitColumnParser("Front Insert OD","Units",ComponentPreset.FORE_SHOULDER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Front OD","Units",ComponentPreset.FORE_OUTER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Rear Insert Len","Units",ComponentPreset.AFT_SHOULDER_LENGTH)); - fileColumns.add(new DoubleUnitColumnParser("Rear Insert OD","Units",ComponentPreset.AFT_SHOULDER_DIAMETER)); - fileColumns.add(new DoubleUnitColumnParser("Rear OD","Units",ComponentPreset.AFT_OUTER_DIAMETER)); - } - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.TRANSITION; - } - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.TRANSITION; - } - -} diff --git a/core/src/net/sf/openrocket/preset/loader/TubeCouplerLoader.java b/core/src/net/sf/openrocket/preset/loader/TubeCouplerLoader.java deleted file mode 100644 index 3a5706bc..00000000 --- a/core/src/net/sf/openrocket/preset/loader/TubeCouplerLoader.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.preset.loader; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; - -import java.io.File; - -public class TubeCouplerLoader extends BodyTubeLoader { - - public TubeCouplerLoader(MaterialHolder materials, File theBasePath) { - super(materials, theBasePath); - } - - @Override - protected Type getComponentPresetType() { - return ComponentPreset.Type.TUBE_COUPLER; - } - - @Override - protected RocksimComponentFileType getFileType() { - return RocksimComponentFileType.TUBE_COUPLER; - } - -} diff --git a/core/src/net/sf/openrocket/preset/xml/BaseComponentDTO.java b/core/src/net/sf/openrocket/preset/xml/BaseComponentDTO.java deleted file mode 100644 index ca8c18fd..00000000 --- a/core/src/net/sf/openrocket/preset/xml/BaseComponentDTO.java +++ /dev/null @@ -1,282 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.xml.bind.DatatypeConverter; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlInlineBinaryData; -import javax.xml.bind.annotation.XmlValue; -import javax.xml.bind.annotation.adapters.XmlAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.unit.UnitGroup; - -/** - * Base class for the external representation of all component presets. - */ -@XmlAccessorType(XmlAccessType.FIELD) -public abstract class BaseComponentDTO { - - @XmlElement(name = "Manufacturer") - private String manufacturer; - @XmlElement(name = "PartNumber") - private String partNo; - @XmlElement(name = "Description") - private String description; - @XmlElement(name = "Material") - private AnnotatedMaterialDTO material; - @XmlElement(name = "Mass") - private AnnotatedMassDTO mass; - @XmlElement(name = "Filled") - private Boolean filled; - @XmlInlineBinaryData - @XmlJavaTypeAdapter(Base64Adapter.class) - @XmlElement(name = "Thumbnail") - private byte[] image; - - /** - * Default constructor. - */ - protected BaseComponentDTO() { - } - - /** - * Constructor. - * - * @param preset the preset to use to pull data values out of - * - * @throws net.sf.openrocket.util.BugException thrown if the expected body tube keys are not in the preset - */ - protected BaseComponentDTO(final ComponentPreset preset) { - setManufacturer(preset.getManufacturer().getSimpleName()); - setPartNo(preset.getPartNo()); - if (preset.has(ComponentPreset.DESCRIPTION)) { - setDescription(preset.get(ComponentPreset.DESCRIPTION)); - } - if (preset.has(ComponentPreset.MATERIAL)) { - setMaterial(new AnnotatedMaterialDTO(preset.get(ComponentPreset.MATERIAL))); - } - if (preset.has(ComponentPreset.MASS)) { - setMass(preset.get(ComponentPreset.MASS)); - } - if (preset.has(ComponentPreset.FILLED)) { - setFilled(preset.get(ComponentPreset.FILLED)); - } - if (preset.has(ComponentPreset.IMAGE)) { - setImageData(preset.get(ComponentPreset.IMAGE)); - } - } - - public String getManufacturer() { - return manufacturer; - } - - public void setManufacturer(final String theManufacturer) { - manufacturer = theManufacturer; - } - - public String getPartNo() { - return partNo; - } - - public void setPartNo(final String thePartNo) { - partNo = thePartNo; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String theDescription) { - description = theDescription; - } - - public AnnotatedMaterialDTO getMaterial() { - return material; - } - - public void setMaterial(final AnnotatedMaterialDTO theMaterial) { - material = theMaterial; - } - - public double getMass() { - return mass.getValue(); - } - - public void setMass(final AnnotatedMassDTO theMass) { - mass = theMass; - } - - public void setMass(final double theMass) { - mass = new AnnotatedMassDTO(theMass); - } - - public Boolean getFilled() { - return filled; - } - - public void setFilled(Boolean filled) { - this.filled = filled; - } - - public byte[] getImageData() { - return image; - } - - public void setImageData(final byte[] theImage) { - image = theImage; - } - - public BufferedImage getImage() throws IOException { - if (image != null) { - return ImageIO.read(new ByteArrayInputStream(image)); - } - return null; - } - - public void setImage(BufferedImage theImage) throws IOException { - if (theImage != null) { - final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ImageIO.write(theImage, "png", byteArrayOutputStream); - image = byteArrayOutputStream.toByteArray(); - } - } - - public abstract ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException; - - void addProps(TypedPropertyMap props, List materialList) { - props.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer(manufacturer)); - props.put(ComponentPreset.PARTNO, partNo); - if (description != null) { - props.put(ComponentPreset.DESCRIPTION, description); - } - Material m = find(materialList, material); - if (m != null) { - props.put(ComponentPreset.MATERIAL, find(materialList, material)); - } - if (mass != null) { - props.put(ComponentPreset.MASS, getMass()); - } - if (filled != null) { - props.put(ComponentPreset.FILLED, getFilled()); - } - if (image != null) { - props.put(ComponentPreset.IMAGE, image); - } - } - - protected Material find(List materialList, AnnotatedMaterialDTO dto) { - if (dto == null) { - return null; - } - for (int i = 0; i < materialList.size(); i++) { - MaterialDTO materialDTO = materialList.get(i); - if (materialDTO.getType().name().equals(dto.type) && materialDTO.getName().equals(dto.material)) { - return materialDTO.asMaterial(); - } - } - - // Don't have one, first check OR's database - Material m = Databases.findMaterial(dto.getORMaterialType(), dto.material); - if (m != null) { - return m; - } - - return Databases.findMaterial(dto.getORMaterialType(), dto.material, 0.0); - - } - - static class AnnotatedMaterialDTO { - @XmlAttribute(name = "Type") - private String type; - @XmlValue - private String material; - - AnnotatedMaterialDTO() { - } - - AnnotatedMaterialDTO(Material theMaterial) { - type = theMaterial.getType().name(); - material = theMaterial.getName(); - } - - public Material.Type getORMaterialType() { - if ("BULK".equals(type)) { - return Material.Type.BULK; - } else if ("SURFACE".equals(type)) { - return Material.Type.SURFACE; - } else if ("LINE".equals(type)) { - return Material.Type.LINE; - } - throw new IllegalArgumentException("Inavlid material type " + type + " specified for Component"); - } - } - - static class AnnotatedLengthDTO { - @XmlAttribute(name = "Unit", required = false) - private String unitName = "m"; - @XmlValue - private double length; - - AnnotatedLengthDTO() { - } - - AnnotatedLengthDTO(double length) { - this.length = length; - } - - public double getValue() { - return UnitGroup.UNITS_LENGTH.getUnit(unitName).fromUnit(length); - } - } - - static class AnnotatedMassDTO { - @XmlAttribute(name = "Unit", required = false) - private String unitName = "kg"; - @XmlValue - private double mass; - - AnnotatedMassDTO() { - } - - AnnotatedMassDTO(double mass) { - this.mass = mass; - } - - public double getValue() { - return UnitGroup.UNITS_MASS.getUnit(unitName).fromUnit(mass); - } - } - - static class Base64Adapter extends XmlAdapter { - @Override - public byte[] unmarshal(String s) { - if (s == null) { - return null; - } - return DatatypeConverter.parseBase64Binary(s); - } - - @Override - public String marshal(byte[] bytes) { - if (bytes == null) { - return null; - } - return DatatypeConverter.printBase64Binary(bytes); - } - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/BodyTubeDTO.java b/core/src/net/sf/openrocket/preset/xml/BodyTubeDTO.java deleted file mode 100644 index 536944f2..00000000 --- a/core/src/net/sf/openrocket/preset/xml/BodyTubeDTO.java +++ /dev/null @@ -1,100 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Body tube preset XML handler. - */ -@XmlRootElement(name = "BodyTube") -@XmlAccessorType(XmlAccessType.FIELD) -public class BodyTubeDTO extends BaseComponentDTO { - - @XmlElement(name = "InsideDiameter") - private AnnotatedLengthDTO insideDiameter; - @XmlElement(name = "OutsideDiameter") - private AnnotatedLengthDTO outsideDiameter; - @XmlElement(name = "Length") - private AnnotatedLengthDTO length; - - /** - * Default constructor. - */ - public BodyTubeDTO() { - } - - /** - * Most-useful constructor that maps a BodyTube preset to a BodyTubeDTO. - * - * @param preset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected body tube keys are not in the preset - */ - public BodyTubeDTO(final ComponentPreset preset) { - super(preset); - setInsideDiameter(preset.get(ComponentPreset.INNER_DIAMETER)); - setOutsideDiameter(preset.get(ComponentPreset.OUTER_DIAMETER)); - setLength(preset.get(ComponentPreset.LENGTH)); - } - - public double getInsideDiameter() { - return insideDiameter.getValue(); - } - - public void setInsideDiameter( final AnnotatedLengthDTO theLength ) { - insideDiameter = theLength; - } - - public void setInsideDiameter(final double theId) { - insideDiameter = new AnnotatedLengthDTO(theId); - } - - public double getOutsideDiameter() { - return outsideDiameter.getValue(); - } - - public void setOutsideDiameter(final AnnotatedLengthDTO theOd) { - outsideDiameter = theOd; - } - - public void setOutsideDiameter(final double theOd) { - outsideDiameter = new AnnotatedLengthDTO(theOd); - } - - public double getLength() { - return length.getValue(); - } - - public void setLength(final AnnotatedLengthDTO theLength) { - length = theLength; - } - - public void setLength(final double theLength) { - length = new AnnotatedLengthDTO(theLength); - } - - @Override - public ComponentPreset asComponentPreset(java.util.List materials) throws InvalidComponentPresetException { - return asComponentPreset(ComponentPreset.Type.BODY_TUBE, materials); - } - - public ComponentPreset asComponentPreset(ComponentPreset.Type type, List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - props.put(ComponentPreset.INNER_DIAMETER, this.getInsideDiameter()); - props.put(ComponentPreset.OUTER_DIAMETER, this.getOutsideDiameter()); - props.put(ComponentPreset.LENGTH, this.getLength()); - props.put(ComponentPreset.TYPE, type); - - return ComponentPresetFactory.create(props); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/BulkHeadDTO.java b/core/src/net/sf/openrocket/preset/xml/BulkHeadDTO.java deleted file mode 100644 index 1db3dd7d..00000000 --- a/core/src/net/sf/openrocket/preset/xml/BulkHeadDTO.java +++ /dev/null @@ -1,78 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Bulkhead preset XML handler. - */ -@XmlRootElement(name = "BulkHead") -@XmlAccessorType(XmlAccessType.FIELD) -public class BulkHeadDTO extends BaseComponentDTO { - - @XmlElement(name = "OutsideDiameter") - private AnnotatedLengthDTO outsideDiameter; - @XmlElement(name = "Length") - private AnnotatedLengthDTO length; - - public BulkHeadDTO() { - } - - /** - * Most-useful constructor that maps a BulkHead preset to a BulkHeadDTO. - * - * @param thePreset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected bulk head keys are not in the preset - */ - public BulkHeadDTO(final ComponentPreset thePreset) { - super(thePreset); - setOutsideDiameter(thePreset.get(ComponentPreset.OUTER_DIAMETER)); - setLength(thePreset.get(ComponentPreset.LENGTH)); - } - - public double getOutsideDiameter() { - return outsideDiameter.getValue(); - } - - public void setOutsideDiameter(final AnnotatedLengthDTO theOutsideDiameter) { - outsideDiameter = theOutsideDiameter; - } - - public void setOutsideDiameter(final double theOutsideDiameter) { - outsideDiameter = new AnnotatedLengthDTO(theOutsideDiameter); - } - - public double getLength() { - return length.getValue(); - } - - public void setLength(final AnnotatedLengthDTO theLength) { - length = theLength; - } - - public void setLength(final double theLength) { - length = new AnnotatedLengthDTO(theLength); - } - - @Override - public ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - props.put(ComponentPreset.OUTER_DIAMETER, this.getOutsideDiameter()); - props.put(ComponentPreset.LENGTH, this.getLength()); - props.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - - return ComponentPresetFactory.create(props); - } - -} diff --git a/core/src/net/sf/openrocket/preset/xml/CenteringRingDTO.java b/core/src/net/sf/openrocket/preset/xml/CenteringRingDTO.java deleted file mode 100644 index 9866a15a..00000000 --- a/core/src/net/sf/openrocket/preset/xml/CenteringRingDTO.java +++ /dev/null @@ -1,41 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; - -/** - * Centering Ring preset XML handler. - */ -@XmlRootElement(name = "CenteringRing") -@XmlAccessorType(XmlAccessType.FIELD) -public class CenteringRingDTO extends BodyTubeDTO { - - /** - * Default constructor. - */ - public CenteringRingDTO() { - } - - /** - * Most-useful constructor that maps a TubeCoupler preset to a TubeCouplerDTO. - * - * @param thePreset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected tube coupler keys are not in the preset - */ - public CenteringRingDTO(ComponentPreset thePreset) { - super(thePreset); - } - - @Override - public ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException { - return super.asComponentPreset(ComponentPreset.Type.CENTERING_RING, materials); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/EngineBlockDTO.java b/core/src/net/sf/openrocket/preset/xml/EngineBlockDTO.java deleted file mode 100644 index 6c3f61fa..00000000 --- a/core/src/net/sf/openrocket/preset/xml/EngineBlockDTO.java +++ /dev/null @@ -1,40 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Engine block preset XML handler. - */ -@XmlRootElement(name = "EngineBlock") -@XmlAccessorType(XmlAccessType.FIELD) -public class EngineBlockDTO extends BodyTubeDTO { - - /** - * Default constructor. - */ - public EngineBlockDTO() { - } - - /** - * Most-useful constructor that maps a EngineBlock preset to a EngineBlockDTO. - * - * @param thePreset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected engine block keys are not in the preset - */ - public EngineBlockDTO(ComponentPreset thePreset) { - super(thePreset); - } - - @Override - public ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException { - return super.asComponentPreset(ComponentPreset.Type.ENGINE_BLOCK, materials); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/LaunchLugDTO.java b/core/src/net/sf/openrocket/preset/xml/LaunchLugDTO.java deleted file mode 100644 index e723861b..00000000 --- a/core/src/net/sf/openrocket/preset/xml/LaunchLugDTO.java +++ /dev/null @@ -1,100 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Body tube preset XML handler. - */ -@XmlRootElement(name = "LaunchLug") -@XmlAccessorType(XmlAccessType.FIELD) -public class LaunchLugDTO extends BaseComponentDTO { - - @XmlElement(name = "InsideDiameter") - private AnnotatedLengthDTO insideDiameter; - @XmlElement(name = "OutsideDiameter") - private AnnotatedLengthDTO outsideDiameter; - @XmlElement(name = "Length") - private AnnotatedLengthDTO length; - - /** - * Default constructor. - */ - public LaunchLugDTO() { - } - - /** - * Most-useful constructor that maps a LaunchLug preset to a LaunchLugDTO. - * - * @param preset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected body tube keys are not in the preset - */ - public LaunchLugDTO(final ComponentPreset preset) { - super(preset); - setInsideDiameter(preset.get(ComponentPreset.INNER_DIAMETER)); - setOutsideDiameter(preset.get(ComponentPreset.OUTER_DIAMETER)); - setLength(preset.get(ComponentPreset.LENGTH)); - } - - public double getInsideDiameter() { - return insideDiameter.getValue(); - } - - public void setInsideDiameter( final AnnotatedLengthDTO theLength ) { - insideDiameter = theLength; - } - - public void setInsideDiameter(final double theId) { - insideDiameter = new AnnotatedLengthDTO(theId); - } - - public double getOutsideDiameter() { - return outsideDiameter.getValue(); - } - - public void setOutsideDiameter(final AnnotatedLengthDTO theOd) { - outsideDiameter = theOd; - } - - public void setOutsideDiameter(final double theOd) { - outsideDiameter = new AnnotatedLengthDTO(theOd); - } - - public double getLength() { - return length.getValue(); - } - - public void setLength(final AnnotatedLengthDTO theLength) { - length = theLength; - } - - public void setLength(final double theLength) { - length = new AnnotatedLengthDTO(theLength); - } - - @Override - public ComponentPreset asComponentPreset(java.util.List materials) throws InvalidComponentPresetException { - return asComponentPreset(ComponentPreset.Type.LAUNCH_LUG, materials); - } - - public ComponentPreset asComponentPreset(ComponentPreset.Type type, List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - props.put(ComponentPreset.INNER_DIAMETER, this.getInsideDiameter()); - props.put(ComponentPreset.OUTER_DIAMETER, this.getOutsideDiameter()); - props.put(ComponentPreset.LENGTH, this.getLength()); - props.put(ComponentPreset.TYPE, type); - - return ComponentPresetFactory.create(props); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/MaterialDTO.java b/core/src/net/sf/openrocket/preset/xml/MaterialDTO.java deleted file mode 100644 index abcebda7..00000000 --- a/core/src/net/sf/openrocket/preset/xml/MaterialDTO.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.util.Chars; - -/** - * XML handler for materials. - */ -@XmlRootElement(name = "Material") -@XmlAccessorType(XmlAccessType.FIELD) -public class MaterialDTO { - - @XmlElement(name = "Name") - private String name; - @XmlElement(name = "Density") - private double density; - @XmlElement(name = "Type") - private MaterialTypeDTO type; - @XmlAttribute(name = "UnitsOfMeasure") - private String uom; - - /** - * Default constructor. - */ - public MaterialDTO() { - } - - public MaterialDTO(final Material theMaterial) { - this(theMaterial.getName(), theMaterial.getDensity(), MaterialTypeDTO.asDTO(theMaterial.getType()), - theMaterial.getType().getUnitGroup().getDefaultUnit().toString()); - } - - public MaterialDTO(final String theName, final double theDensity, final MaterialTypeDTO theType, final String theUom) { - name = theName; - density = theDensity; - type = theType; - uom = theUom; - } - - public String getName() { - return name; - } - - public void setName(final String theName) { - name = theName; - } - - public double getDensity() { - return density; - } - - public void setDensity(final double theDensity) { - density = theDensity; - } - - public MaterialTypeDTO getType() { - return type; - } - - public void setType(final MaterialTypeDTO theType) { - type = theType; - } - - public String getUom() { - return uom; - } - - public void setUom(final String theUom) { - uom = theUom; - } - - Material asMaterial() { - return Databases.findMaterial(type.getORMaterialType(), name, density); - } - - - /** - * Special directive to the JAXB system. After the object is parsed from xml, - * we replace the '2' with Chars.SQUARED, and '3' with Chars.CUBED. Just the - * opposite transformation as doen in beforeMarshal. - * @param unmarshaller - * @param parent - */ - @SuppressWarnings("unused") - private void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { - if (uom != null) { - uom = uom.replace('2', Chars.SQUARED); - uom = uom.replace('3', Chars.CUBED); - } - } - - /** - * Special directive to the JAXB system. Before the object is serialized into xml, - * we strip out the special unicode characters for cubed and squared so they appear - * as simple "3" and "2" chars. The reverse transformation is done in afterUnmarshal. - * @param marshaller - */ - @SuppressWarnings("unused") - private void beforeMarshal(Marshaller marshaller) { - if (uom != null) { - uom = uom.replace(Chars.SQUARED, '2'); - uom = uom.replace(Chars.CUBED, '3'); - } - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/MaterialTypeDTO.java b/core/src/net/sf/openrocket/preset/xml/MaterialTypeDTO.java deleted file mode 100644 index 93a83b35..00000000 --- a/core/src/net/sf/openrocket/preset/xml/MaterialTypeDTO.java +++ /dev/null @@ -1,35 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.material.Material; - -/** - * A mirror enum of Material.Type, for the purposes of mapping to/from an XML representation. - */ -public enum MaterialTypeDTO { - - LINE (Material.Type.LINE), - SURFACE (Material.Type.SURFACE), - BULK (Material.Type.BULK); - - private Material.Type corollary; - - private MaterialTypeDTO(final Material.Type theCorollary) { - corollary = theCorollary; - } - - public static MaterialTypeDTO asDTO(Material.Type targetType) { - MaterialTypeDTO[] values = values(); - for (int i = 0; i < values.length; i++) { - MaterialTypeDTO value = values[i]; - if (value.corollary.equals(targetType)) { - return value; - } - } - return BULK; //default - } - - public Material.Type getORMaterialType() { - return corollary; - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/NoseConeDTO.java b/core/src/net/sf/openrocket/preset/xml/NoseConeDTO.java deleted file mode 100644 index 0a071d6c..00000000 --- a/core/src/net/sf/openrocket/preset/xml/NoseConeDTO.java +++ /dev/null @@ -1,154 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -/** - * A NoseCone preset XML handler. - */ -@XmlRootElement(name = "NoseCone") -@XmlAccessorType(XmlAccessType.FIELD) -public class NoseConeDTO extends BaseComponentDTO { - - @XmlElement(name = "Shape") - private ShapeDTO shape; - @XmlElement(name = "OutsideDiameter") - private AnnotatedLengthDTO outsideDiameter; - @XmlElement(name = "ShoulderDiameter") - private AnnotatedLengthDTO shoulderDiameter; - @XmlElement(name = "ShoulderLength") - private AnnotatedLengthDTO shoulderLength; - @XmlElement(name = "Length") - private AnnotatedLengthDTO length; - - @XmlElement(name = "Thickness") - private AnnotatedLengthDTO thickness; - - /** - * Default constructor. - */ - public NoseConeDTO() { - } - - /** - * Constructor that - * - * @param thePreset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected body tube keys are not in the preset - */ - public NoseConeDTO(final ComponentPreset thePreset) { - super(thePreset); - setShape(ShapeDTO.asDTO(thePreset.get(ComponentPreset.SHAPE))); - setOutsideDiameter(thePreset.get(ComponentPreset.AFT_OUTER_DIAMETER)); - if ( thePreset.has(ComponentPreset.AFT_SHOULDER_DIAMETER)) { - setShoulderDiameter(thePreset.get(ComponentPreset.AFT_SHOULDER_DIAMETER)); - } - if ( thePreset.has(ComponentPreset.AFT_SHOULDER_LENGTH)) { - setShoulderLength(thePreset.get(ComponentPreset.AFT_SHOULDER_LENGTH)); - } - setLength(thePreset.get(ComponentPreset.LENGTH)); - if ( thePreset.has(ComponentPreset.THICKNESS)) { - setThickness(thePreset.get(ComponentPreset.THICKNESS)); - } - } - - public ShapeDTO getShape() { - return shape; - } - - public void setShape(final ShapeDTO theShape) { - shape = theShape; - } - - public double getOutsideDiameter() { - return outsideDiameter.getValue(); - } - - public void setOutsideDiameter(final AnnotatedLengthDTO theOutsideDiameter) { - outsideDiameter = theOutsideDiameter; - } - - public void setOutsideDiameter(final double theOutsideDiameter) { - outsideDiameter = new AnnotatedLengthDTO(theOutsideDiameter); - } - - public double getShoulderDiameter() { - return shoulderDiameter.getValue(); - } - - public void setShoulderDiameter(final AnnotatedLengthDTO theShoulderDiameter) { - shoulderDiameter = theShoulderDiameter; - } - - public void setShoulderDiameter(final double theShoulderDiameter) { - shoulderDiameter = new AnnotatedLengthDTO(theShoulderDiameter); - } - - public double getShoulderLength() { - return shoulderLength.getValue(); - } - - public void setShoulderLength(final AnnotatedLengthDTO theShoulderLength) { - shoulderLength = theShoulderLength; - } - - public void setShoulderLength(final double theShoulderLength) { - shoulderLength = new AnnotatedLengthDTO(theShoulderLength); - } - - public double getLength() { - return length.getValue(); - } - - public void setLength(final AnnotatedLengthDTO theLength) { - length = theLength; - } - - public void setLength(final double theLength) { - length = new AnnotatedLengthDTO(theLength); - } - - public double getThickness() { - return thickness.getValue(); - } - - public void setThickness(AnnotatedLengthDTO thickness) { - this.thickness = thickness; - } - - public void setThickness(double thickness) { - this.thickness = new AnnotatedLengthDTO(thickness); - } - - @Override - public ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - props.put(ComponentPreset.SHAPE, shape.getORShape()); - props.put(ComponentPreset.AFT_OUTER_DIAMETER, this.getOutsideDiameter()); - if ( shoulderLength != null ) { - props.put(ComponentPreset.AFT_SHOULDER_LENGTH, this.getShoulderLength()); - } - if ( shoulderDiameter != null ) { - props.put(ComponentPreset.AFT_SHOULDER_DIAMETER, this.getShoulderDiameter()); - } - props.put(ComponentPreset.LENGTH, this.getLength()); - props.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - if ( thickness != null ) { - props.put(ComponentPreset.THICKNESS, this.getThickness()); - } - - return ComponentPresetFactory.create(props); - } - -} diff --git a/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentDTO.java b/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentDTO.java deleted file mode 100644 index 69da4e85..00000000 --- a/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentDTO.java +++ /dev/null @@ -1,93 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; - -/** - * The real 'root' element in an XML document. - */ -@XmlRootElement(name = "OpenRocketComponent") -@XmlAccessorType(XmlAccessType.FIELD) -public class OpenRocketComponentDTO { - - @XmlElement(name = "Version") - private final String version = "0.1"; - - @XmlElementWrapper(name = "Materials") - @XmlElement(name = "Material") - List materials = new ArrayList(); - - @XmlElementWrapper(name = "Components") - @XmlElementRefs({ - @XmlElementRef(name = "BodyTubes", type = BodyTubeDTO.class), - @XmlElementRef(name = "TubeCouplers", type = TubeCouplerDTO.class), - @XmlElementRef(name = "NoseCones", type = NoseConeDTO.class), - @XmlElementRef(name = "Transitions", type = TransitionDTO.class), - @XmlElementRef(name = "BulkHeads", type = BulkHeadDTO.class), - @XmlElementRef(name = "CenteringRings", type = CenteringRingDTO.class), - @XmlElementRef(name = "EngineBlocks", type = EngineBlockDTO.class), - @XmlElementRef(name = "LaunchLugs", type = LaunchLugDTO.class), - @XmlElementRef(name = "Streamers", type = StreamerDTO.class), - @XmlElementRef(name = "Parachutes", type = ParachuteDTO.class)}) - private List components = new ArrayList(); - - public OpenRocketComponentDTO() { - } - - public OpenRocketComponentDTO(final List theMaterials, final List theComponents) { - materials = theMaterials; - components = theComponents; - } - - public List getMaterials() { - return materials; - } - - public void addMaterial(final MaterialDTO theMaterial) { - materials.add(theMaterial); - } - - public void setMaterials(final List theMaterials) { - materials = theMaterials; - } - - public List getComponents() { - return components; - } - - public void addComponent(final BaseComponentDTO theComponent) { - components.add(theComponent); - } - - public void setComponents(final List theComponents) { - components = theComponents; - } - - public List asComponentPresets() throws InvalidComponentPresetException { - List result = new ArrayList(components.size()); - for (int i = 0; i < components.size(); i++) { - result.add(components.get(i).asComponentPreset(materials)); - } - return result; - } - - public List asMaterialList() { - List result = new ArrayList( materials.size() ); - for( MaterialDTO material : materials ) { - result.add( material.asMaterial() ); - } - return result; - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentLoader.java b/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentLoader.java deleted file mode 100644 index a27712c7..00000000 --- a/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentLoader.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import java.io.BufferedInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Collection; -import java.util.List; - -import javax.xml.bind.JAXBException; - -import net.sf.openrocket.file.Loader; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; - -public class OpenRocketComponentLoader implements Loader { - - private static final LogHelper log = Application.getLogger(); - - @Override - public Collection load(InputStream stream, String filename) { - - log.debug("Loading presets from file " + filename); - - if ( ! (stream instanceof BufferedInputStream) ) { - stream = new BufferedInputStream(stream); - } - - try { - List presets; - presets = (new OpenRocketComponentSaver().unmarshalFromOpenRocketComponent( new InputStreamReader (stream))).asComponentPresets(); - log.debug("ComponentPreset file " + filename + " contained " + presets.size() + " presets"); - return presets; - } catch (JAXBException e) { - throw new BugException("Unable to parse file: "+ filename, e); - } catch (InvalidComponentPresetException e) { - throw new BugException("Unable to parse file: "+ filename, e); - } - - } - -} diff --git a/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentSaver.java b/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentSaver.java deleted file mode 100644 index 934d4be5..00000000 --- a/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentSaver.java +++ /dev/null @@ -1,206 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.startup.Application; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** - * The active manager class that is the entry point for reading and writing *.orc files. - */ -public class OpenRocketComponentSaver { - - /** - * The JAXBContext. JAXBContext is thread-safe. - */ - private static JAXBContext context = null; - - static { - try { - context = JAXBContext.newInstance(OpenRocketComponentDTO.class); - } - catch (JAXBException jaxb) { - Application.getLogger().error("Unable to create JAXBContext for loading of *.orc files.", jaxb); - } - } - - public boolean save(File file, List theMaterialList, List thePresetList) throws - JAXBException, - IOException { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); - writer.write(marshalToOpenRocketComponent(theMaterialList, thePresetList)); - writer.flush(); - writer.close(); - return true; - } - - /** - * This method marshals a list of materials and ComponentPresets into an .orc formatted XML string. - * - * @param theMaterialList the list of materials to be included - * @param thePresetList the list of presets to be included - * - * @return ORC-compliant XML - * - * @throws JAXBException - */ - public String marshalToOpenRocketComponent(List theMaterialList, List thePresetList) throws - JAXBException { - /** The context is thread-safe, but marshallers are not. Create a local one. */ - Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - StringWriter sw = new StringWriter(); - - // We're going to sort the initial data since that makes the output much easier on the eyes. - - Collections.sort(theMaterialList, new Comparator() { - - @Override - public int compare(Material o1, Material o2) { - return o1.getName().compareTo( o2.getName() ); - } - - }); - - Collections.sort(thePresetList, new Comparator() { - - @Override - public int compare(ComponentPreset o1, ComponentPreset o2) { - int manucmp = o1.getManufacturer().getSimpleName().compareTo( o2.getManufacturer().getSimpleName() ); - - if ( manucmp != 0 ) { - return manucmp; - } - - return o1.getPartNo().compareTo( o2.getPartNo()); - } - - }); - - marshaller.marshal(toOpenRocketComponentDTO(theMaterialList, thePresetList), sw); - return sw.toString(); - - } - - /** - * This method unmarshals from a Reader that is presumed to be open on an XML file in .orc format. - * - * @param is an open reader; StringBufferInputStream could not be used because it's deprecated and does not handle - * UTF characters correctly - * - * @return a list of ComponentPresets - * - * @throws InvalidComponentPresetException - * - */ - public OpenRocketComponentDTO unmarshalFromOpenRocketComponent(Reader is) throws JAXBException, - InvalidComponentPresetException { - return fromOpenRocketComponent(is); - } - - /** - * Write an XML representation of a list of presets. - * - * @param dest the stream to write the data to - * @param theMaterialList the list of materials to be included - * @param thePresetList the list of presets to be included - * - * @throws JAXBException - * @throws IOException thrown if the stream could not be written - */ - public void save(OutputStream dest, List theMaterialList, List thePresetList) throws - IOException, - JAXBException { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(dest, "UTF-8")); - writer.write(marshalToOpenRocketComponent(theMaterialList, thePresetList)); - writer.flush(); - writer.close(); - } - - /** - * Read from an open Reader instance XML in .orc format and reconstruct an OpenRocketComponentDTO instance. - * - * @param is an open Reader; assumed to be opened on a file of XML in .orc format - * - * @return the OpenRocketComponentDTO that is a POJO representation of the XML; null if the data could not be read - * or was in an invalid format - */ - private OpenRocketComponentDTO fromOpenRocketComponent(Reader is) throws JAXBException { - /** The context is thread-safe, but unmarshallers are not. Create a local one. */ - Unmarshaller unmarshaller = context.createUnmarshaller(); - return (OpenRocketComponentDTO) unmarshaller.unmarshal(is); //new StreamSource(is)); - } - - /** - * Root conversion method. It iterates over all subcomponents. - * - * @return a corresponding ORC representation - */ - private OpenRocketComponentDTO toOpenRocketComponentDTO(List theMaterialList, List thePresetList) { - OpenRocketComponentDTO rsd = new OpenRocketComponentDTO(); - - if (theMaterialList != null) { - for (Material material : theMaterialList) { - rsd.addMaterial(new MaterialDTO(material)); - } - } - - if (thePresetList != null) { - for (ComponentPreset componentPreset : thePresetList) { - rsd.addComponent(toComponentDTO(componentPreset)); - } - } - return rsd; - } - - /** - * Factory method that maps a preset to the corresponding DTO handler. - * - * @param thePreset the preset for which a handler will be found - * - * @return a subclass of BaseComponentDTO that can be used for marshalling/unmarshalling a preset; null if not found - * for the preset type - */ - private static BaseComponentDTO toComponentDTO(ComponentPreset thePreset) { - switch (thePreset.getType()) { - case BODY_TUBE: - return new BodyTubeDTO(thePreset); - case TUBE_COUPLER: - return new TubeCouplerDTO(thePreset); - case NOSE_CONE: - return new NoseConeDTO(thePreset); - case TRANSITION: - return new TransitionDTO(thePreset); - case BULK_HEAD: - return new BulkHeadDTO(thePreset); - case CENTERING_RING: - return new CenteringRingDTO(thePreset); - case ENGINE_BLOCK: - return new EngineBlockDTO(thePreset); - case LAUNCH_LUG: - return new LaunchLugDTO(thePreset); - case STREAMER: - return new StreamerDTO(thePreset); - case PARACHUTE: - return new ParachuteDTO(thePreset); - } - - return null; - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/ParachuteDTO.java b/core/src/net/sf/openrocket/preset/xml/ParachuteDTO.java deleted file mode 100644 index f7056c05..00000000 --- a/core/src/net/sf/openrocket/preset/xml/ParachuteDTO.java +++ /dev/null @@ -1,140 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; -import net.sf.openrocket.preset.xml.BaseComponentDTO.AnnotatedMaterialDTO; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Streamer preset XML handler. - */ -@XmlRootElement(name = "Parachute") -@XmlAccessorType(XmlAccessType.FIELD) -public class ParachuteDTO extends BaseComponentDTO { - - @XmlElement(name = "Diameter") - private AnnotatedLengthDTO diameter; - @XmlElement(name = "Sides") - private Integer sides; - @XmlElement(name = "LineCount") - private Integer lineCount; - @XmlElement(name = "LineLength") - private AnnotatedLengthDTO lineLength; - - @XmlElement(name = "LineMaterial") - private AnnotatedMaterialDTO lineMaterial; - - - /** - * Default constructor. - */ - public ParachuteDTO() { - } - - public double getDiameter() { - return diameter.getValue(); - } - - public void setDiameter(AnnotatedLengthDTO diameter) { - this.diameter = diameter; - } - public void setDiameter(double diameter) { - this.diameter = new AnnotatedLengthDTO(diameter); - } - - public Integer getSides() { - return sides; - } - - public void setSides(Integer sides) { - this.sides = sides; - } - - public Integer getLineCount() { - return lineCount; - } - - public void setLineCount(Integer lineCount) { - this.lineCount = lineCount; - } - - public double getLineLength() { - return lineLength.getValue(); - } - - public void setLineLength(AnnotatedLengthDTO lineLength) { - this.lineLength = lineLength; - } - - public void setLineLength(double lineLength) { - this.lineLength = new AnnotatedLengthDTO(lineLength); - } - - public AnnotatedMaterialDTO getLineMaterial() { - return lineMaterial; - } - - public void setLineMaterial(AnnotatedMaterialDTO lineMaterial) { - this.lineMaterial = lineMaterial; - } - - /** - * Most-useful constructor that maps a BodyTube preset to a BodyTubeDTO. - * - * @param preset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected body tube keys are not in the preset - */ - public ParachuteDTO(final ComponentPreset preset) { - super(preset); - setDiameter(preset.get(ComponentPreset.DIAMETER)); - setLineCount(preset.get(ComponentPreset.LINE_COUNT)); - if ( preset.has(ComponentPreset.LINE_LENGTH)) { - setLineLength(preset.get(ComponentPreset.LINE_LENGTH)); - } - if ( preset.has(ComponentPreset.SIDES)) { - setSides(preset.get(ComponentPreset.SIDES)); - } - if ( preset.has(ComponentPreset.LINE_MATERIAL)) { - setLineMaterial(new AnnotatedMaterialDTO(preset.get(ComponentPreset.LINE_MATERIAL))); - } - } - - @Override - public ComponentPreset asComponentPreset(java.util.List materials) throws InvalidComponentPresetException { - return asComponentPreset(ComponentPreset.Type.PARACHUTE, materials); - } - - public ComponentPreset asComponentPreset(ComponentPreset.Type type, List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - // TODO - seems some vendors use a bulk material for the sheet along with a Thickness. - // need to fix the MATERIAL packed into the componentpreset. - props.put(ComponentPreset.TYPE, type); - props.put(ComponentPreset.DIAMETER, this.getDiameter()); - props.put(ComponentPreset.LINE_COUNT, this.getLineCount()); - if ( this.lineLength != null ) { - props.put(ComponentPreset.LINE_LENGTH, this.getLineLength()); - } - if ( this.sides != null ) { - props.put(ComponentPreset.SIDES, this.getSides()); - } - if ( this.lineMaterial != null ) { - Material m = find(materials, this.lineMaterial); - if ( m != null ) { - props.put(ComponentPreset.LINE_MATERIAL, m); - } - } - - return ComponentPresetFactory.create(props); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/ShapeDTO.java b/core/src/net/sf/openrocket/preset/xml/ShapeDTO.java deleted file mode 100644 index d85fbcb0..00000000 --- a/core/src/net/sf/openrocket/preset/xml/ShapeDTO.java +++ /dev/null @@ -1,41 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.rocketcomponent.Transition; - -import javax.xml.bind.annotation.XmlEnum; - -/** - * A mirror class to Transition.Shape to adapt that class to/from XML. - */ -@XmlEnum(String.class) -public enum ShapeDTO { - - CONICAL (Transition.Shape.CONICAL), - OGIVE (Transition.Shape.OGIVE), - ELLIPSOID (Transition.Shape.ELLIPSOID), - POWER (Transition.Shape.POWER), - PARABOLIC (Transition.Shape.PARABOLIC), - HAACK (Transition.Shape.HAACK); - - private Transition.Shape corollary; - - private ShapeDTO(Transition.Shape theShape) { - corollary = theShape; - } - - public static ShapeDTO asDTO(Transition.Shape targetShape) { - ShapeDTO[] values = values(); - for (int i = 0; i < values.length; i++) { - ShapeDTO value = values[i]; - if (value.corollary.equals(targetShape)) { - return value; - } - } - return ELLIPSOID; //default - } - - public Transition.Shape getORShape() { - return corollary; - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/StreamerDTO.java b/core/src/net/sf/openrocket/preset/xml/StreamerDTO.java deleted file mode 100644 index 7ed0dd84..00000000 --- a/core/src/net/sf/openrocket/preset/xml/StreamerDTO.java +++ /dev/null @@ -1,102 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Streamer preset XML handler. - */ -@XmlRootElement(name = "Streamer") -@XmlAccessorType(XmlAccessType.FIELD) -public class StreamerDTO extends BaseComponentDTO { - - @XmlElement(name = "Length") - private AnnotatedLengthDTO length; - @XmlElement(name = "Width") - private AnnotatedLengthDTO width; - @XmlElement(name = "Thickness") - private AnnotatedLengthDTO thickness; - - /** - * Default constructor. - */ - public StreamerDTO() { - } - - /** - * Most-useful constructor that maps a BodyTube preset to a BodyTubeDTO. - * - * @param preset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected body tube keys are not in the preset - */ - public StreamerDTO(final ComponentPreset preset) { - super(preset); - setWidth(preset.get(ComponentPreset.WIDTH)); - setThickness(preset.get(ComponentPreset.THICKNESS)); - setLength(preset.get(ComponentPreset.LENGTH)); - } - - public double getWidth() { - return width.getValue(); - } - - public void setWidth( final AnnotatedLengthDTO theWidth ) { - width = theWidth; - } - - public void setWidth(final double theId) { - width = new AnnotatedLengthDTO(theId); - } - - public double getThickness() { - return thickness.getValue(); - } - - public void setThickness(final AnnotatedLengthDTO theThickness) { - thickness = theThickness; - } - - public void setThickness(final double theThickness) { - thickness = new AnnotatedLengthDTO(theThickness); - } - - public double getLength() { - return length.getValue(); - } - - public void setLength(final AnnotatedLengthDTO theLength) { - length = theLength; - } - - public void setLength(final double theLength) { - length = new AnnotatedLengthDTO(theLength); - } - - @Override - public ComponentPreset asComponentPreset(java.util.List materials) throws InvalidComponentPresetException { - return asComponentPreset(ComponentPreset.Type.STREAMER, materials); - } - - public ComponentPreset asComponentPreset(ComponentPreset.Type type, List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - // TODO - seems some vendors use a bulk material for the sheet along with a Thickness. - // need to fix the MATERIAL packed into the componentpreset. - props.put(ComponentPreset.WIDTH, this.getWidth()); - props.put(ComponentPreset.THICKNESS, this.getThickness()); - props.put(ComponentPreset.LENGTH, this.getLength()); - props.put(ComponentPreset.TYPE, type); - - return ComponentPresetFactory.create(props); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/TransitionDTO.java b/core/src/net/sf/openrocket/preset/xml/TransitionDTO.java deleted file mode 100644 index 1aaaac65..00000000 --- a/core/src/net/sf/openrocket/preset/xml/TransitionDTO.java +++ /dev/null @@ -1,197 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.InvalidComponentPresetException; -import net.sf.openrocket.preset.TypedPropertyMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Transition preset XML handler. - */ -@XmlRootElement(name = "Transition") -@XmlAccessorType(XmlAccessType.FIELD) -public class TransitionDTO extends BaseComponentDTO { - - @XmlElement(name = "Shape") - private ShapeDTO shape; - - @XmlElement(name = "ForeOutsideDiameter") - private AnnotatedLengthDTO foreOutsideDiameter; - @XmlElement(name = "ForeShoulderDiameter") - private AnnotatedLengthDTO foreShoulderDiameter; - @XmlElement(name = "ForeShoulderLength") - private AnnotatedLengthDTO foreShoulderLength; - - @XmlElement(name = "AftOutsideDiameter") - private AnnotatedLengthDTO aftOutsideDiameter; - @XmlElement(name = "AftShoulderDiameter") - private AnnotatedLengthDTO aftShoulderDiameter; - @XmlElement(name = "AftShoulderLength") - private AnnotatedLengthDTO aftShoulderLength; - - @XmlElement(name = "Length") - private AnnotatedLengthDTO length; - - @XmlElement(name = "Thickness") - private AnnotatedLengthDTO thickness; - - - /** - * Default constructor. - */ - public TransitionDTO() { - } - - /** - * Most-useful constructor that maps a Transition preset to a TransitionDTO. - * - * @param thePreset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected transition keys are not in the preset - */ - public TransitionDTO(final ComponentPreset thePreset) { - super(thePreset); - setShape(ShapeDTO.asDTO(thePreset.get(ComponentPreset.SHAPE))); - setForeOutsideDiameter(thePreset.get(ComponentPreset.FORE_OUTER_DIAMETER)); - setForeShoulderDiameter(thePreset.get(ComponentPreset.FORE_SHOULDER_DIAMETER)); - setForeShoulderLength(thePreset.get(ComponentPreset.FORE_SHOULDER_LENGTH)); - setAftOutsideDiameter(thePreset.get(ComponentPreset.AFT_OUTER_DIAMETER)); - setAftShoulderDiameter(thePreset.get(ComponentPreset.AFT_SHOULDER_DIAMETER)); - setAftShoulderLength(thePreset.get(ComponentPreset.AFT_SHOULDER_LENGTH)); - setLength(thePreset.get(ComponentPreset.LENGTH)); - if ( thePreset.has(ComponentPreset.THICKNESS)) { - setThickness(thePreset.get(ComponentPreset.THICKNESS)); - } - } - - public ShapeDTO getShape() { - return shape; - } - - public void setShape(final ShapeDTO theShape) { - shape = theShape; - } - - public double getForeOutsideDiameter() { - return foreOutsideDiameter.getValue(); - } - - public void setForeOutsideDiameter(final AnnotatedLengthDTO theForeOutsideDiameter) { - foreOutsideDiameter = theForeOutsideDiameter; - } - - public void setForeOutsideDiameter(final double theForeOutsideDiameter) { - foreOutsideDiameter = new AnnotatedLengthDTO(theForeOutsideDiameter); - } - - public double getForeShoulderDiameter() { - return foreShoulderDiameter.getValue(); - } - - public void setForeShoulderDiameter(final AnnotatedLengthDTO theForeShoulderDiameter) { - foreShoulderDiameter = theForeShoulderDiameter; - } - - public void setForeShoulderDiameter(final double theForeShoulderDiameter) { - foreShoulderDiameter = new AnnotatedLengthDTO(theForeShoulderDiameter); - } - - public double getForeShoulderLength() { - return foreShoulderLength.getValue(); - } - - public void setForeShoulderLength(final AnnotatedLengthDTO theForeShoulderLength) { - foreShoulderLength = theForeShoulderLength; - } - - public void setForeShoulderLength(final double theForeShoulderLength) { - foreShoulderLength = new AnnotatedLengthDTO(theForeShoulderLength); - } - - public double getAftOutsideDiameter() { - return aftOutsideDiameter.getValue(); - } - - public void setAftOutsideDiameter(final AnnotatedLengthDTO theAftOutsideDiameter) { - aftOutsideDiameter = theAftOutsideDiameter; - } - - public void setAftOutsideDiameter(final double theAftOutsideDiameter) { - aftOutsideDiameter = new AnnotatedLengthDTO(theAftOutsideDiameter); - } - - public double getAftShoulderDiameter() { - return aftShoulderDiameter.getValue(); - } - - public void setAftShoulderDiameter(final AnnotatedLengthDTO theAftShoulderDiameter) { - aftShoulderDiameter = theAftShoulderDiameter; - } - - public void setAftShoulderDiameter(final double theAftShoulderDiameter) { - aftShoulderDiameter = new AnnotatedLengthDTO(theAftShoulderDiameter); - } - - public double getAftShoulderLength() { - return aftShoulderLength.getValue(); - } - - public void setAftShoulderLength(final AnnotatedLengthDTO theAftShoulderLength) { - aftShoulderLength = theAftShoulderLength; - } - - public void setAftShoulderLength(final double theAftShoulderLength) { - aftShoulderLength = new AnnotatedLengthDTO(theAftShoulderLength); - } - - public double getLength() { - return length.getValue(); - } - - public void setLength(final AnnotatedLengthDTO theLength) { - length = theLength; - } - - public void setLength(final double theLength) { - length = new AnnotatedLengthDTO(theLength); - } - - public double getThickness() { - return thickness.getValue(); - } - - public void setThickness(AnnotatedLengthDTO thickness) { - this.thickness = thickness; - } - - public void setThickness(double thickness) { - this.thickness = new AnnotatedLengthDTO(thickness); - } - - @Override - public ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException { - TypedPropertyMap props = new TypedPropertyMap(); - addProps(props, materials); - props.put(ComponentPreset.SHAPE, shape.getORShape()); - props.put(ComponentPreset.FORE_OUTER_DIAMETER, this.getForeOutsideDiameter()); - props.put(ComponentPreset.FORE_SHOULDER_DIAMETER, this.getForeShoulderDiameter()); - props.put(ComponentPreset.FORE_SHOULDER_LENGTH, this.getForeShoulderLength()); - props.put(ComponentPreset.AFT_OUTER_DIAMETER, this.getAftOutsideDiameter()); - props.put(ComponentPreset.AFT_SHOULDER_DIAMETER, this.getAftShoulderDiameter()); - props.put(ComponentPreset.AFT_SHOULDER_LENGTH, this.getAftShoulderLength()); - props.put(ComponentPreset.LENGTH, this.getLength()); - props.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - if ( thickness != null ) { - props.put(ComponentPreset.THICKNESS, this.getThickness()); - } - - return ComponentPresetFactory.create(props); - } -} diff --git a/core/src/net/sf/openrocket/preset/xml/TubeCouplerDTO.java b/core/src/net/sf/openrocket/preset/xml/TubeCouplerDTO.java deleted file mode 100644 index 3cc09658..00000000 --- a/core/src/net/sf/openrocket/preset/xml/TubeCouplerDTO.java +++ /dev/null @@ -1,40 +0,0 @@ - -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.InvalidComponentPresetException; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * Tube coupler preset XML handler. - */ -@XmlRootElement(name = "TubeCoupler") -@XmlAccessorType(XmlAccessType.FIELD) -public class TubeCouplerDTO extends BodyTubeDTO { - - /** - * Default constructor. - */ - public TubeCouplerDTO() { - } - - /** - * Most-useful constructor that maps a TubeCoupler preset to a TubeCouplerDTO. - * - * @param thePreset the preset - * - * @throws net.sf.openrocket.util.BugException thrown if the expected tube coupler keys are not in the preset - */ - public TubeCouplerDTO(ComponentPreset thePreset) { - super(thePreset); - } - - @Override - public ComponentPreset asComponentPreset(List materials) throws InvalidComponentPresetException { - return super.asComponentPreset(ComponentPreset.Type.TUBE_COUPLER, materials); - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/BodyComponent.java b/core/src/net/sf/openrocket/rocketcomponent/BodyComponent.java deleted file mode 100644 index 6f4d7dbe..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/BodyComponent.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.preset.ComponentPreset; - - - -/** - * Class to represent a body object. The object can be described as a function of - * the cylindrical coordinates x and angle theta as r = f(x,theta). The component - * need not be symmetrical in any way (e.g. square tube, slanted cone etc). - * - * It defines the methods getRadius(x,theta) and getInnerRadius(x,theta), as well - * as get/setLength(). - * - * @author Sampo Niskanen - */ - -public abstract class BodyComponent extends ExternalComponent { - - /** - * Default constructor. Sets the relative position to POSITION_RELATIVE_AFTER, - * i.e. body components come after one another. - */ - public BodyComponent() { - super(RocketComponent.Position.AFTER); - } - - - /** - * Get the outer radius of the component at cylindrical coordinate (x,theta). - * - * Note that the return value may be negative for a slanted object. - * - * @param x Distance in x direction - * @param theta Angle about the x-axis - * @return Distance to the outer edge of the object - */ - public abstract double getRadius(double x, double theta); - - - /** - * Get the inner radius of the component at cylindrical coordinate (x,theta). - * - * Note that the return value may be negative for a slanted object. - * - * @param x Distance in x direction - * @param theta Angle about the x-axis - * @return Distance to the inner edge of the object - */ - public abstract double getInnerRadius(double x, double theta); - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - super.loadFromPreset(preset); - } - - - - /** - * Sets the length of the body component. - *

- * Note: This should be overridden by the subcomponents which need to call - * clearPreset(). (BodyTube allows changing length without resetting the preset.) - */ - public void setLength(double length) { - if (this.length == length) - return; - this.length = Math.max(length, 0); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public boolean allowsChildren() { - return true; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java b/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java deleted file mode 100644 index 65317a3c..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java +++ /dev/null @@ -1,477 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -/** - * Rocket body tube component. Has only two parameters, a radius and length. - * - * @author Sampo Niskanen - */ - -public class BodyTube extends SymmetricComponent implements MotorMount, Coaxial { - private static final Translator trans = Application.getTranslator(); - - private double outerRadius = 0; - private boolean autoRadius = false; // Radius chosen automatically based on parent component - - // When changing the inner radius, thickness is modified - - private boolean motorMount = false; - private HashMap ejectionDelays = new HashMap(); - private HashMap motors = new HashMap(); - private IgnitionEvent ignitionEvent = IgnitionEvent.AUTOMATIC; - private double ignitionDelay = 0; - private double overhang = 0; - - - - public BodyTube() { - super(); - this.length = 8 * DEFAULT_RADIUS; - this.outerRadius = DEFAULT_RADIUS; - this.autoRadius = true; - } - - public BodyTube(double length, double radius) { - super(); - this.outerRadius = Math.max(radius, 0); - this.length = Math.max(length, 0); - } - - - public BodyTube(double length, double radius, boolean filled) { - this(length, radius); - this.filled = filled; - } - - public BodyTube(double length, double radius, double thickness) { - this(length, radius); - this.filled = false; - this.thickness = thickness; - } - - - /************ Get/set component parameter methods ************/ - - @Override - public ComponentPreset.Type getPresetType() { - return ComponentPreset.Type.BODY_TUBE; - } - - /** - * Return the outer radius of the body tube. - * - * @return the outside radius of the tube - */ - @Override - public double getOuterRadius() { - if (autoRadius) { - // Return auto radius from front or rear - double r = -1; - SymmetricComponent c = this.getPreviousSymmetricComponent(); - if (c != null) { - r = c.getFrontAutoRadius(); - } - if (r < 0) { - c = this.getNextSymmetricComponent(); - if (c != null) { - r = c.getRearAutoRadius(); - } - } - if (r < 0) - r = DEFAULT_RADIUS; - return r; - } - return outerRadius; - } - - - /** - * Set the outer radius of the body tube. If the radius is less than the wall thickness, - * the wall thickness is decreased accordingly of the value of the radius. - * This method sets the automatic radius off. - * - * @param radius the outside radius in standard units - */ - @Override - public void setOuterRadius(double radius) { - if ((this.outerRadius == radius) && (autoRadius == false)) - return; - - this.autoRadius = false; - this.outerRadius = Math.max(radius, 0); - - if (this.thickness > this.outerRadius) - this.thickness = this.outerRadius; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - clearPreset(); - } - - - /** - * Returns whether the radius is selected automatically or not. - * Returns false also in case automatic radius selection is not possible. - */ - public boolean isOuterRadiusAutomatic() { - return autoRadius; - } - - /** - * Sets whether the radius is selected automatically or not. - */ - public void setOuterRadiusAutomatic(boolean auto) { - if (autoRadius == auto) - return; - - autoRadius = auto; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - clearPreset(); - } - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - this.autoRadius = false; - if ( preset.has(ComponentPreset.OUTER_DIAMETER) ) { - double outerDiameter = preset.get(ComponentPreset.OUTER_DIAMETER); - this.outerRadius = outerDiameter/2.0; - if ( preset.has(ComponentPreset.INNER_DIAMETER) ) { - double innerDiameter = preset.get(ComponentPreset.INNER_DIAMETER); - this.thickness = (outerDiameter-innerDiameter) / 2.0; - } - } - - super.loadFromPreset(preset); - - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public double getAftRadius() { - return getOuterRadius(); - } - - @Override - public double getForeRadius() { - return getOuterRadius(); - } - - @Override - public boolean isAftRadiusAutomatic() { - return isOuterRadiusAutomatic(); - } - - @Override - public boolean isForeRadiusAutomatic() { - return isOuterRadiusAutomatic(); - } - - - - @Override - protected double getFrontAutoRadius() { - if (isOuterRadiusAutomatic()) { - // Search for previous SymmetricComponent - SymmetricComponent c = this.getPreviousSymmetricComponent(); - if (c != null) { - return c.getFrontAutoRadius(); - } else { - return -1; - } - } - return getOuterRadius(); - } - - @Override - protected double getRearAutoRadius() { - if (isOuterRadiusAutomatic()) { - // Search for next SymmetricComponent - SymmetricComponent c = this.getNextSymmetricComponent(); - if (c != null) { - return c.getRearAutoRadius(); - } else { - return -1; - } - } - return getOuterRadius(); - } - - - - - - @Override - public double getInnerRadius() { - if (filled) - return 0; - return Math.max(getOuterRadius() - thickness, 0); - } - - @Override - public void setInnerRadius(double r) { - setThickness(getOuterRadius() - r); - } - - - - - /** - * Return the component name. - */ - @Override - public String getComponentName() { - //// Body tube - return trans.get("BodyTube.BodyTube"); - } - - - /************ Component calculations ***********/ - - // From SymmetricComponent - /** - * Returns the outer radius at the position x. This returns the same value as getOuterRadius(). - */ - @Override - public double getRadius(double x) { - return getOuterRadius(); - } - - /** - * Returns the inner radius at the position x. If the tube is filled, returns always zero. - */ - @Override - public double getInnerRadius(double x) { - if (filled) - return 0.0; - else - return Math.max(getOuterRadius() - thickness, 0); - } - - - /** - * Returns the body tube's center of gravity. - */ - @Override - public Coordinate getComponentCG() { - return new Coordinate(length / 2, 0, 0, getComponentMass()); - } - - /** - * Returns the body tube's volume. - */ - @Override - public double getComponentVolume() { - double r = getOuterRadius(); - if (filled) - return getFilledVolume(r, length); - else - return getFilledVolume(r, length) - getFilledVolume(getInnerRadius(0), length); - } - - - @Override - public double getLongitudinalUnitInertia() { - // 1/12 * (3 * (r1^2 + r2^2) + h^2) - return (3 * (MathUtil.pow2(getInnerRadius())) + MathUtil.pow2(getOuterRadius()) + MathUtil.pow2(getLength())) / 12; - } - - @Override - public double getRotationalUnitInertia() { - // 1/2 * (r1^2 + r2^2) - return (MathUtil.pow2(getInnerRadius()) + MathUtil.pow2(getOuterRadius())) / 2; - } - - - - - /** - * Helper function for cylinder volume. - */ - private static double getFilledVolume(double r, double l) { - return Math.PI * r * r * l; - } - - - /** - * Adds bounding coordinates to the given set. The body tube will fit within the - * convex hull of the points. - * - * Currently the points are simply a rectangular box around the body tube. - */ - @Override - public Collection getComponentBounds() { - Collection bounds = new ArrayList(8); - double r = getOuterRadius(); - addBound(bounds, 0, r); - addBound(bounds, length, r); - return bounds; - } - - - - /** - * Check whether the given type can be added to this component. BodyTubes allow any - * InternalComponents or ExternalComponents, excluding BodyComponents, to be added. - * - * @param type The RocketComponent class type to add. - * @return Whether such a component can be added. - */ - @Override - public boolean isCompatible(Class type) { - if (InternalComponent.class.isAssignableFrom(type)) - return true; - if (ExternalComponent.class.isAssignableFrom(type) && - !BodyComponent.class.isAssignableFrom(type)) - return true; - return false; - } - - //////////////// Motor mount ///////////////// - - @Override - public boolean isMotorMount() { - return motorMount; - } - - @Override - public void setMotorMount(boolean mount) { - if (motorMount == mount) - return; - motorMount = mount; - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - @Override - public Motor getMotor(String id) { - if (id == null) - return null; - - // Check whether the id is valid for the current rocket - RocketComponent root = this.getRoot(); - if (!(root instanceof Rocket)) - return null; - if (!((Rocket) root).isMotorConfigurationID(id)) - return null; - - return motors.get(id); - } - - @Override - public void setMotor(String id, Motor motor) { - if (id == null) { - if (motor != null) { - throw new IllegalArgumentException("Cannot set non-null motor for id null"); - } - } - Motor current = motors.get(id); - if ((motor == null && current == null) || - (motor != null && motor.equals(current))) - return; - motors.put(id, motor); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - @Override - public double getMotorDelay(String id) { - Double delay = ejectionDelays.get(id); - if (delay == null) - return Motor.PLUGGED; - return delay; - } - - @Override - public void setMotorDelay(String id, double delay) { - ejectionDelays.put(id, delay); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - @Override - public int getMotorCount() { - return 1; - } - - @Override - public double getMotorMountDiameter() { - return getInnerRadius() * 2; - } - - @Override - public IgnitionEvent getIgnitionEvent() { - return ignitionEvent; - } - - @Override - public void setIgnitionEvent(IgnitionEvent event) { - if (ignitionEvent == event) - return; - ignitionEvent = event; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - @Override - public double getIgnitionDelay() { - return ignitionDelay; - } - - @Override - public void setIgnitionDelay(double delay) { - if (MathUtil.equals(delay, ignitionDelay)) - return; - ignitionDelay = delay; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - @Override - public double getMotorOverhang() { - return overhang; - } - - @Override - public void setMotorOverhang(double overhang) { - if (MathUtil.equals(this.overhang, overhang)) - return; - this.overhang = overhang; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public Coordinate getMotorPosition(String id) { - Motor motor = motors.get(id); - if (motor == null) { - throw new IllegalArgumentException("No motor with id " + id + " defined."); - } - - return new Coordinate(this.getLength() - motor.getLength() + this.getMotorOverhang()); - } - - - - - /* - * (non-Javadoc) - * Copy the motor and ejection delay HashMaps. - * - * @see rocketcomponent.RocketComponent#copy() - */ - @SuppressWarnings("unchecked") - @Override - protected RocketComponent copyWithOriginalID() { - RocketComponent c = super.copyWithOriginalID(); - ((BodyTube) c).motors = (HashMap) motors.clone(); - ((BodyTube) c).ejectionDelays = (HashMap) ejectionDelays.clone(); - return c; - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java b/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java deleted file mode 100644 index 36822c4d..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; - - -public class Bulkhead extends RadiusRingComponent { - private static final Translator trans = Application.getTranslator(); - - public Bulkhead() { - setOuterRadiusAutomatic(true); - setLength(0.002); - } - - @Override - public Type getPresetType() { - return ComponentPreset.Type.BULK_HEAD; - } - - @Override - public double getInnerRadius() { - return 0; - } - - @Override - public void setInnerRadius(double r) { - // No-op - } - - @Override - public void setOuterRadiusAutomatic(boolean auto) { - super.setOuterRadiusAutomatic(auto); - clearPreset(); - } - - @Override - public String getComponentName() { - //// Bulkhead - return trans.get("Bulkhead.Bulkhead"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class type) { - return false; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java b/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java deleted file mode 100644 index 0dc9e1ee..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; - - -public class CenteringRing extends RadiusRingComponent { - - public CenteringRing() { - setOuterRadiusAutomatic(true); - setInnerRadiusAutomatic(true); - setLength(0.002); - } - - private static final Translator trans = Application.getTranslator(); - - - @Override - public double getInnerRadius() { - // Implement sibling inner radius automation - if (isInnerRadiusAutomatic()) { - innerRadius = 0; - // Component can be parentless if disattached from rocket - if (this.getParent() != null) { - for (RocketComponent sibling : this.getParent().getChildren()) { - /* - * Only InnerTubes are considered when determining the automatic - * inner radius (for now). - */ - if (!(sibling instanceof InnerTube)) // Excludes itself - continue; - - double pos1 = this.toRelative(Coordinate.NUL, sibling)[0].x; - double pos2 = this.toRelative(new Coordinate(getLength()), sibling)[0].x; - if (pos2 < 0 || pos1 > sibling.getLength()) - continue; - - innerRadius = Math.max(innerRadius, ((InnerTube) sibling).getOuterRadius()); - } - innerRadius = Math.min(innerRadius, getOuterRadius()); - } - } - - return super.getInnerRadius(); - } - - - @Override - public void setOuterRadiusAutomatic(boolean auto) { - super.setOuterRadiusAutomatic(auto); - } - - @Override - public void setInnerRadiusAutomatic(boolean auto) { - super.setInnerRadiusAutomatic(auto); - } - - @Override - public String getComponentName() { - return trans.get ("CenteringRing.CenteringRing"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class type) { - return false; - } - - @Override - public Type getPresetType() { - return ComponentPreset.Type.CENTERING_RING; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ClusterConfiguration.java b/core/src/net/sf/openrocket/rocketcomponent/ClusterConfiguration.java deleted file mode 100644 index 73e8a6de..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ClusterConfiguration.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -/** - * Class that defines different cluster configurations available for the InnerTube. - * The class is immutable, and all the constructors are private. Therefore the only - * available cluster configurations are those available in the static fields. - * - * @author Sampo Niskanen - */ -public class ClusterConfiguration { - // Helper vars - private static final double R5 = 1.0/(2*Math.sin(2*Math.PI/10)); - private static final double SQRT2 = Math.sqrt(2); - private static final double SQRT3 = Math.sqrt(3); - - /** A single motor */ - public static final ClusterConfiguration SINGLE = new ClusterConfiguration("single", 0,0); - - /** Definitions of cluster configurations. Do not modify array. */ - public static final ClusterConfiguration[] CONFIGURATIONS = { - // Single row - SINGLE, - new ClusterConfiguration("double", -0.5,0, 0.5,0), - new ClusterConfiguration("3-row", -1.0,0, 0.0,0, 1.0,0), - new ClusterConfiguration("4-row", -1.5,0, -0.5,0, 0.5,0, 1.5,0), - - // Ring of tubes - new ClusterConfiguration("3-ring", -0.5,-1.0/(2*SQRT3), - 0.5,-1.0/(2*SQRT3), - 0, 1.0/SQRT3), - new ClusterConfiguration("4-ring", -0.5,0.5, 0.5,0.5, 0.5,-0.5, -0.5,-0.5), - new ClusterConfiguration("5-ring", 0,R5, - R5*Math.sin(2*Math.PI/5),R5*Math.cos(2*Math.PI/5), - R5*Math.sin(2*Math.PI*2/5),R5*Math.cos(2*Math.PI*2/5), - R5*Math.sin(2*Math.PI*3/5),R5*Math.cos(2*Math.PI*3/5), - R5*Math.sin(2*Math.PI*4/5),R5*Math.cos(2*Math.PI*4/5)), - new ClusterConfiguration("6-ring", 0,1, SQRT3/2,0.5, SQRT3/2,-0.5, - 0,-1, -SQRT3/2,-0.5, -SQRT3/2,0.5), - - // Centered with ring - new ClusterConfiguration("3-star", 0,0, 0,1, SQRT3/2,-0.5, -SQRT3/2,-0.5), - new ClusterConfiguration("4-star", 0,0, -1/SQRT2,1/SQRT2, 1/SQRT2,1/SQRT2, - 1/SQRT2,-1/SQRT2, -1/SQRT2,-1/SQRT2), - new ClusterConfiguration("5-star", 0,0, 0,1, - Math.sin(2*Math.PI/5),Math.cos(2*Math.PI/5), - Math.sin(2*Math.PI*2/5),Math.cos(2*Math.PI*2/5), - Math.sin(2*Math.PI*3/5),Math.cos(2*Math.PI*3/5), - Math.sin(2*Math.PI*4/5),Math.cos(2*Math.PI*4/5)), - new ClusterConfiguration("6-star", 0,0, 0,1, SQRT3/2,0.5, SQRT3/2,-0.5, - 0,-1, -SQRT3/2,-0.5, -SQRT3/2,0.5) - }; - - - - private final List points; - private final String xmlName; - - - private ClusterConfiguration(String xmlName, double... points) { - this.xmlName = xmlName; - if (points.length == 0 || points.length%2 == 1) { - throw new IllegalArgumentException("Illegal number of points specified: "+ - points.length); - } - List l = new ArrayList(points.length); - for (double d: points) - l.add(d); - - this.points = Collections.unmodifiableList(l); - } - - public String getXMLName() { - return xmlName; - } - - public int getClusterCount() { - return points.size()/2; - } - - /** - * Returns the relative positions of the cluster components. The list is of length - * 2*getClusterCount() with (x,y) value pairs. The origin is at (0,0) - * and the values are positioned so that the closest clusters have distance of 1. - * - * @return a list of (x,y) coordinate pairs. - */ - public List getPoints() { - return points; // Unmodifiable - } - - /** - * Return the points rotated by rotation radians. - * @param rotation Rotation amount. - */ - public List getPoints(double rotation) { - double cos = Math.cos(rotation); - double sin = Math.sin(rotation); - List ret = new ArrayList(points.size()); - for (int i=0; i - * Note that the mass and CG overrides of the ComponentAssembly class - * overrides all sibling mass/CG as well as its own. - * - * @author Sampo Niskanen - */ -public abstract class ComponentAssembly extends RocketComponent { - - /** - * Sets the position of the components to POSITION_RELATIVE_AFTER. - * (Should have no effect.) - */ - public ComponentAssembly() { - super(RocketComponent.Position.AFTER); - } - - /** - * Null method (ComponentAssembly has no bounds of itself). - */ - @Override - public Collection getComponentBounds() { - return Collections.emptyList(); - } - - /** - * Null method (ComponentAssembly has no mass of itself). - */ - @Override - public Coordinate getComponentCG() { - return Coordinate.NUL; - } - - /** - * Null method (ComponentAssembly has no mass of itself). - */ - @Override - public double getComponentMass() { - return 0; - } - - /** - * Null method (ComponentAssembly has no mass of itself). - */ - @Override - public double getLongitudinalUnitInertia() { - return 0; - } - - /** - * Null method (ComponentAssembly has no mass of itself). - */ - @Override - public double getRotationalUnitInertia() { - return 0; - } - - /** - * Components have no aerodynamic effect, so return false. - */ - @Override - public boolean isAerodynamic() { - return false; - } - - /** - * Component have no effect on mass, so return false (even though the override values - * may have an effect). - */ - @Override - public boolean isMassive() { - return false; - } - - @Override - public boolean getOverrideSubcomponents() { - return true; - } - - @Override - public void setOverrideSubcomponents(boolean override) { - // No-op - } - - @Override - public boolean isOverrideSubcomponentsEnabled() { - return false; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ComponentChangeEvent.java b/core/src/net/sf/openrocket/rocketcomponent/ComponentChangeEvent.java deleted file mode 100644 index 5a2a2e24..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ComponentChangeEvent.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.EventObject; - -public class ComponentChangeEvent extends EventObject { - private static final long serialVersionUID = 1L; - - - /** A change that does not affect simulation results in any way (name, color, etc.) */ - public static final int NONFUNCTIONAL_CHANGE = 1; - /** A change that affects the mass properties of the rocket */ - public static final int MASS_CHANGE = 2; - /** A change that affects the aerodynamic properties of the rocket */ - public static final int AERODYNAMIC_CHANGE = 4; - /** A change that affects the mass and aerodynamic properties of the rocket */ - public static final int BOTH_CHANGE = MASS_CHANGE | AERODYNAMIC_CHANGE; // Mass & Aerodynamic - - /** A change that affects the rocket tree structure */ - public static final int TREE_CHANGE = 8; - /** A change caused by undo/redo. */ - public static final int UNDO_CHANGE = 16; - /** A change in the motor configurations or names */ - public static final int MOTOR_CHANGE = 32; - /** A change that affects the events occurring during flight. */ - public static final int EVENT_CHANGE = 64; - - /** A bit-field that contains all possible change types. */ - public static final int ALL_CHANGE = 0xFFFFFFFF; - - private final int type; - - - public ComponentChangeEvent(RocketComponent component, int type) { - super(component); - if (type == 0) { - throw new IllegalArgumentException("no event type provided"); - } - this.type = type; - } - - - /** - * Return the source component of this event as specified in the constructor. - */ - @Override - public RocketComponent getSource() { - return (RocketComponent) super.getSource(); - } - - - public boolean isAerodynamicChange() { - return (type & AERODYNAMIC_CHANGE) != 0; - } - - public boolean isMassChange() { - return (type & MASS_CHANGE) != 0; - } - - public boolean isOtherChange() { - return (type & BOTH_CHANGE) == 0; - } - - public boolean isTreeChange() { - return (type & TREE_CHANGE) != 0; - } - - public boolean isUndoChange() { - return (type & UNDO_CHANGE) != 0; - } - - public boolean isMotorChange() { - return (type & MOTOR_CHANGE) != 0; - } - - public int getType() { - return type; - } - - @Override - public String toString() { - String s = ""; - - if ((type & NONFUNCTIONAL_CHANGE) != 0) - s += ",nonfunc"; - if (isMassChange()) - s += ",mass"; - if (isAerodynamicChange()) - s += ",aero"; - if (isTreeChange()) - s += ",tree"; - if (isUndoChange()) - s += ",undo"; - if (isMotorChange()) - s += ",motor"; - if ((type & EVENT_CHANGE) != 0) - s += ",event"; - - if (s.length() > 0) - s = s.substring(1); - - return "ComponentChangeEvent[" + s + "]"; - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ComponentChangeListener.java b/core/src/net/sf/openrocket/rocketcomponent/ComponentChangeListener.java deleted file mode 100644 index dba150ae..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ComponentChangeListener.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.EventListener; - -public interface ComponentChangeListener extends EventListener { - - public void componentChanged(ComponentChangeEvent e); - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Configuration.java b/core/src/net/sf/openrocket/rocketcomponent/Configuration.java deleted file mode 100644 index 4a76df71..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Configuration.java +++ /dev/null @@ -1,470 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.BitSet; -import java.util.Collection; -import java.util.Collections; -import java.util.EventListener; -import java.util.EventObject; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.StateChangeListener; - - -/** - * A class defining a rocket configuration, including motors and which stages are active. - * - * TODO: HIGH: Remove motor ignition times from this class. - * - * @author Sampo Niskanen - */ -public class Configuration implements Cloneable, ChangeSource, ComponentChangeListener, - Iterable, Monitorable { - - private Rocket rocket; - private BitSet stages = new BitSet(); - - private String motorConfiguration = null; - - private List listenerList = new ArrayList(); - - - /* Cached data */ - private int boundsModID = -1; - private ArrayList cachedBounds = new ArrayList(); - private double cachedLength = -1; - - private int refLengthModID = -1; - private double cachedRefLength = -1; - - - private int modID = 0; - - - /** - * Create a new configuration with the specified Rocket with - * null motor configuration. - * - * @param rocket the rocket - */ - public Configuration(Rocket rocket) { - this.rocket = rocket; - setAllStages(); - rocket.addComponentChangeListener(this); - } - - - - public Rocket getRocket() { - return rocket; - } - - - public void setAllStages() { - stages.clear(); - stages.set(0, rocket.getStageCount()); - fireChangeEvent(); - } - - - /** - * Set all stages up to and including the given stage number. For example, - * setToStage(0) will set only the first stage active. - * - * @param stage the stage number. - */ - public void setToStage(int stage) { - stages.clear(); - stages.set(0, stage + 1, true); - // stages.set(stage+1, rocket.getStageCount(), false); - fireChangeEvent(); - } - - - /** - * Check whether the up-most stage of the rocket is in this configuration. - * - * @return true if the first stage is active in this configuration. - */ - public boolean isHead() { - return isStageActive(0); - } - - - - /** - * Check whether the stage specified by the index is active. - */ - public boolean isStageActive(int stage) { - if (stage >= rocket.getStageCount()) - return false; - return stages.get(stage); - } - - public int getStageCount() { - return rocket.getStageCount(); - } - - public int getActiveStageCount() { - int count = 0; - int s = rocket.getStageCount(); - - for (int i = 0; i < s; i++) { - if (stages.get(i)) - count++; - } - return count; - } - - public int[] getActiveStages() { - int stageCount = rocket.getStageCount(); - List active = new ArrayList(); - int[] ret; - - for (int i = 0; i < stageCount; i++) { - if (stages.get(i)) { - active.add(i); - } - } - - ret = new int[active.size()]; - for (int i = 0; i < ret.length; i++) { - ret[i] = active.get(i); - } - - return ret; - } - - - /** - * Return the reference length associated with the current configuration. The - * reference length type is retrieved from the Rocket. - * - * @return the reference length for this configuration. - */ - public double getReferenceLength() { - if (rocket.getModID() != refLengthModID) { - refLengthModID = rocket.getModID(); - cachedRefLength = rocket.getReferenceType().getReferenceLength(this); - } - return cachedRefLength; - } - - - public double getReferenceArea() { - return Math.PI * MathUtil.pow2(getReferenceLength() / 2); - } - - - public String getMotorConfigurationID() { - return motorConfiguration; - } - - public void setMotorConfigurationID(String id) { - if ((motorConfiguration == null && id == null) || - (id != null && id.equals(motorConfiguration))) - return; - - motorConfiguration = id; - fireChangeEvent(); - } - - public String getMotorConfigurationDescription() { - return rocket.getMotorConfigurationNameOrDescription(motorConfiguration); - } - - - - - - /** - * Removes the listener connection to the rocket and listeners of this object. - * This configuration may not be used after a call to this method! - */ - public void release() { - rocket.removeComponentChangeListener(this); - listenerList = null; - rocket = null; - } - - - //////////////// Listeners //////////////// - - @Override - public void addChangeListener(EventListener listener) { - listenerList.add(listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - listenerList.remove(listener); - } - - protected void fireChangeEvent() { - EventObject e = new EventObject(this); - - this.modID++; - boundsModID = -1; - refLengthModID = -1; - - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] listeners = listenerList.toArray(new EventListener[0]); - for (EventListener l : listeners) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(e); - } - } - } - - - @Override - public void componentChanged(ComponentChangeEvent e) { - fireChangeEvent(); - } - - - /////////////// Helper methods /////////////// - - /** - * Return whether this configuration has any motors defined to it. - * - * @return true if this configuration has active motor mounts with motors defined to them. - */ - public boolean hasMotors() { - for (RocketComponent c : this) { - if (c instanceof MotorMount) { - MotorMount mount = (MotorMount) c; - if (!mount.isMotorMount()) - continue; - if (mount.getMotor(this.motorConfiguration) != null) { - return true; - } - } - } - return false; - } - - - /** - * Return whether a component is in the currently active stages. - */ - public boolean isComponentActive(final RocketComponent c) { - int stage = c.getStageNumber(); - return isStageActive(stage); - } - - - /** - * Return the bounds of the current configuration. The bounds are cached. - * - * @return a Collection containing coordinates bouding the rocket. - */ - public Collection getBounds() { - if (rocket.getModID() != boundsModID) { - boundsModID = rocket.getModID(); - cachedBounds.clear(); - - double minX = Double.POSITIVE_INFINITY, maxX = Double.NEGATIVE_INFINITY; - for (RocketComponent component : this) { - for (Coordinate c : component.getComponentBounds()) { - for (Coordinate coord : component.toAbsolute(c)) { - cachedBounds.add(coord); - if (coord.x < minX) - minX = coord.x; - if (coord.x > maxX) - maxX = coord.x; - } - } - } - - if (Double.isInfinite(minX) || Double.isInfinite(maxX)) { - cachedLength = 0; - } else { - cachedLength = maxX - minX; - } - } - return cachedBounds.clone(); - } - - - /** - * Returns the length of the rocket configuration, from the foremost bound X-coordinate - * to the aft-most X-coordinate. The value is cached. - * - * @return the length of the rocket in the X-direction. - */ - public double getLength() { - if (rocket.getModID() != boundsModID) - getBounds(); // Calculates the length - - return cachedLength; - } - - - - - /** - * Return an iterator that iterates over the currently active components. - * The Rocket and Stage components are not returned, - * but instead all components that are within currently active stages. - */ - @Override - public Iterator iterator() { - return new ConfigurationIterator(); - } - - - /** - * Return an iterator that iterates over all MotorMounts within the - * current configuration that have an active motor. - * - * @return an iterator over active motor mounts. - */ - public Iterator motorIterator() { - return new MotorIterator(); - } - - - /** - * Perform a deep-clone. The object references are also cloned and no - * listeners are listening on the cloned object. The rocket instance remains the same. - */ - @Override - public Configuration clone() { - try { - Configuration config = (Configuration) super.clone(); - config.listenerList = new ArrayList(); - config.stages = (BitSet) this.stages.clone(); - config.cachedBounds = new ArrayList(); - config.boundsModID = -1; - config.refLengthModID = -1; - rocket.addComponentChangeListener(config); - return config; - } catch (CloneNotSupportedException e) { - throw new BugException("clone not supported!", e); - } - } - - - @Override - public int getModID() { - return modID + rocket.getModID(); - } - - - /** - * A class that iterates over all currently active components. - * - * @author Sampo Niskanen - */ - private class ConfigurationIterator implements Iterator { - Iterator> iterators; - Iterator current = null; - - public ConfigurationIterator() { - List> list = new ArrayList>(); - - for (RocketComponent stage : rocket.getChildren()) { - if (isComponentActive(stage)) { - list.add(stage.iterator(false)); - } - } - - // Get iterators and initialize current - iterators = list.iterator(); - if (iterators.hasNext()) { - current = iterators.next(); - } else { - List l = Collections.emptyList(); - current = l.iterator(); - } - } - - - @Override - public boolean hasNext() { - if (!current.hasNext()) - getNextIterator(); - - return current.hasNext(); - } - - @Override - public RocketComponent next() { - if (!current.hasNext()) - getNextIterator(); - - return current.next(); - } - - /** - * Get the next iterator that has items. If such an iterator does - * not exist, current is left to an empty iterator. - */ - private void getNextIterator() { - while ((!current.hasNext()) && iterators.hasNext()) { - current = iterators.next(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove unsupported"); - } - } - - private class MotorIterator implements Iterator { - private final Iterator iterator; - private MotorMount next = null; - - public MotorIterator() { - this.iterator = iterator(); - } - - @Override - public boolean hasNext() { - getNext(); - return (next != null); - } - - @Override - public MotorMount next() { - getNext(); - if (next == null) { - throw new NoSuchElementException("iterator called for too long"); - } - - MotorMount ret = next; - next = null; - return ret; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove unsupported"); - } - - private void getNext() { - if (next != null) - return; - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - if (c instanceof MotorMount) { - MotorMount mount = (MotorMount) c; - if (mount.isMotorMount() && mount.getMotor(motorConfiguration) != null) { - next = mount; - return; - } - } - } - } - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/EllipticalFinSet.java b/core/src/net/sf/openrocket/rocketcomponent/EllipticalFinSet.java deleted file mode 100644 index 0fa9497c..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/EllipticalFinSet.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -public class EllipticalFinSet extends FinSet { - private static final Translator trans = Application.getTranslator(); - - private static final int POINTS = 31; - - // Static positioning for the fin points - private static final double[] POINT_X = new double[POINTS]; - private static final double[] POINT_Y = new double[POINTS]; - static { - for (int i = 0; i < POINTS; i++) { - double a = Math.PI * (POINTS - 1 - i) / (POINTS - 1); - POINT_X[i] = (Math.cos(a) + 1) / 2; - POINT_Y[i] = Math.sin(a); - } - POINT_X[0] = 0; - POINT_Y[0] = 0; - POINT_X[POINTS - 1] = 1; - POINT_Y[POINTS - 1] = 0; - } - - - private double height = 0.05; - - public EllipticalFinSet() { - this.length = 0.05; - } - - - @Override - public Coordinate[] getFinPoints() { - double len = MathUtil.max(length, 0.0001); - Coordinate[] points = new Coordinate[POINTS]; - for (int i = 0; i < POINTS; i++) { - points[i] = new Coordinate(POINT_X[i] * len, POINT_Y[i] * height); - } - return points; - } - - @Override - public double getSpan() { - return height; - } - - @Override - public String getComponentName() { - //// Elliptical fin set - return trans.get("EllipticalFinSet.Ellipticalfinset"); - } - - - public double getHeight() { - return height; - } - - public void setHeight(double height) { - if (MathUtil.equals(this.height, height)) - return; - this.height = height; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - public void setLength(double length) { - if (MathUtil.equals(this.length, length)) - return; - this.length = length; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java b/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java deleted file mode 100644 index 660bbba1..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; - - -public class EngineBlock extends ThicknessRingComponent { - - private static final Translator trans = Application.getTranslator(); - - public EngineBlock() { - super(); - setOuterRadiusAutomatic(true); - setThickness(0.005); - setLength(0.005); - } - - @Override - public void setOuterRadiusAutomatic(boolean auto) { - super.setOuterRadiusAutomatic(auto); - } - - @Override - public String getComponentName() { - return trans.get ("EngineBlock.EngineBlock"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class type) { - return false; - } - - @Override - public Type getPresetType() { - return ComponentPreset.Type.ENGINE_BLOCK; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ExternalComponent.java b/core/src/net/sf/openrocket/rocketcomponent/ExternalComponent.java deleted file mode 100644 index 4377a8c3..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ExternalComponent.java +++ /dev/null @@ -1,167 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.List; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * Class of components with well-defined physical appearance and which have an effect on - * aerodynamic simulation. They have material defined for them, and the mass of the component - * is calculated using the component's volume. - * - * @author Sampo Niskanen - */ - -public abstract class ExternalComponent extends RocketComponent { - - public enum Finish { - //// Rough - ROUGH("ExternalComponent.Rough", 500e-6), - //// Unfinished - UNFINISHED("ExternalComponent.Unfinished", 150e-6), - //// Regular paint - NORMAL("ExternalComponent.Regularpaint", 60e-6), - //// Smooth paint - SMOOTH("ExternalComponent.Smoothpaint", 20e-6), - //// Polished - POLISHED("ExternalComponent.Polished", 2e-6); - - private static final Translator trans = Application.getTranslator(); - private final String name; - private final double roughnessSize; - - Finish(String name, double roughness) { - this.name = name; - this.roughnessSize = roughness; - } - - public double getRoughnessSize() { - return roughnessSize; - } - - @Override - public String toString() { - return trans.get(name) + " (" + UnitGroup.UNITS_ROUGHNESS.toStringUnit(roughnessSize) + ")"; - } - } - - - /** - * The material of the component. - */ - protected Material material = null; - - protected Finish finish = Finish.NORMAL; - - - - /** - * Constructor that sets the relative position of the component. - */ - public ExternalComponent(RocketComponent.Position relativePosition) { - super(relativePosition); - this.material = Application.getPreferences().getDefaultComponentMaterial(this.getClass(), Material.Type.BULK); - } - - /** - * Returns the volume of the component. This value is used in calculating the mass - * of the object. - */ - public abstract double getComponentVolume(); - - /** - * Calculates the mass of the component as the product of the volume and interior density. - */ - @Override - public double getComponentMass() { - return material.getDensity() * getComponentVolume(); - } - - /** - * ExternalComponent has aerodynamic effect, so return true. - */ - @Override - public boolean isAerodynamic() { - return true; - } - - /** - * ExternalComponent has effect on the mass, so return true. - */ - @Override - public boolean isMassive() { - return true; - } - - - public Material getMaterial() { - return material; - } - - public void setMaterial(Material mat) { - if (mat.getType() != Material.Type.BULK) { - throw new IllegalArgumentException("ExternalComponent requires a bulk material" + - " type=" + mat.getType()); - } - - if (material.equals(mat)) - return; - material = mat; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public Finish getFinish() { - return finish; - } - - public void setFinish(Finish finish) { - if (this.finish == finish) - return; - this.finish = finish; - fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE); - } - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - super.loadFromPreset(preset); - - // Surface finish is left unchanged - - if ( preset.has(ComponentPreset.MATERIAL ) ) { - Material mat = preset.get(ComponentPreset.MATERIAL); - if ( mat != null ) { - material = mat; - } /* - TODO - - else if (c.isMassOverridden()) { - double mass = c.getOverrideMass(); - double volume = getComponentVolume(); - double density; - if (volume > 0.00001) { - density = mass / volume; - } else { - density = 1000; - } - mat = Material.newMaterial(Type.BULK, mat.getName(), density, true); - setMaterial(mat); - } - */ - } - } - - - @Override - protected List copyFrom(RocketComponent c) { - ExternalComponent src = (ExternalComponent) c; - this.finish = src.finish; - this.material = src.material; - return super.copyFrom(c); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/FinSet.java b/core/src/net/sf/openrocket/rocketcomponent/FinSet.java deleted file mode 100644 index 4b8d5805..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/FinSet.java +++ /dev/null @@ -1,714 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayUtils; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Transformation; - - -public abstract class FinSet extends ExternalComponent { - private static final Translator trans = Application.getTranslator(); - - /** - * Maximum allowed cant of fins. - */ - public static final double MAX_CANT = (15.0 * Math.PI / 180); - - - public enum CrossSection { - //// Square - SQUARE(trans.get("FinSet.CrossSection.SQUARE"), 1.00), - //// Rounded - ROUNDED(trans.get("FinSet.CrossSection.ROUNDED"), 0.99), - //// Airfoil - AIRFOIL(trans.get("FinSet.CrossSection.AIRFOIL"), 0.85); - - private final String name; - private final double volume; - - CrossSection(String name, double volume) { - this.name = name; - this.volume = volume; - } - - public double getRelativeVolume() { - return volume; - } - - @Override - public String toString() { - return name; - } - } - - public enum TabRelativePosition { - //// Root chord leading edge - FRONT(trans.get("FinSet.TabRelativePosition.FRONT")), - //// Root chord midpoint - CENTER(trans.get("FinSet.TabRelativePosition.CENTER")), - //// Root chord trailing edge - END(trans.get("FinSet.TabRelativePosition.END")); - - private final String name; - - TabRelativePosition(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - } - - /** - * Number of fins. - */ - protected int fins = 3; - - /** - * Rotation about the x-axis by 2*PI/fins. - */ - protected Transformation finRotation = Transformation.rotate_x(2 * Math.PI / fins); - - /** - * Rotation angle of the first fin. Zero corresponds to the positive y-axis. - */ - protected double rotation = 0; - - /** - * Rotation about the x-axis by angle this.rotation. - */ - protected Transformation baseRotation = Transformation.rotate_x(rotation); - - - /** - * Cant angle of fins. - */ - protected double cantAngle = 0; - - /* Cached value: */ - private Transformation cantRotation = null; - - - /** - * Thickness of the fins. - */ - protected double thickness = 0.003; - - - /** - * The cross-section shape of the fins. - */ - protected CrossSection crossSection = CrossSection.SQUARE; - - - /* - * Fin tab properties. - */ - private double tabHeight = 0; - private double tabLength = 0.05; - private double tabShift = 0; - private TabRelativePosition tabRelativePosition = TabRelativePosition.CENTER; - - - // Cached fin area & CG. Validity of both must be checked using finArea! - // Fin area does not include fin tabs, CG does. - private double finArea = -1; - private double finCGx = -1; - private double finCGy = -1; - - - /** - * New FinSet with given number of fins and given base rotation angle. - * Sets the component relative position to POSITION_RELATIVE_BOTTOM, - * i.e. fins are positioned at the bottom of the parent component. - */ - public FinSet() { - super(RocketComponent.Position.BOTTOM); - } - - - - /** - * Return the number of fins in the set. - * @return The number of fins. - */ - public int getFinCount() { - return fins; - } - - /** - * Sets the number of fins in the set. - * @param n The number of fins, greater of equal to one. - */ - public void setFinCount(int n) { - if (fins == n) - return; - if (n < 1) - n = 1; - if (n > 8) - n = 8; - fins = n; - finRotation = Transformation.rotate_x(2 * Math.PI / fins); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public Transformation getFinRotationTransformation() { - return finRotation; - } - - /** - * Gets the base rotation amount of the first fin. - * @return The base rotation amount. - */ - public double getBaseRotation() { - return rotation; - } - - /** - * Sets the base rotation amount of the first fin. - * @param r The base rotation amount. - */ - public void setBaseRotation(double r) { - r = MathUtil.reduce180(r); - if (MathUtil.equals(r, rotation)) - return; - rotation = r; - baseRotation = Transformation.rotate_x(rotation); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public Transformation getBaseRotationTransformation() { - return baseRotation; - } - - - - public double getCantAngle() { - return cantAngle; - } - - public void setCantAngle(double cant) { - cant = MathUtil.clamp(cant, -MAX_CANT, MAX_CANT); - if (MathUtil.equals(cant, cantAngle)) - return; - this.cantAngle = cant; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - public Transformation getCantRotation() { - if (cantRotation == null) { - if (MathUtil.equals(cantAngle, 0)) { - cantRotation = Transformation.IDENTITY; - } else { - Transformation t = new Transformation(-length / 2, 0, 0); - t = Transformation.rotate_y(cantAngle).applyTransformation(t); - t = new Transformation(length / 2, 0, 0).applyTransformation(t); - cantRotation = t; - } - } - return cantRotation; - } - - - - public double getThickness() { - return thickness; - } - - public void setThickness(double r) { - if (thickness == r) - return; - thickness = Math.max(r, 0); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - public CrossSection getCrossSection() { - return crossSection; - } - - public void setCrossSection(CrossSection cs) { - if (crossSection == cs) - return; - crossSection = cs; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - - - @Override - public void setRelativePosition(RocketComponent.Position position) { - super.setRelativePosition(position); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public void setPositionValue(double value) { - super.setPositionValue(value); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - - public double getTabHeight() { - return tabHeight; - } - - public void setTabHeight(double height) { - height = MathUtil.max(height, 0); - if (MathUtil.equals(this.tabHeight, height)) - return; - this.tabHeight = height; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public double getTabLength() { - return tabLength; - } - - public void setTabLength(double length) { - length = MathUtil.max(length, 0); - if (MathUtil.equals(this.tabLength, length)) - return; - this.tabLength = length; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public double getTabShift() { - return tabShift; - } - - public void setTabShift(double shift) { - this.tabShift = shift; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public TabRelativePosition getTabRelativePosition() { - return tabRelativePosition; - } - - public void setTabRelativePosition(TabRelativePosition position) { - if (this.tabRelativePosition == position) - return; - - - double front = getTabFrontEdge(); - switch (position) { - case FRONT: - this.tabShift = front; - break; - - case CENTER: - this.tabShift = front + tabLength / 2 - getLength() / 2; - break; - - case END: - this.tabShift = front + tabLength - getLength(); - break; - - default: - throw new IllegalArgumentException("position=" + position); - } - this.tabRelativePosition = position; - - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - /** - * Return the tab front edge position from the front of the fin. - */ - public double getTabFrontEdge() { - switch (this.tabRelativePosition) { - case FRONT: - return tabShift; - - case CENTER: - return getLength() / 2 - tabLength / 2 + tabShift; - - case END: - return getLength() - tabLength + tabShift; - - default: - throw new IllegalStateException("tabRelativePosition=" + tabRelativePosition); - } - } - - /** - * Return the tab trailing edge position *from the front of the fin*. - */ - public double getTabTrailingEdge() { - switch (this.tabRelativePosition) { - case FRONT: - return tabLength + tabShift; - case CENTER: - return getLength() / 2 + tabLength / 2 + tabShift; - - case END: - return getLength() + tabShift; - - default: - throw new IllegalStateException("tabRelativePosition=" + tabRelativePosition); - } - } - - - - - /////////// Calculation methods /////////// - - /** - * Return the area of one side of one fin. This does NOT include the area of - * the fin tab. - * - * @return the area of one side of one fin. - */ - public double getFinArea() { - if (finArea < 0) - calculateAreaCG(); - - return finArea; - } - - - /** - * Return the unweighted CG of a single fin. The X-coordinate is relative to - * the root chord trailing edge and the Y-coordinate to the fin root chord. - * - * @return the unweighted CG coordinate of a single fin. - */ - public Coordinate getFinCG() { - if (finArea < 0) - calculateAreaCG(); - - return new Coordinate(finCGx, finCGy, 0); - } - - - - @Override - public double getComponentVolume() { - return fins * (getFinArea() + tabHeight * tabLength) * thickness * - crossSection.getRelativeVolume(); - } - - - @Override - public Coordinate getComponentCG() { - if (finArea < 0) - calculateAreaCG(); - - double mass = getComponentMass(); // safe - - if (fins == 1) { - return baseRotation.transform( - new Coordinate(finCGx, finCGy + getBodyRadius(), 0, mass)); - } else { - return new Coordinate(finCGx, 0, 0, mass); - } - } - - - private void calculateAreaCG() { - Coordinate[] points = this.getFinPoints(); - finArea = 0; - finCGx = 0; - finCGy = 0; - - for (int i = 0; i < points.length - 1; i++) { - final double x0 = points[i].x; - final double x1 = points[i + 1].x; - final double y0 = points[i].y; - final double y1 = points[i + 1].y; - - double da = (y0 + y1) * (x1 - x0) / 2; - finArea += da; - if (Math.abs(y0 - y1) < 0.00001) { - finCGx += (x0 + x1) / 2 * da; - finCGy += y0 / 2 * da; - } else { - finCGx += (x0 * (2 * y0 + y1) + x1 * (y0 + 2 * y1)) / (3 * (y0 + y1)) * da; - finCGy += (y1 + y0 * y0 / (y0 + y1)) / 3 * da; - } - } - - if (finArea < 0) - finArea = 0; - - // Add effect of fin tabs to CG - double tabArea = tabLength * tabHeight; - if (!MathUtil.equals(tabArea, 0)) { - - double x = (getTabFrontEdge() + getTabTrailingEdge()) / 2; - double y = -this.tabHeight / 2; - - finCGx += x * tabArea; - finCGy += y * tabArea; - - } - - if ((finArea + tabArea) > 0) { - finCGx /= (finArea + tabArea); - finCGy /= (finArea + tabArea); - } else { - finCGx = (points[0].x + points[points.length - 1].x) / 2; - finCGy = 0; - } - } - - - /* - * Return an approximation of the longitudinal unitary inertia of the fin set. - * The process is the following: - * - * 1. Approximate the fin with a rectangular fin - * - * 2. The inertia of one fin is taken as the average of the moments of inertia - * through its center perpendicular to the plane, and the inertia through - * its center parallel to the plane - * - * 3. If there are multiple fins, the inertia is shifted to the center of the fin - * set and multiplied by the number of fins. - */ - @Override - public double getLongitudinalUnitInertia() { - double area = getFinArea(); - if (MathUtil.equals(area, 0)) - return 0; - - // Approximate fin with a rectangular fin - // w2 and h2 are squares of the fin width and height - double w = getLength(); - double h = getSpan(); - double w2, h2; - - if (MathUtil.equals(w * h, 0)) { - w2 = area; - h2 = area; - } else { - w2 = w * area / h; - h2 = h * area / w; - } - - double inertia = (h2 + 2 * w2) / 24; - - if (fins == 1) - return inertia; - - double radius = getBodyRadius(); - - return fins * (inertia + MathUtil.pow2(MathUtil.safeSqrt(h2) + radius)); - } - - - /* - * Return an approximation of the rotational unitary inertia of the fin set. - * The process is the following: - * - * 1. Approximate the fin with a rectangular fin and calculate the inertia of the - * rectangular approximate - * - * 2. If there are multiple fins, shift the inertia center to the fin set center - * and multiply with the number of fins. - */ - @Override - public double getRotationalUnitInertia() { - double area = getFinArea(); - if (MathUtil.equals(area, 0)) - return 0; - - // Approximate fin with a rectangular fin - double w = getLength(); - double h = getSpan(); - - if (MathUtil.equals(w * h, 0)) { - h = MathUtil.safeSqrt(area); - } else { - h = MathUtil.safeSqrt(h * area / w); - } - - if (fins == 1) - return h * h / 12; - - double radius = getBodyRadius(); - - return fins * (h * h / 12 + MathUtil.pow2(h / 2 + radius)); - } - - - /** - * Adds the fin set's bounds to the collection. - */ - @Override - public Collection getComponentBounds() { - List bounds = new ArrayList(); - double r = getBodyRadius(); - - for (Coordinate point : getFinPoints()) { - addFinBound(bounds, point.x, point.y + r); - } - - return bounds; - } - - - /** - * Adds the 2d-coordinate bound (x,y) to the collection for both z-components and for - * all fin rotations. - */ - private void addFinBound(Collection set, double x, double y) { - Coordinate c; - int i; - - c = new Coordinate(x, y, thickness / 2); - c = baseRotation.transform(c); - set.add(c); - for (i = 1; i < fins; i++) { - c = finRotation.transform(c); - set.add(c); - } - - c = new Coordinate(x, y, -thickness / 2); - c = baseRotation.transform(c); - set.add(c); - for (i = 1; i < fins; i++) { - c = finRotation.transform(c); - set.add(c); - } - } - - - - @Override - public void componentChanged(ComponentChangeEvent e) { - if (e.isAerodynamicChange()) { - finArea = -1; - cantRotation = null; - } - } - - - /** - * Return the radius of the BodyComponent the fin set is situated on. Currently - * only supports SymmetricComponents and returns the radius at the starting point of the - * root chord. - * - * @return radius of the underlying BodyComponent or 0 if none exists. - */ - public double getBodyRadius() { - RocketComponent s; - - s = this.getParent(); - while (s != null) { - if (s instanceof SymmetricComponent) { - double x = this.toRelative(new Coordinate(0, 0, 0), s)[0].x; - return ((SymmetricComponent) s).getRadius(x); - } - s = s.getParent(); - } - return 0; - } - - @Override - public boolean allowsChildren() { - return false; - } - - /** - * Allows nothing to be attached to a FinSet. - * - * @return false - */ - @Override - public boolean isCompatible(Class type) { - return false; - } - - - - - /** - * Return a list of coordinates defining the geometry of a single fin. - * The coordinates are the XY-coordinates of points defining the shape of a single fin, - * where the origin is the leading root edge. Therefore, the first point must be (0,0,0). - * All Z-coordinates must be zero, and the last coordinate must have Y=0. - * - * @return List of XY-coordinates. - */ - public abstract Coordinate[] getFinPoints(); - - - /** - * Return a list of coordinates defining the geometry of a single fin, including a - * possible fin tab. The coordinates are the XY-coordinates of points defining the - * shape of a single fin, where the origin is the leading root edge. This implementation - * calls {@link #getFinPoints()} and adds the necessary points for the fin tab. - * The tab coordinates will have a negative y value. - * - * @return List of XY-coordinates. - */ - public Coordinate[] getFinPointsWithTab() { - Coordinate[] points = getFinPoints(); - - if (MathUtil.equals(getTabHeight(), 0) || - MathUtil.equals(getTabLength(), 0)) - return points; - - double x1 = getTabFrontEdge(); - double x2 = getTabTrailingEdge(); - double y = -getTabHeight(); - - int n = points.length; - points = ArrayUtils.copyOf(points, points.length + 4); - points[n] = new Coordinate(x2, 0); - points[n + 1] = new Coordinate(x2, y); - points[n + 2] = new Coordinate(x1, y); - points[n + 3] = new Coordinate(x1, 0); - return points; - } - - - - /** - * Get the span of a single fin. That is, the length from the root to the tip of the fin. - * @return Span of a single fin. - */ - public abstract double getSpan(); - - - @Override - protected List copyFrom(RocketComponent c) { - FinSet src = (FinSet) c; - this.fins = src.fins; - this.finRotation = src.finRotation; - this.rotation = src.rotation; - this.baseRotation = src.baseRotation; - this.cantAngle = src.cantAngle; - this.cantRotation = src.cantRotation; - this.thickness = src.thickness; - this.crossSection = src.crossSection; - this.tabHeight = src.tabHeight; - this.tabLength = src.tabLength; - this.tabRelativePosition = src.tabRelativePosition; - this.tabShift = src.tabShift; - - return super.copyFrom(c); - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java b/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java deleted file mode 100644 index ac52a0f8..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java +++ /dev/null @@ -1,340 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; - - -public class FreeformFinSet extends FinSet { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private ArrayList points = new ArrayList(); - - public FreeformFinSet() { - points.add(Coordinate.NUL); - points.add(new Coordinate(0.025, 0.05)); - points.add(new Coordinate(0.075, 0.05)); - points.add(new Coordinate(0.05, 0)); - - this.length = 0.05; - } - - - public FreeformFinSet(Coordinate[] finpoints) throws IllegalFinPointException { - setPoints(finpoints); - } - - /* - public FreeformFinSet(FinSet finset) { - Coordinate[] finpoints = finset.getFinPoints(); - this.copyFrom(finset); - - points.clear(); - for (Coordinate c: finpoints) { - points.add(c); - } - this.length = points.get(points.size()-1).x - points.get(0).x; - } - */ - - - /** - * Convert an existing fin set into a freeform fin set. The specified - * fin set is taken out of the rocket tree (if any) and the new component - * inserted in its stead. - *

- * The specified fin set should not be used after the call! - * - * @param finset the fin set to convert. - * @return the new freeform fin set. - */ - public static FreeformFinSet convertFinSet(FinSet finset) { - log.info("Converting " + finset.getComponentName() + " into freeform fin set"); - final RocketComponent root = finset.getRoot(); - FreeformFinSet freeform; - List toInvalidate = Collections.emptyList(); - - try { - if (root instanceof Rocket) { - ((Rocket) root).freeze(); - } - - // Get fin set position and remove fin set - final RocketComponent parent = finset.getParent(); - final int position; - if (parent != null) { - position = parent.getChildPosition(finset); - parent.removeChild(position); - } else { - position = -1; - } - - - // Create the freeform fin set - Coordinate[] finpoints = finset.getFinPoints(); - try { - freeform = new FreeformFinSet(finpoints); - } catch (IllegalFinPointException e) { - throw new BugException("Illegal fin points when converting existing fin to " + - "freeform fin, fin=" + finset + " points=" + Arrays.toString(finpoints), - e); - } - - // Copy component attributes - toInvalidate = freeform.copyFrom(finset); - - // Set name - final String componentTypeName = finset.getComponentName(); - final String name = freeform.getName(); - - if (name.startsWith(componentTypeName)) { - freeform.setName(freeform.getComponentName() + - name.substring(componentTypeName.length())); - } - - // Add freeform fin set to parent - if (parent != null) { - parent.addChild(freeform, position); - } - - } finally { - if (root instanceof Rocket) { - ((Rocket) root).thaw(); - } - // Invalidate components after events have been fired - for (RocketComponent c : toInvalidate) { - c.invalidate(); - } - } - return freeform; - } - - - - /** - * Add a fin point between indices index-1 and index. - * The point is placed at the midpoint of the current segment. - * - * @param index the fin point before which to add the new point. - */ - public void addPoint(int index) { - double x0, y0, x1, y1; - - x0 = points.get(index - 1).x; - y0 = points.get(index - 1).y; - x1 = points.get(index).x; - y1 = points.get(index).y; - - points.add(index, new Coordinate((x0 + x1) / 2, (y0 + y1) / 2)); - // adding a point within the segment affects neither mass nor aerodynamics - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - /** - * Remove the fin point with the given index. The first and last fin points - * cannot be removed, and will cause an IllegalFinPointException - * if attempted. - * - * @param index the fin point index to remove - * @throws IllegalFinPointException if removing would result in invalid fin planform - */ - public void removePoint(int index) throws IllegalFinPointException { - if (index == 0 || index == points.size() - 1) { - throw new IllegalFinPointException("cannot remove first or last point"); - } - - ArrayList copy = this.points.clone(); - copy.remove(index); - validate(copy); - this.points = copy; - - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - public int getPointCount() { - return points.size(); - } - - public void setPoints(Coordinate[] points) throws IllegalFinPointException { - setPoints(Arrays.asList(points)); - } - - public void setPoints(List points) throws IllegalFinPointException { - ArrayList list = new ArrayList(points); - validate(list); - this.points = list; - - this.length = points.get(points.size() - 1).x; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - /** - * Set the point at position i to coordinates (x,y). - *

- * Note that this method enforces basic fin shape restrictions (non-negative y, - * first and last point locations) silently, but throws an - * IllegalFinPointException if the point causes fin segments to - * intersect. - *

- * Moving of the first point in the X-axis is allowed, but this actually moves - * all of the other points the corresponding distance back. - * - * @param index the point index to modify. - * @param x the x-coordinate. - * @param y the y-coordinate. - * @throws IllegalFinPointException if the specified fin point would cause intersecting - * segments - */ - public void setPoint(int index, double x, double y) throws IllegalFinPointException { - if (y < 0) - y = 0; - - double x0, y0, x1, y1; - - if (index == 0) { - - // Restrict point - x = Math.min(x, points.get(points.size() - 1).x); - y = 0; - x0 = Double.NaN; - y0 = Double.NaN; - x1 = points.get(1).x; - y1 = points.get(1).y; - - } else if (index == points.size() - 1) { - - // Restrict point - x = Math.max(x, 0); - y = 0; - x0 = points.get(index - 1).x; - y0 = points.get(index - 1).y; - x1 = Double.NaN; - y1 = Double.NaN; - - } else { - - x0 = points.get(index - 1).x; - y0 = points.get(index - 1).y; - x1 = points.get(index + 1).x; - y1 = points.get(index + 1).y; - - } - - - - // Check for intersecting - double px0, py0, px1, py1; - px0 = 0; - py0 = 0; - for (int i = 1; i < points.size(); i++) { - px1 = points.get(i).x; - py1 = points.get(i).y; - - if (i != index - 1 && i != index && i != index + 1) { - if (intersects(x0, y0, x, y, px0, py0, px1, py1)) { - throw new IllegalFinPointException("segments intersect"); - } - } - if (i != index && i != index + 1 && i != index + 2) { - if (intersects(x, y, x1, y1, px0, py0, px1, py1)) { - throw new IllegalFinPointException("segments intersect"); - } - } - - px0 = px1; - py0 = py1; - } - - if (index == 0) { - - //System.out.println("Set point zero to x:" + x); - for (int i = 1; i < points.size(); i++) { - Coordinate c = points.get(i); - points.set(i, c.setX(c.x - x)); - } - - } else { - - points.set(index, new Coordinate(x, y)); - - } - if (index == 0 || index == points.size() - 1) { - this.length = points.get(points.size() - 1).x; - } - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - private boolean intersects(double ax0, double ay0, double ax1, double ay1, - double bx0, double by0, double bx1, double by1) { - - double d = ((by1 - by0) * (ax1 - ax0) - (bx1 - bx0) * (ay1 - ay0)); - - double ua = ((bx1 - bx0) * (ay0 - by0) - (by1 - by0) * (ax0 - bx0)) / d; - double ub = ((ax1 - ax0) * (ay0 - by0) - (ay1 - ay0) * (ax0 - bx0)) / d; - - return (ua >= 0) && (ua <= 1) && (ub >= 0) && (ub <= 1); - } - - - @Override - public Coordinate[] getFinPoints() { - return points.toArray(new Coordinate[0]); - } - - @Override - public double getSpan() { - double max = 0; - for (Coordinate c : points) { - if (c.y > max) - max = c.y; - } - return max; - } - - @Override - public String getComponentName() { - //// Freeform fin set - return trans.get("FreeformFinSet.FreeformFinSet"); - } - - - @Override - protected RocketComponent copyWithOriginalID() { - RocketComponent c = super.copyWithOriginalID(); - ((FreeformFinSet) c).points = this.points.clone(); - return c; - } - - private void validate(ArrayList pts) throws IllegalFinPointException { - final int n = pts.size(); - if (pts.get(0).x != 0 || pts.get(0).y != 0 || - pts.get(n - 1).x < 0 || pts.get(n - 1).y != 0) { - throw new IllegalFinPointException("Start or end point illegal."); - } - for (int i = 0; i < n - 1; i++) { - for (int j = i + 2; j < n - 1; j++) { - if (intersects(pts.get(i).x, pts.get(i).y, pts.get(i + 1).x, pts.get(i + 1).y, - pts.get(j).x, pts.get(j).y, pts.get(j + 1).x, pts.get(j + 1).y)) { - throw new IllegalFinPointException("segments intersect"); - } - } - if (pts.get(i).z != 0) { - throw new IllegalFinPointException("z-coordinate not zero"); - } - } - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/IllegalFinPointException.java b/core/src/net/sf/openrocket/rocketcomponent/IllegalFinPointException.java deleted file mode 100644 index 8f9a88ac..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/IllegalFinPointException.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -/** - * An exception signifying that an operation on the freeform fin set points was - * illegal (segments intersect, removing first or last point, etc). - * - * @author Sampo Niskanen - */ -public class IllegalFinPointException extends Exception { - - public IllegalFinPointException() { - - } - - public IllegalFinPointException(String message) { - super(message); - } - - public IllegalFinPointException(Throwable cause) { - super(cause); - } - - public IllegalFinPointException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java b/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java deleted file mode 100644 index 937edbf5..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java +++ /dev/null @@ -1,360 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -/** - * This class defines an inner tube that can be used as a motor mount. The component - * may also be clustered. - * - * @author Sampo Niskanen - */ -public class InnerTube extends ThicknessRingComponent - implements Clusterable, RadialParent, MotorMount { - private static final Translator trans = Application.getTranslator(); - - private ClusterConfiguration cluster = ClusterConfiguration.SINGLE; - private double clusterScale = 1.0; - private double clusterRotation = 0.0; - - - private boolean motorMount = false; - private HashMap ejectionDelays = new HashMap(); - private HashMap motors = new HashMap(); - private IgnitionEvent ignitionEvent = IgnitionEvent.AUTOMATIC; - private double ignitionDelay = 0; - private double overhang = 0; - - - /** - * Main constructor. - */ - public InnerTube() { - // A-C motor size: - this.setOuterRadius(0.019 / 2); - this.setInnerRadius(0.018 / 2); - this.setLength(0.070); - } - - - @Override - public double getInnerRadius(double x) { - return getInnerRadius(); - } - - - @Override - public double getOuterRadius(double x) { - return getOuterRadius(); - } - - - @Override - public String getComponentName() { - //// Inner Tube - return trans.get("InnerTube.InnerTube"); - } - - @Override - public boolean allowsChildren() { - return true; - } - - /** - * Allow all InternalComponents to be added to this component. - */ - @Override - public boolean isCompatible(Class type) { - return InternalComponent.class.isAssignableFrom(type); - } - - @Override - public ComponentPreset.Type getPresetType() { - return ComponentPreset.Type.BODY_TUBE; - } - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.OUTER_DIAMETER) ) { - double outerDiameter = preset.get(ComponentPreset.OUTER_DIAMETER); - this.outerRadius = outerDiameter/2.0; - if ( preset.has(ComponentPreset.INNER_DIAMETER) ) { - double innerDiameter = preset.get(ComponentPreset.INNER_DIAMETER); - this.thickness = (outerDiameter-innerDiameter) / 2.0; - } - } - - super.loadFromPreset(preset); - - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - ///////////// Cluster methods ////////////// - - /** - * Get the current cluster configuration. - * @return The current cluster configuration. - */ - @Override - public ClusterConfiguration getClusterConfiguration() { - return cluster; - } - - /** - * Set the current cluster configuration. - * @param cluster The cluster configuration. - */ - @Override - public void setClusterConfiguration(ClusterConfiguration cluster) { - this.cluster = cluster; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - /** - * Return the number of tubes in the cluster. - * @return Number of tubes in the current cluster. - */ - @Override - public int getClusterCount() { - return cluster.getClusterCount(); - } - - /** - * Get the cluster scaling. A value of 1.0 indicates that the tubes are packed - * touching each other, larger values separate the tubes and smaller values - * pack inside each other. - */ - public double getClusterScale() { - return clusterScale; - } - - /** - * Set the cluster scaling. - * @see #getClusterScale() - */ - public void setClusterScale(double scale) { - scale = Math.max(scale, 0); - if (MathUtil.equals(clusterScale, scale)) - return; - clusterScale = scale; - fireComponentChangeEvent(new ComponentChangeEvent(this, ComponentChangeEvent.MASS_CHANGE)); - } - - - - /** - * @return the clusterRotation - */ - public double getClusterRotation() { - return clusterRotation; - } - - - /** - * @param rotation the clusterRotation to set - */ - public void setClusterRotation(double rotation) { - rotation = MathUtil.reduce180(rotation); - if (clusterRotation == rotation) - return; - this.clusterRotation = rotation; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - /** - * Return the distance between the closest two cluster inner tube center points. - * This is equivalent to the cluster scale multiplied by the tube diameter. - */ - @Override - public double getClusterSeparation() { - return 2 * getOuterRadius() * clusterScale; - } - - - public List getClusterPoints() { - List list = new ArrayList(getClusterCount()); - List points = cluster.getPoints(clusterRotation - getRadialDirection()); - double separation = getClusterSeparation(); - for (int i = 0; i < points.size() / 2; i++) { - list.add(new Coordinate(0, points.get(2 * i) * separation, points.get(2 * i + 1) * separation)); - } - return list; - } - - - @Override - public Coordinate[] shiftCoordinates(Coordinate[] array) { - array = super.shiftCoordinates(array); - - int count = getClusterCount(); - if (count == 1) - return array; - - List points = getClusterPoints(); - if (points.size() != count) { - throw new BugException("Inconsistent cluster configuration, cluster count=" + count + - " point count=" + points.size()); - } - Coordinate[] newArray = new Coordinate[array.length * count]; - for (int i = 0; i < array.length; i++) { - for (int j = 0; j < count; j++) { - newArray[i * count + j] = array[i].add(points.get(j)); - } - } - - return newArray; - } - - - - - //////////////// Motor mount ///////////////// - - @Override - public boolean isMotorMount() { - return motorMount; - } - - @Override - public void setMotorMount(boolean mount) { - if (motorMount == mount) - return; - motorMount = mount; - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - @Override - public Motor getMotor(String id) { - if (id == null) - return null; - - // Check whether the id is valid for the current rocket - RocketComponent root = this.getRoot(); - if (!(root instanceof Rocket)) - return null; - if (!((Rocket) root).isMotorConfigurationID(id)) - return null; - - return motors.get(id); - } - - @Override - public void setMotor(String id, Motor motor) { - if (id == null) { - if (motor != null) { - throw new IllegalArgumentException("Cannot set non-null motor for id null"); - } - } - Motor current = motors.get(id); - if ((motor == null && current == null) || - (motor != null && motor.equals(current))) - return; - motors.put(id, motor); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - @Override - public double getMotorDelay(String id) { - Double delay = ejectionDelays.get(id); - if (delay == null) - return Motor.PLUGGED; - return delay; - } - - @Override - public void setMotorDelay(String id, double delay) { - ejectionDelays.put(id, delay); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - @Deprecated - @Override - public int getMotorCount() { - return getClusterCount(); - } - - @Override - public double getMotorMountDiameter() { - return getInnerRadius() * 2; - } - - @Override - public IgnitionEvent getIgnitionEvent() { - return ignitionEvent; - } - - @Override - public void setIgnitionEvent(IgnitionEvent event) { - if (ignitionEvent == event) - return; - ignitionEvent = event; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - @Override - public double getIgnitionDelay() { - return ignitionDelay; - } - - @Override - public void setIgnitionDelay(double delay) { - if (MathUtil.equals(delay, ignitionDelay)) - return; - ignitionDelay = delay; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - @Override - public double getMotorOverhang() { - return overhang; - } - - @Override - public void setMotorOverhang(double overhang) { - if (MathUtil.equals(this.overhang, overhang)) - return; - this.overhang = overhang; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public Coordinate getMotorPosition(String id) { - Motor motor = motors.get(id); - if (motor == null) { - throw new IllegalArgumentException("No motor with id " + id + " defined."); - } - - return new Coordinate(this.getLength() - motor.getLength() + this.getMotorOverhang()); - } - - /* - * (non-Javadoc) - * Copy the motor and ejection delay HashMaps. - * - * @see rocketcomponent.RocketComponent#copy() - */ - @SuppressWarnings("unchecked") - @Override - protected RocketComponent copyWithOriginalID() { - RocketComponent c = super.copyWithOriginalID(); - ((InnerTube) c).motors = (HashMap) motors.clone(); - ((InnerTube) c).ejectionDelays = (HashMap) ejectionDelays.clone(); - return c; - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/rocketcomponent/InternalComponent.java b/core/src/net/sf/openrocket/rocketcomponent/InternalComponent.java deleted file mode 100644 index 1f2dba40..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/InternalComponent.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - - -/** - * A component internal to the rocket. Internal components have no effect on the - * the aerodynamics of a rocket, only its mass properties (though the location of the - * components is not enforced to be within external components). Internal components - * are always attached relative to the parent component, which can be internal or - * external, or absolutely. - * - * @author Sampo Niskanen - */ -public abstract class InternalComponent extends RocketComponent { - - public InternalComponent() { - super(RocketComponent.Position.BOTTOM); - } - - - @Override - public final void setRelativePosition(RocketComponent.Position position) { - super.setRelativePosition(position); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - @Override - public final void setPositionValue(double value) { - super.setPositionValue(value); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - /** - * Non-aerodynamic components. - * @return false - */ - @Override - public final boolean isAerodynamic() { - return false; - } - - /** - * Is massive. - * @return true - */ - @Override - public final boolean isMassive() { - return true; - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java b/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java deleted file mode 100644 index 43709436..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java +++ /dev/null @@ -1,235 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.ArrayList; -import java.util.Collection; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - - -public class LaunchLug extends ExternalComponent implements Coaxial { - - private static final Translator trans = Application.getTranslator(); - - private double radius; - private double thickness; - - private double radialDirection = 0; - - /* These are calculated when the component is first attached to any Rocket */ - private double shiftY, shiftZ; - - - - public LaunchLug() { - super(Position.MIDDLE); - radius = 0.01 / 2; - thickness = 0.001; - length = 0.03; - } - - - @Override - public double getOuterRadius() { - return radius; - } - - @Override - public void setOuterRadius(double radius) { - if (MathUtil.equals(this.radius, radius)) - return; - this.radius = radius; - this.thickness = Math.min(this.thickness, this.radius); - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public double getInnerRadius() { - return radius - thickness; - } - - @Override - public void setInnerRadius(double innerRadius) { - setOuterRadius(innerRadius + thickness); - } - - @Override - public double getThickness() { - return thickness; - } - - public void setThickness(double thickness) { - if (MathUtil.equals(this.thickness, thickness)) - return; - this.thickness = MathUtil.clamp(thickness, 0, radius); - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - public double getRadialDirection() { - return radialDirection; - } - - public void setRadialDirection(double direction) { - direction = MathUtil.reduce180(direction); - if (MathUtil.equals(this.radialDirection, direction)) - return; - this.radialDirection = direction; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - public void setLength(double length) { - if (MathUtil.equals(this.length, length)) - return; - this.length = length; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - - - @Override - public void setRelativePosition(RocketComponent.Position position) { - super.setRelativePosition(position); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public void setPositionValue(double value) { - super.setPositionValue(value); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.OUTER_DIAMETER) ) { - double outerDiameter = preset.get(ComponentPreset.OUTER_DIAMETER); - this.radius = outerDiameter/2.0; - if ( preset.has(ComponentPreset.INNER_DIAMETER) ) { - double innerDiameter = preset.get(ComponentPreset.INNER_DIAMETER); - this.thickness = (outerDiameter-innerDiameter) / 2.0; - } - } - - super.loadFromPreset(preset); - - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public Type getPresetType() { - return ComponentPreset.Type.LAUNCH_LUG; - } - - - @Override - public Coordinate[] shiftCoordinates(Coordinate[] array) { - array = super.shiftCoordinates(array); - - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(0, shiftY, shiftZ); - } - - return array; - } - - - @Override - public void componentChanged(ComponentChangeEvent e) { - super.componentChanged(e); - - /* - * shiftY and shiftZ must be computed here since calculating them - * in shiftCoordinates() would cause an infinite loop due to .toRelative - */ - RocketComponent body; - double parentRadius; - - for (body = this.getParent(); body != null; body = body.getParent()) { - if (body instanceof SymmetricComponent) - break; - } - - if (body == null) { - parentRadius = 0; - } else { - SymmetricComponent s = (SymmetricComponent) body; - double x1, x2; - x1 = this.toRelative(Coordinate.NUL, body)[0].x; - x2 = this.toRelative(new Coordinate(length, 0, 0), body)[0].x; - x1 = MathUtil.clamp(x1, 0, body.getLength()); - x2 = MathUtil.clamp(x2, 0, body.getLength()); - parentRadius = Math.max(s.getRadius(x1), s.getRadius(x2)); - } - - shiftY = Math.cos(radialDirection) * (parentRadius + radius); - shiftZ = Math.sin(radialDirection) * (parentRadius + radius); - - // System.out.println("Computed shift: y="+shiftY+" z="+shiftZ); - } - - - - - @Override - public double getComponentVolume() { - return length * Math.PI * (MathUtil.pow2(radius) - MathUtil.pow2(radius - thickness)); - } - - @Override - public Collection getComponentBounds() { - ArrayList set = new ArrayList(); - addBound(set, 0, radius); - addBound(set, length, radius); - return set; - } - - @Override - public Coordinate getComponentCG() { - return new Coordinate(length / 2, 0, 0, getComponentMass()); - } - - @Override - public String getComponentName() { - //// Launch lug - return trans.get("LaunchLug.Launchlug"); - } - - @Override - public double getLongitudinalUnitInertia() { - // 1/12 * (3 * (r1^2 + r2^2) + h^2) - return (3 * (MathUtil.pow2(getInnerRadius())) + MathUtil.pow2(getOuterRadius()) + MathUtil.pow2(getLength())) / 12; - } - - @Override - public double getRotationalUnitInertia() { - // 1/2 * (r1^2 + r2^2) - return (MathUtil.pow2(getInnerRadius()) + MathUtil.pow2(getOuterRadius())) / 2; - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class type) { - // Allow nothing to be attached to a LaunchLug - return false; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java b/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java deleted file mode 100644 index 81e5a63d..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - -/** - * This class represents a generic component that has a specific mass and an approximate shape. - * The mass is accessed via get/setComponentMass. - * - * @author Sampo Niskanen - */ -public class MassComponent extends MassObject { - private static final Translator trans = Application.getTranslator(); - - private double mass = 0; - - - public MassComponent() { - super(); - } - - public MassComponent(double length, double radius, double mass) { - super(length, radius); - this.mass = mass; - } - - - @Override - public double getComponentMass() { - return mass; - } - - public void setComponentMass(double mass) { - mass = Math.max(mass, 0); - if (MathUtil.equals(this.mass, mass)) - return; - this.mass = mass; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public double getDensity() { - double d = getComponentMass() / getVolume(); - if (Double.isNaN(d)) - d = 0; - return d; - } - - public void setDensity(double density) { - double m = density * getVolume(); - m = MathUtil.clamp(m, 0, 1000000); - if (Double.isNaN(m)) - m = 0; - setComponentMass(m); - } - - - private double getVolume() { - return Math.PI * MathUtil.pow2(getRadius()) * getLength(); - } - - - @Override - public String getComponentName() { - //// Mass component - return trans.get("MassComponent.MassComponent"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class type) { - // Allow no components to be attached to a MassComponent - return false; - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/MassObject.java b/core/src/net/sf/openrocket/rocketcomponent/MassObject.java deleted file mode 100644 index fb4aa744..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/MassObject.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import static net.sf.openrocket.util.MathUtil.pow2; - -import java.util.ArrayList; -import java.util.Collection; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -/** - * A MassObject is an internal component that can a specific weight, but not necessarily a strictly bound shape. It is - * represented as a homogeneous cylinder and drawn in the rocket figure with rounded corners. - *

- * Subclasses of this class need only implement the {@link #getComponentMass()}, {@link #getComponentName()} and {@link - * #isCompatible(RocketComponent)} methods. - * - * @author Sampo Niskanen - */ -public abstract class MassObject extends InternalComponent { - - private double radius; - - private double radialPosition; - private double radialDirection; - - private double shiftY = 0; - private double shiftZ = 0; - - - public MassObject() { - this(0.025, 0.0125); - } - - public MassObject(double length, double radius) { - super(); - - this.length = length; - this.radius = radius; - - this.setRelativePosition(Position.TOP); - this.setPositionValue(0.0); - } - - - public void setLength(double length) { - length = Math.max(length, 0); - if (MathUtil.equals(this.length, length)) { - return; - } - this.length = length; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public final double getRadius() { - return radius; - } - - - public final void setRadius(double radius) { - radius = Math.max(radius, 0); - if (MathUtil.equals(this.radius, radius)) { - return; - } - this.radius = radius; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - public final double getRadialPosition() { - return radialPosition; - } - - public final void setRadialPosition(double radialPosition) { - radialPosition = Math.max(radialPosition, 0); - if (MathUtil.equals(this.radialPosition, radialPosition)) { - return; - } - this.radialPosition = radialPosition; - shiftY = radialPosition * Math.cos(radialDirection); - shiftZ = radialPosition * Math.sin(radialDirection); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public final double getRadialDirection() { - return radialDirection; - } - - public final void setRadialDirection(double radialDirection) { - radialDirection = MathUtil.reduce180(radialDirection); - if (MathUtil.equals(this.radialDirection, radialDirection)) { - return; - } - this.radialDirection = radialDirection; - shiftY = radialPosition * Math.cos(radialDirection); - shiftZ = radialPosition * Math.sin(radialDirection); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - /** - * Shift the coordinates according to the radial position and direction. - */ - @Override - public final Coordinate[] shiftCoordinates(Coordinate[] array) { - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(0, shiftY, shiftZ); - } - return array; - } - - @Override - public final Coordinate getComponentCG() { - return new Coordinate(length / 2, shiftY, shiftZ, getComponentMass()); - } - - @Override - public final double getLongitudinalUnitInertia() { - return (3 * pow2(radius) + pow2(length)) / 12; - } - - @Override - public final double getRotationalUnitInertia() { - return pow2(radius) / 2; - } - - @Override - public final Collection getComponentBounds() { - Collection c = new ArrayList(); - addBound(c, 0, radius); - addBound(c, length, radius); - return c; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/MotorMount.java b/core/src/net/sf/openrocket/rocketcomponent/MotorMount.java deleted file mode 100644 index 1c849d4d..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/MotorMount.java +++ /dev/null @@ -1,213 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Coordinate; - -public interface MotorMount extends ChangeSource { - - public static enum IgnitionEvent { - //// Automatic (launch or ejection charge) - AUTOMATIC("MotorMount.IgnitionEvent.AUTOMATIC") { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - int count = source.getRocket().getStageCount(); - int stage = source.getStageNumber(); - - if (stage == count - 1) { - return LAUNCH.isActivationEvent(e, source); - } else { - return EJECTION_CHARGE.isActivationEvent(e, source); - } - } - }, - //// Launch - LAUNCH("MotorMount.IgnitionEvent.LAUNCH") { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - return (e.getType() == FlightEvent.Type.LAUNCH); - } - }, - //// First ejection charge of previous stage - EJECTION_CHARGE("MotorMount.IgnitionEvent.EJECTION_CHARGE") { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - if (e.getType() != FlightEvent.Type.EJECTION_CHARGE) - return false; - - int charge = e.getSource().getStageNumber(); - int mount = source.getStageNumber(); - return (mount + 1 == charge); - } - }, - //// First burnout of previous stage - BURNOUT("MotorMount.IgnitionEvent.BURNOUT") { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - if (e.getType() != FlightEvent.Type.BURNOUT) - return false; - - int charge = e.getSource().getStageNumber(); - int mount = source.getStageNumber(); - return (mount + 1 == charge); - } - }, - //// Never - NEVER("MotorMount.IgnitionEvent.NEVER") { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - return false; - } - }, - ; - - - private static final Translator trans = Application.getTranslator(); - private final String description; - - IgnitionEvent(String description) { - this.description = description; - } - - public abstract boolean isActivationEvent(FlightEvent e, RocketComponent source); - - @Override - public String toString() { - return trans.get(description); - } - }; - - - /** - * Is the component currently a motor mount. - * - * @return whether the component holds a motor. - */ - public boolean isMotorMount(); - - /** - * Set whether the component is currently a motor mount. - */ - public void setMotorMount(boolean mount); - - - /** - * Return the motor for the motor configuration. May return null - * if no motor has been set. This method must return null if ID - * is null or if the ID is not valid for the current rocket - * (or if the component is not part of any rocket). - * - * @param id the motor configuration ID - * @return the motor, or null if not set. - */ - public Motor getMotor(String id); - - /** - * Set the motor for the motor configuration. May be set to null - * to remove the motor. - * - * @param id the motor configuration ID - * @param motor the motor, or null. - */ - public void setMotor(String id, Motor motor); - - /** - * Get the number of similar motors clustered. - * - * TODO: HIGH: This should not be used, since the components themselves can be clustered - * - * @return the number of motors. - */ - @Deprecated - public int getMotorCount(); - - - - /** - * Return the ejection charge delay of given motor configuration. - * A "plugged" motor without an ejection charge is given by - * {@link Motor#PLUGGED} (Double.POSITIVE_INFINITY). - * - * @param id the motor configuration ID - * @return the ejection charge delay. - */ - public double getMotorDelay(String id); - - /** - * Set the ejection change delay of the given motor configuration. - * The ejection charge is disable (a "plugged" motor) is set by - * {@link Motor#PLUGGED} (Double.POSITIVE_INFINITY). - * - * @param id the motor configuration ID - * @param delay the ejection charge delay. - */ - public void setMotorDelay(String id, double delay); - - - /** - * Return the event that ignites this motor. - * - * @return the {@link IgnitionEvent} that ignites this motor. - */ - public IgnitionEvent getIgnitionEvent(); - - /** - * Sets the event that ignites this motor. - * - * @param event the {@link IgnitionEvent} that ignites this motor. - */ - public void setIgnitionEvent(IgnitionEvent event); - - - /** - * Returns the ignition delay of this motor. - * - * @return the ignition delay - */ - public double getIgnitionDelay(); - - /** - * Sets the ignition delay of this motor. - * - * @param delay the ignition delay. - */ - public void setIgnitionDelay(double delay); - - - /** - * Return the distance that the motors hang outside this motor mount. - * - * @return the overhang length. - */ - public double getMotorOverhang(); - - /** - * Sets the distance that the motors hang outside this motor mount. - * - * @param overhang the overhang length. - */ - public void setMotorOverhang(double overhang); - - - - /** - * Return the inner diameter of the motor mount. - * - * @return the inner diameter of the motor mount. - */ - public double getMotorMountDiameter(); - - - /** - * Return the position of the motor relative to this component. The coordinate - * is that of the front cap of the motor. - * - * @return the position of the motor relative to this component. - * @throws IllegalArgumentException if a motor with the specified ID does not exist. - */ - public Coordinate getMotorPosition(String id); - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java b/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java deleted file mode 100644 index 6ef65ed2..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java +++ /dev/null @@ -1,137 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; - -/** - * Rocket nose cones of various types. Implemented as a transition with the - * fore radius == 0. - * - * @author Sampo Niskanen - */ - -public class NoseCone extends Transition { - private static final Translator trans = Application.getTranslator(); - - - /********* Constructors **********/ - public NoseCone() { - this(Transition.Shape.OGIVE, 6 * DEFAULT_RADIUS, DEFAULT_RADIUS); - } - - public NoseCone(Transition.Shape type, double length, double radius) { - super(); - super.setType(type); - super.setForeRadiusAutomatic(false); - super.setForeRadius(0); - super.setForeShoulderLength(0); - super.setForeShoulderRadius(0.9 * radius); - super.setForeShoulderThickness(0); - super.setForeShoulderCapped(filled); - super.setThickness(0.002); - super.setLength(length); - super.setClipped(false); - - } - - - /********** Get/set methods for component parameters **********/ - - @Override - public double getForeRadius() { - return 0; - } - - @Override - public void setForeRadius(double r) { - // No-op - } - - @Override - public boolean isForeRadiusAutomatic() { - return false; - } - - @Override - public void setForeRadiusAutomatic(boolean b) { - // No-op - } - - @Override - public double getForeShoulderLength() { - return 0; - } - - @Override - public double getForeShoulderRadius() { - return 0; - } - - @Override - public double getForeShoulderThickness() { - return 0; - } - - @Override - public boolean isForeShoulderCapped() { - return false; - } - - @Override - public void setForeShoulderCapped(boolean capped) { - // No-op - } - - @Override - public void setForeShoulderLength(double foreShoulderLength) { - // No-op - } - - @Override - public void setForeShoulderRadius(double foreShoulderRadius) { - // No-op - } - - @Override - public void setForeShoulderThickness(double foreShoulderThickness) { - // No-op - } - - @Override - public boolean isClipped() { - return false; - } - - @Override - public void setClipped(boolean b) { - // No-op - } - - - - /********** RocketComponent methods **********/ - - @Override - public Type getPresetType() { - return ComponentPreset.Type.NOSE_CONE; - } - - @Override - protected void loadFromPreset(ComponentPreset preset) { - - //Many parameters are handled by the super class Transition.loadFromPreset - super.loadFromPreset(preset); - } - - /** - * Return component name. - */ - @Override - public String getComponentName() { - //// Nose cone - return trans.get("NoseCone.NoseCone"); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Parachute.java b/core/src/net/sf/openrocket/rocketcomponent/Parachute.java deleted file mode 100644 index aabb6117..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Parachute.java +++ /dev/null @@ -1,151 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - -public class Parachute extends RecoveryDevice { - private static final Translator trans = Application.getTranslator(); - - public static final double DEFAULT_CD = 0.8; - - private double diameter; - - private Material lineMaterial; - private int lineCount = 6; - private double lineLength = 0.3; - - - public Parachute() { - this.diameter = 0.3; - this.lineMaterial = Application.getPreferences().getDefaultComponentMaterial(Parachute.class, Material.Type.LINE); - this.lineLength = 0.3; - } - - - public double getDiameter() { - return diameter; - } - - public void setDiameter(double d) { - if (MathUtil.equals(this.diameter, d)) - return; - this.diameter = d; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - public final Material getLineMaterial() { - return lineMaterial; - } - - public final void setLineMaterial(Material mat) { - if (mat.getType() != Material.Type.LINE) { - throw new IllegalArgumentException("Attempted to set non-line material " + mat); - } - if (mat.equals(lineMaterial)) - return; - this.lineMaterial = mat; - if (getLineCount() != 0) - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - else - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - public final int getLineCount() { - return lineCount; - } - - public final void setLineCount(int n) { - if (this.lineCount == n) - return; - this.lineCount = n; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public final double getLineLength() { - return lineLength; - } - - public final void setLineLength(double length) { - if (MathUtil.equals(this.lineLength, length)) - return; - this.lineLength = length; - if (getLineCount() != 0) - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - else - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - @Override - public double getComponentCD(double mach) { - return DEFAULT_CD; // TODO: HIGH: Better parachute CD estimate? - } - - @Override - public double getArea() { - return Math.PI * MathUtil.pow2(diameter / 2); - } - - public void setArea(double area) { - if (MathUtil.equals(getArea(), area)) - return; - diameter = MathUtil.safeSqrt(area / Math.PI) * 2; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public double getComponentMass() { - return super.getComponentMass() + - getLineCount() * getLineLength() * getLineMaterial().getDensity(); - } - - @Override - public String getComponentName() { - //// Parachute - return trans.get("Parachute.Parachute"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class type) { - return false; - } - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if( preset.has( ComponentPreset.DIAMETER )) { - this.diameter = preset.get( ComponentPreset.DIAMETER ); - } - if( preset.has( ComponentPreset.LINE_COUNT )) { - this.lineCount = preset.get( ComponentPreset.LINE_COUNT ); - } - if( preset.has( ComponentPreset.LINE_LENGTH )) { - this.lineLength = preset.get( ComponentPreset.LINE_LENGTH ); - } - if( preset.has( ComponentPreset.LINE_MATERIAL )) { - this.lineMaterial = preset.get( ComponentPreset.LINE_MATERIAL ); - } - super.loadFromPreset(preset); - } - - - @Override - public Type getPresetType() { - return ComponentPreset.Type.PARACHUTE; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/RadialParent.java b/core/src/net/sf/openrocket/rocketcomponent/RadialParent.java deleted file mode 100644 index 41c731af..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/RadialParent.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -public interface RadialParent { - - /** - * Return the outer radius of the component at local coordinate x. - * Values for x < 0 and x > getLength() are undefined. - * - * @param x the lengthwise position in the coordinates of this component. - * @return the outer radius of the component at that position. - */ - public double getOuterRadius(double x); - - /** - * Return the inner radius of the component at local coordinate x. - * Values for x < 0 and x > getLength() are undefined. - * - * @param x the lengthwise position in the coordinates of this component. - * @return the inner radius of the component at that position. - */ - public double getInnerRadius(double x); - - - /** - * Return the length of this component. - * - * @return the length of this component. - */ - public double getLength(); - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/RadiusRingComponent.java b/core/src/net/sf/openrocket/rocketcomponent/RadiusRingComponent.java deleted file mode 100644 index 6d0ccb65..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/RadiusRingComponent.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -/** - * An inner component that consists of a hollow cylindrical component. This can be - * an inner tube, tube coupler, centering ring, bulkhead etc. - * - * The properties include the inner and outer radii, length and radial position. - * - * @author Sampo Niskanen - */ -public abstract class RadiusRingComponent extends RingComponent implements Coaxial { - - protected double outerRadius = 0; - protected double innerRadius = 0; - - @Override - protected void loadFromPreset(ComponentPreset preset) { - super.loadFromPreset(preset); - if ( preset.has(ComponentPreset.OUTER_DIAMETER)) { - this.outerRadius = preset.get(ComponentPreset.OUTER_DIAMETER) / 2.0; - this.outerRadiusAutomatic = false; - } - this.innerRadiusAutomatic = false; - if ( preset.has(ComponentPreset.INNER_DIAMETER)) { - this.innerRadius = preset.get(ComponentPreset.INNER_DIAMETER) / 2.0; - } - - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - - } - - @Override - public double getOuterRadius() { - if (outerRadiusAutomatic && getParent() instanceof RadialParent) { - RocketComponent parent = getParent(); - double pos1 = this.toRelative(Coordinate.NUL, parent)[0].x; - double pos2 = this.toRelative(new Coordinate(getLength()), parent)[0].x; - pos1 = MathUtil.clamp(pos1, 0, parent.getLength()); - pos2 = MathUtil.clamp(pos2, 0, parent.getLength()); - outerRadius = Math.min(((RadialParent)parent).getInnerRadius(pos1), - ((RadialParent)parent).getInnerRadius(pos2)); - } - - return outerRadius; - } - - @Override - public void setOuterRadius(double r) { - r = Math.max(r,0); - if (MathUtil.equals(outerRadius, r) && !isOuterRadiusAutomatic()) - return; - - outerRadius = r; - outerRadiusAutomatic = false; - if (getInnerRadius() > r) { - innerRadius = r; - innerRadiusAutomatic = false; - } - - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - @Override - public double getInnerRadius() { - return innerRadius; - } - @Override - public void setInnerRadius(double r) { - r = Math.max(r,0); - if (MathUtil.equals(innerRadius, r)) - return; - - innerRadius = r; - innerRadiusAutomatic = false; - if (getOuterRadius() < r) { - outerRadius = r; - outerRadiusAutomatic = false; - } - - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - @Override - public double getThickness() { - return Math.max(getOuterRadius() - getInnerRadius(), 0); - } - @Override - public void setThickness(double thickness) { - double outer = getOuterRadius(); - - thickness = MathUtil.clamp(thickness, 0, outer); - setInnerRadius(outer - thickness); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java b/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java deleted file mode 100644 index 3c5a88f1..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java +++ /dev/null @@ -1,237 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Pair; - - -/** - * RecoveryDevice is a class representing devices that slow down descent. - * Recovery devices report that they have no aerodynamic effect, since they - * are within the rocket during ascent. - *

- * A recovery device includes a surface material of which it is made of. - * The mass of the component is calculated based on the material and the - * area of the device from {@link #getArea()}. {@link #getComponentMass()} - * may be overridden if additional mass needs to be included. - * - * @author Sampo Niskanen - */ -public abstract class RecoveryDevice extends MassObject { - private static final Translator trans = Application.getTranslator(); - - public static enum DeployEvent { - LAUNCH(trans.get("RecoveryDevice.DeployEvent.LAUNCH")) { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - return e.getType() == FlightEvent.Type.LAUNCH; - } - }, - EJECTION(trans.get("RecoveryDevice.DeployEvent.EJECTION")) { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - if (e.getType() != FlightEvent.Type.EJECTION_CHARGE) - return false; - RocketComponent charge = e.getSource(); - return charge.getStageNumber() == source.getStageNumber(); - } - }, - APOGEE(trans.get("RecoveryDevice.DeployEvent.APOGEE")) { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - return e.getType() == FlightEvent.Type.APOGEE; - } - }, - ALTITUDE(trans.get("RecoveryDevice.DeployEvent.ALTITUDE")) { - @SuppressWarnings("unchecked") - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - if (e.getType() != FlightEvent.Type.ALTITUDE) - return false; - - double alt = ((RecoveryDevice) source).getDeployAltitude(); - Pair altitude = (Pair) e.getData(); - - return (altitude.getU() >= alt) && (altitude.getV() <= alt); - } - }, - LOWER_STAGE_SEPARATION(trans.get("RecoveryDevice.DeployEvent.LOWER_STAGE_SEPARATION")) { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - if (e.getType() != FlightEvent.Type.STAGE_SEPARATION) - return false; - - int separation = e.getSource().getStageNumber(); - int current = source.getStageNumber(); - return (current + 1 == separation); - } - }, - NEVER(trans.get("RecoveryDevice.DeployEvent.NEVER")) { - @Override - public boolean isActivationEvent(FlightEvent e, RocketComponent source) { - return false; - } - }; - - private final String description; - - DeployEvent(String description) { - this.description = description; - } - - public abstract boolean isActivationEvent(FlightEvent e, RocketComponent source); - - @Override - public String toString() { - return description; - } - - } - - - private DeployEvent deployEvent = DeployEvent.EJECTION; - private double deployAltitude = 200; - private double deployDelay = 0; - - private double cd = Parachute.DEFAULT_CD; - private boolean cdAutomatic = true; - - - private Material.Surface material; - - - public RecoveryDevice() { - this(Application.getPreferences().getDefaultComponentMaterial(RecoveryDevice.class, Material.Type.SURFACE)); - } - - public RecoveryDevice(Material material) { - super(); - setMaterial(material); - } - - public RecoveryDevice(double length, double radius, Material material) { - super(length, radius); - setMaterial(material); - } - - - - - public abstract double getArea(); - - public abstract double getComponentCD(double mach); - - - - public double getCD() { - return getCD(0); - } - - public double getCD(double mach) { - if (cdAutomatic) - cd = getComponentCD(mach); - return cd; - } - - public void setCD(double cd) { - if (MathUtil.equals(this.cd, cd) && !isCDAutomatic()) - return; - this.cd = cd; - this.cdAutomatic = false; - fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE); - } - - - public boolean isCDAutomatic() { - return cdAutomatic; - } - - public void setCDAutomatic(boolean auto) { - if (cdAutomatic == auto) - return; - this.cdAutomatic = auto; - fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE); - } - - - - public final Material getMaterial() { - return material; - } - - public final void setMaterial(Material mat) { - if (!(mat instanceof Material.Surface)) { - throw new IllegalArgumentException("Attempted to set non-surface material " + mat); - } - if (mat.equals(material)) - return; - this.material = (Material.Surface) mat; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - public DeployEvent getDeployEvent() { - return deployEvent; - } - - public void setDeployEvent(DeployEvent deployEvent) { - if (this.deployEvent == deployEvent) - return; - this.deployEvent = deployEvent; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - public double getDeployAltitude() { - return deployAltitude; - } - - public void setDeployAltitude(double deployAltitude) { - if (MathUtil.equals(this.deployAltitude, deployAltitude)) - return; - this.deployAltitude = deployAltitude; - if (getDeployEvent() == DeployEvent.ALTITUDE) - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - else - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - public double getDeployDelay() { - return deployDelay; - } - - public void setDeployDelay(double delay) { - delay = MathUtil.max(delay, 0); - if (MathUtil.equals(this.deployDelay, delay)) - return; - this.deployDelay = delay; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - - @Override - public double getComponentMass() { - return getArea() * getMaterial().getDensity(); - } - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.MATERIAL)) { - Material m = preset.get(ComponentPreset.MATERIAL); - this.material = (Material.Surface)m; - } - super.loadFromPreset(preset); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ReferenceType.java b/core/src/net/sf/openrocket/rocketcomponent/ReferenceType.java deleted file mode 100644 index 02264ebe..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ReferenceType.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * - */ -package net.sf.openrocket.rocketcomponent; - -public enum ReferenceType { - - NOSECONE { - @Override - public double getReferenceLength(Configuration config) { - for (RocketComponent c: config) { - if (c instanceof SymmetricComponent) { - SymmetricComponent s = (SymmetricComponent)c; - if (s.getForeRadius() >= 0.0005) - return s.getForeRadius() * 2; - if (s.getAftRadius() >= 0.0005) - return s.getAftRadius() * 2; - } - } - return Rocket.DEFAULT_REFERENCE_LENGTH; - } - }, - - MAXIMUM { - @Override - public double getReferenceLength(Configuration config) { - double r = 0; - for (RocketComponent c: config) { - if (c instanceof SymmetricComponent) { - SymmetricComponent s = (SymmetricComponent)c; - r = Math.max(r, s.getForeRadius()); - r = Math.max(r, s.getAftRadius()); - } - } - r *= 2; - if (r < 0.001) - r = Rocket.DEFAULT_REFERENCE_LENGTH; - return r; - } - }, - - CUSTOM { - @Override - public double getReferenceLength(Configuration config) { - return config.getRocket().getCustomReferenceLength(); - } - }; - - public abstract double getReferenceLength(Configuration rocket); -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/RingComponent.java b/core/src/net/sf/openrocket/rocketcomponent/RingComponent.java deleted file mode 100644 index 9e2c16bc..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/RingComponent.java +++ /dev/null @@ -1,221 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -/** - * An inner component that consists of a hollow cylindrical component. This can be - * an inner tube, tube coupler, centering ring, bulkhead etc. - * - * The properties include the inner and outer radii, length and radial position. - * - * @author Sampo Niskanen - */ -public abstract class RingComponent extends StructuralComponent implements Coaxial { - - protected boolean outerRadiusAutomatic = false; - protected boolean innerRadiusAutomatic = false; - - - private double radialDirection = 0; - private double radialPosition = 0; - - private double shiftY = 0; - private double shiftZ = 0; - - - - @Override - public abstract double getOuterRadius(); - - @Override - public abstract void setOuterRadius(double r); - - @Override - public abstract double getInnerRadius(); - - @Override - public abstract void setInnerRadius(double r); - - @Override - public abstract double getThickness(); - - public abstract void setThickness(double thickness); - - - public final boolean isOuterRadiusAutomatic() { - return outerRadiusAutomatic; - } - - // Setter is protected, subclasses may make it public - protected void setOuterRadiusAutomatic(boolean auto) { - if (auto == outerRadiusAutomatic) - return; - outerRadiusAutomatic = auto; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public final boolean isInnerRadiusAutomatic() { - return innerRadiusAutomatic; - } - - // Setter is protected, subclasses may make it public - protected void setInnerRadiusAutomatic(boolean auto) { - if (auto == innerRadiusAutomatic) - return; - innerRadiusAutomatic = auto; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - public final void setLength(double length) { - double l = Math.max(length, 0); - if (this.length == l) - return; - - this.length = l; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - /** - * Return the radial direction of displacement of the component. Direction 0 - * is equivalent to the Y-direction. - * - * @return the radial direction. - */ - public double getRadialDirection() { - return radialDirection; - } - - /** - * Set the radial direction of displacement of the component. Direction 0 - * is equivalent to the Y-direction. - * - * @param dir the radial direction. - */ - public void setRadialDirection(double dir) { - dir = MathUtil.reduce180(dir); - if (radialDirection == dir) - return; - radialDirection = dir; - shiftY = radialPosition * Math.cos(radialDirection); - shiftZ = radialPosition * Math.sin(radialDirection); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - /** - * Return the radial position of the component. The position is the distance - * of the center of the component from the center of the parent component. - * - * @return the radial position. - */ - public double getRadialPosition() { - return radialPosition; - } - - /** - * Set the radial position of the component. The position is the distance - * of the center of the component from the center of the parent component. - * - * @param pos the radial position. - */ - public void setRadialPosition(double pos) { - pos = Math.max(pos, 0); - if (radialPosition == pos) - return; - radialPosition = pos; - shiftY = radialPosition * Math.cos(radialDirection); - shiftZ = radialPosition * Math.sin(radialDirection); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public double getRadialShiftY() { - return shiftY; - } - - public double getRadialShiftZ() { - return shiftZ; - } - - public void setRadialShift(double y, double z) { - radialPosition = Math.hypot(y, z); - radialDirection = Math.atan2(z, y); - - // Re-calculate to ensure consistency - shiftY = radialPosition * Math.cos(radialDirection); - shiftZ = radialPosition * Math.sin(radialDirection); - assert (MathUtil.equals(y, shiftY)); - assert (MathUtil.equals(z, shiftZ)); - - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - /** - * Return the number of times the component is multiplied. - */ - public int getClusterCount() { - if (this instanceof Clusterable) - return ((Clusterable) this).getClusterConfiguration().getClusterCount(); - return 1; - } - - - /** - * Shift the coordinates according to the radial position and direction. - */ - @Override - public Coordinate[] shiftCoordinates(Coordinate[] array) { - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(0, shiftY, shiftZ); - } - return array; - } - - - @Override - public Collection getComponentBounds() { - List bounds = new ArrayList(); - addBound(bounds, 0, getOuterRadius()); - addBound(bounds, length, getOuterRadius()); - return bounds; - } - - - - @Override - public Coordinate getComponentCG() { - return new Coordinate(length / 2, 0, 0, getComponentMass()); - } - - @Override - public double getComponentMass() { - return ringMass(getOuterRadius(), getInnerRadius(), getLength(), - getMaterial().getDensity()) * getClusterCount(); - } - - - @Override - public double getLongitudinalUnitInertia() { - return ringLongitudinalUnitInertia(getOuterRadius(), getInnerRadius(), getLength()); - } - - @Override - public double getRotationalUnitInertia() { - return ringRotationalUnitInertia(getOuterRadius(), getInnerRadius()); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Rocket.java b/core/src/net/sf/openrocket/rocketcomponent/Rocket.java deleted file mode 100644 index d493ca49..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Rocket.java +++ /dev/null @@ -1,834 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.Collection; -import java.util.Collections; -import java.util.EventListener; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.UUID; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.Chars; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.StateChangeListener; -import net.sf.openrocket.util.UniqueID; - - -/** - * Base for all rocket components. This is the "starting point" for all rocket trees. - * It provides the actual implementations of several methods defined in RocketComponent - * (eg. the rocket listener lists) and the methods defined in RocketComponent call these. - * It also defines some other methods that concern the whole rocket, and helper methods - * that keep information about the program state. - * - * @author Sampo Niskanen - */ - -public class Rocket extends RocketComponent { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - public static final double DEFAULT_REFERENCE_LENGTH = 0.01; - - - /** - * List of component change listeners. - */ - private List listenerList = new ArrayList(); - - /** - * When freezeList != null, events are not dispatched but stored in the list. - * When the structure is thawed, a single combined event will be fired. - */ - private List freezeList = null; - - - private int modID; - private int massModID; - private int aeroModID; - private int treeModID; - private int functionalModID; - - - private ReferenceType refType = ReferenceType.MAXIMUM; // Set in constructor - private double customReferenceLength = DEFAULT_REFERENCE_LENGTH; - - - // The default configuration used in dialogs - private final Configuration defaultConfiguration; - - - private String designer = ""; - private String revision = ""; - - - // Motor configuration list - private ArrayList motorConfigurationIDs = new ArrayList(); - private HashMap motorConfigurationNames = new HashMap(); - { - motorConfigurationIDs.add(null); - } - - - // Does the rocket have a perfect finish (a notable amount of laminar flow) - private boolean perfectFinish = false; - - - - ///////////// Constructor ///////////// - - public Rocket() { - super(RocketComponent.Position.AFTER); - modID = UniqueID.next(); - massModID = modID; - aeroModID = modID; - treeModID = modID; - functionalModID = modID; - defaultConfiguration = new Configuration(this); - } - - - - public String getDesigner() { - checkState(); - return designer; - } - - public void setDesigner(String s) { - if (s == null) - s = ""; - designer = s; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - public String getRevision() { - checkState(); - return revision; - } - - public void setRevision(String s) { - if (s == null) - s = ""; - revision = s; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - /** - * Return the number of stages in this rocket. - * - * @return the number of stages in this rocket. - */ - public int getStageCount() { - checkState(); - return this.getChildCount(); - } - - - /** - * Return the non-negative modification ID of this rocket. The ID is changed - * every time any change occurs in the rocket. This can be used to check - * whether it is necessary to void cached data in cases where listeners can not - * or should not be used. - *

- * Three other modification IDs are also available, {@link #getMassModID()}, - * {@link #getAerodynamicModID()} {@link #getTreeModID()}, which change every time - * a mass change, aerodynamic change, or tree change occur. Even though the values - * of the different modification ID's may be equal, they should be treated totally - * separate. - *

- * Note that undo events restore the modification IDs that were in use at the - * corresponding undo level. Subsequent modifications, however, produce modIDs - * distinct from those already used. - * - * @return a unique ID number for this modification state. - */ - public int getModID() { - return modID; - } - - /** - * Return the non-negative mass modification ID of this rocket. See - * {@link #getModID()} for details. - * - * @return a unique ID number for this mass-modification state. - */ - public int getMassModID() { - return massModID; - } - - /** - * Return the non-negative aerodynamic modification ID of this rocket. See - * {@link #getModID()} for details. - * - * @return a unique ID number for this aerodynamic-modification state. - */ - public int getAerodynamicModID() { - return aeroModID; - } - - /** - * Return the non-negative tree modification ID of this rocket. See - * {@link #getModID()} for details. - * - * @return a unique ID number for this tree-modification state. - */ - public int getTreeModID() { - return treeModID; - } - - /** - * Return the non-negative functional modificationID of this rocket. - * This changes every time a functional change occurs. - * - * @return a unique ID number for this functional modification state. - */ - public int getFunctionalModID() { - return functionalModID; - } - - - - - public ReferenceType getReferenceType() { - checkState(); - return refType; - } - - public void setReferenceType(ReferenceType type) { - if (refType == type) - return; - refType = type; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - public double getCustomReferenceLength() { - checkState(); - return customReferenceLength; - } - - public void setCustomReferenceLength(double length) { - if (MathUtil.equals(customReferenceLength, length)) - return; - - this.customReferenceLength = Math.max(length, 0.001); - - if (refType == ReferenceType.CUSTOM) { - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - } - - - - - - /** - * Set whether the rocket has a perfect finish. This will affect whether the - * boundary layer is assumed to be fully turbulent or not. - * - * @param perfectFinish whether the finish is perfect. - */ - public void setPerfectFinish(boolean perfectFinish) { - if (this.perfectFinish == perfectFinish) - return; - this.perfectFinish = perfectFinish; - fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE); - } - - - - /** - * Get whether the rocket has a perfect finish. - * - * @return the perfectFinish - */ - public boolean isPerfectFinish() { - return perfectFinish; - } - - - - - - /** - * Make a deep copy of the Rocket structure. This method is exposed as public to allow - * for undo/redo system functionality. - */ - @SuppressWarnings("unchecked") - @Override - public Rocket copyWithOriginalID() { - Rocket copy = (Rocket) super.copyWithOriginalID(); - copy.motorConfigurationIDs = this.motorConfigurationIDs.clone(); - copy.motorConfigurationNames = - (HashMap) this.motorConfigurationNames.clone(); - copy.resetListeners(); - - return copy; - } - - /** - * Load the rocket structure from the source. The method loads the fields of this - * Rocket object and copies the references to siblings from the source. - * The object source should not be used after this call, as it is in - * an illegal state! - *

- * This method is meant to be used in conjunction with undo/redo functionality, - * and therefore fires an UNDO_EVENT, masked with all applicable mass/aerodynamic/tree - * changes. - */ - @SuppressWarnings("unchecked") - public void loadFrom(Rocket r) { - - // Store list of components to invalidate after event has been fired - List toInvalidate = this.copyFrom(r); - - int type = ComponentChangeEvent.UNDO_CHANGE | ComponentChangeEvent.NONFUNCTIONAL_CHANGE; - if (this.massModID != r.massModID) - type |= ComponentChangeEvent.MASS_CHANGE; - if (this.aeroModID != r.aeroModID) - type |= ComponentChangeEvent.AERODYNAMIC_CHANGE; - // Loading a rocket is always a tree change since the component objects change - type |= ComponentChangeEvent.TREE_CHANGE; - - this.modID = r.modID; - this.massModID = r.massModID; - this.aeroModID = r.aeroModID; - this.treeModID = r.treeModID; - this.functionalModID = r.functionalModID; - this.refType = r.refType; - this.customReferenceLength = r.customReferenceLength; - - this.motorConfigurationIDs = r.motorConfigurationIDs.clone(); - this.motorConfigurationNames = - (HashMap) r.motorConfigurationNames.clone(); - this.perfectFinish = r.perfectFinish; - - String id = defaultConfiguration.getMotorConfigurationID(); - if (!this.motorConfigurationIDs.contains(id)) - defaultConfiguration.setMotorConfigurationID(null); - - this.checkComponentStructure(); - - fireComponentChangeEvent(type); - - // Invalidate obsolete components after event - for (RocketComponent c : toInvalidate) { - c.invalidate(); - } - } - - - - - /////// Implement the ComponentChangeListener lists - - /** - * Creates a new EventListenerList for this component. This is necessary when cloning - * the structure. - */ - public void resetListeners() { - // System.out.println("RESETTING LISTENER LIST of Rocket "+this); - listenerList = new ArrayList(); - } - - - public void printListeners() { - System.out.println("" + this + " has " + listenerList.size() + " listeners:"); - int i =0; - for( EventListener l : listenerList ) { - System.out.println(" " + (i) + ": " + l); - i++; - } - } - - @Override - public void addComponentChangeListener(ComponentChangeListener l) { - checkState(); - listenerList.add(l); - log.verbose("Added ComponentChangeListener " + l + ", current number of listeners is " + - listenerList.size()); - } - - @Override - public void removeComponentChangeListener(ComponentChangeListener l) { - listenerList.remove(l); - log.verbose("Removed ComponentChangeListener " + l + ", current number of listeners is " + - listenerList.size()); - } - - - @Override - public void addChangeListener(EventListener l) { - checkState(); - listenerList.add(l); - log.verbose("Added ChangeListener " + l + ", current number of listeners is " + - listenerList.size()); - } - - @Override - public void removeChangeListener(EventListener l) { - listenerList.remove(l); - log.verbose("Removed ChangeListener " + l + ", current number of listeners is " + - listenerList.size()); - } - - - @Override - protected void fireComponentChangeEvent(ComponentChangeEvent e) { - mutex.lock("fireComponentChangeEvent"); - try { - checkState(); - - // Update modification ID's only for normal (not undo/redo) events - if (!e.isUndoChange()) { - modID = UniqueID.next(); - if (e.isMassChange()) - massModID = modID; - if (e.isAerodynamicChange()) - aeroModID = modID; - if (e.isTreeChange()) - treeModID = modID; - if (e.getType() != ComponentChangeEvent.NONFUNCTIONAL_CHANGE) - functionalModID = modID; - } - - // Check whether frozen - if (freezeList != null) { - log.debug("Rocket is in frozen state, adding event " + e + " info freeze list"); - freezeList.add(e); - return; - } - - log.debug("Firing rocket change event " + e); - - // Notify all components first - Iterator iterator = this.iterator(true); - while (iterator.hasNext()) { - iterator.next().componentChanged(e); - } - - // Notify all listeners - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] list = listenerList.toArray( new EventListener[0] ); - for ( EventListener l : list ) { - if ( l instanceof ComponentChangeListener ) { - ((ComponentChangeListener) l ).componentChanged(e); - } else if ( l instanceof StateChangeListener ) { - ((StateChangeListener) l ).stateChanged(e); - } - } - } finally { - mutex.unlock("fireComponentChangeEvent"); - } - } - - - /** - * Freezes the rocket structure from firing any events. This may be performed to - * combine several actions on the structure into a single large action. - * thaw() must always be called afterwards. - * - * NOTE: Always use a try/finally to ensure thaw() is called: - *

-	 *     Rocket r = c.getRocket();
-	 *     try {
-	 *         r.freeze();
-	 *         // do stuff
-	 *     } finally {
-	 *         r.thaw();
-	 *     }
-	 * 
- * - * @see #thaw() - */ - public void freeze() { - checkState(); - if (freezeList == null) { - freezeList = new LinkedList(); - log.debug("Freezing Rocket"); - } else { - Application.getExceptionHandler().handleErrorCondition("Attempting to freeze Rocket when it is already frozen, " + - "freezeList=" + freezeList); - } - } - - /** - * Thaws a frozen rocket structure and fires a combination of the events fired during - * the freeze. The event type is a combination of those fired and the source is the - * last component to have been an event source. - * - * @see #freeze() - */ - public void thaw() { - checkState(); - if (freezeList == null) { - Application.getExceptionHandler().handleErrorCondition("Attempting to thaw Rocket when it is not frozen"); - return; - } - if (freezeList.size() == 0) { - log.warn("Thawing rocket with no changes made"); - freezeList = null; - return; - } - - log.debug("Thawing rocket, freezeList=" + freezeList); - - int type = 0; - Object c = null; - for (ComponentChangeEvent e : freezeList) { - type = type | e.getType(); - c = e.getSource(); - } - freezeList = null; - - fireComponentChangeEvent(new ComponentChangeEvent((RocketComponent) c, type)); - } - - - - - //////// Motor configurations //////// - - - /** - * Return the default configuration. This should be used in the user interface - * to ensure a consistent rocket configuration between dialogs. It should NOT - * be used in simulations not relating to the UI. - * - * @return the default {@link Configuration}. - */ - public Configuration getDefaultConfiguration() { - checkState(); - return defaultConfiguration; - } - - - /** - * Return an array of the motor configuration IDs. This array is guaranteed - * to contain the null ID as the first element. - * - * @return an array of the motor configuration IDs. - */ - public String[] getMotorConfigurationIDs() { - checkState(); - return motorConfigurationIDs.toArray(new String[0]); - } - - /** - * Add a new motor configuration ID to the motor configurations. The new ID - * is returned. - * - * @return the new motor configuration ID. - */ - public String newMotorConfigurationID() { - checkState(); - String id = UUID.randomUUID().toString(); - motorConfigurationIDs.add(id); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - return id; - } - - /** - * Add a specified motor configuration ID to the motor configurations. - * - * @param id the motor configuration ID. - * @return true if successful, false if the ID was already used. - */ - public boolean addMotorConfigurationID(String id) { - checkState(); - if (id == null || motorConfigurationIDs.contains(id)) - return false; - motorConfigurationIDs.add(id); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - return true; - } - - /** - * Remove a motor configuration ID from the configuration IDs. The null - * ID cannot be removed, and an attempt to remove it will be silently ignored. - * - * @param id the motor configuration ID to remove - */ - public void removeMotorConfigurationID(String id) { - checkState(); - if (id == null) - return; - motorConfigurationIDs.remove(id); - fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE); - } - - - /** - * Check whether id is a valid motor configuration ID. - * - * @param id the configuration ID. - * @return whether a motor configuration with that ID exists. - */ - public boolean isMotorConfigurationID(String id) { - checkState(); - return motorConfigurationIDs.contains(id); - } - - - - /** - * Check whether the given motor configuration ID has motors defined for it. - * - * @param id the motor configuration ID (may be invalid). - * @return whether any motors are defined for it. - */ - public boolean hasMotors(String id) { - checkState(); - if (id == null) - return false; - - Iterator iterator = this.iterator(); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - - if (c instanceof MotorMount) { - MotorMount mount = (MotorMount) c; - if (!mount.isMotorMount()) - continue; - if (mount.getMotor(id) != null) { - return true; - } - } - } - return false; - } - - - /** - * Return the user-set name of the motor configuration. If no name has been set, - * returns an empty string (not null). - * - * @param id the motor configuration id - * @return the configuration name - */ - public String getMotorConfigurationName(String id) { - checkState(); - if (!isMotorConfigurationID(id)) - return ""; - String s = motorConfigurationNames.get(id); - if (s == null) - return ""; - return s; - } - - - /** - * Set the name of the motor configuration. A name can be unset by passing - * null or an empty string. - * - * @param id the motor configuration id - * @param name the name for the motor configuration - */ - public void setMotorConfigurationName(String id, String name) { - checkState(); - motorConfigurationNames.put(id, name); - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - /** - * Return either the motor configuration name (if set) or its description. - * - * @param id the motor configuration ID. - * @return a textual representation of the configuration - */ - public String getMotorConfigurationNameOrDescription(String id) { - checkState(); - String name; - - name = getMotorConfigurationName(id); - if (name != null && !name.equals("")) - return name; - - return getMotorConfigurationDescription(id); - } - - /** - * Return a description for the motor configuration, generated from the motor - * designations of the components. - * - * @param id the motor configuration ID. - * @return a textual representation of the configuration - */ - @SuppressWarnings("null") - public String getMotorConfigurationDescription(String id) { - checkState(); - String name; - int motorCount = 0; - - // Generate the description - - // First iterate over each stage and store the designations of each motor - List> list = new ArrayList>(); - List currentList = null; - - Iterator iterator = this.iterator(); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - - if (c instanceof Stage) { - - currentList = new ArrayList(); - list.add(currentList); - - } else if (c instanceof MotorMount) { - - MotorMount mount = (MotorMount) c; - Motor motor = mount.getMotor(id); - - if (mount.isMotorMount() && motor != null) { - String designation = motor.getDesignation(mount.getMotorDelay(id)); - - for (int i = 0; i < mount.getMotorCount(); i++) { - currentList.add(designation); - motorCount++; - } - } - - } - } - - if (motorCount == 0) { - //// [No motors] - return trans.get("Rocket.motorCount.Nomotor"); - } - - // Change multiple occurrences of a motor to n x motor - List stages = new ArrayList(); - - for (List stage : list) { - String stageName = ""; - String previous = null; - int count = 0; - - Collections.sort(stage); - for (String current : stage) { - if (current.equals(previous)) { - - count++; - - } else { - - if (previous != null) { - String s = ""; - if (count > 1) { - s = "" + count + Chars.TIMES + previous; - } else { - s = previous; - } - - if (stageName.equals("")) - stageName = s; - else - stageName = stageName + "," + s; - } - - previous = current; - count = 1; - - } - } - if (previous != null) { - String s = ""; - if (count > 1) { - s = "" + count + Chars.TIMES + previous; - } else { - s = previous; - } - - if (stageName.equals("")) - stageName = s; - else - stageName = stageName + "," + s; - } - - stages.add(stageName); - } - - name = "["; - for (int i = 0; i < stages.size(); i++) { - String s = stages.get(i); - if (s.equals("")) - s = "None"; - if (i == 0) - name = name + s; - else - name = name + "; " + s; - } - name += "]"; - return name; - } - - - - //////// Obligatory component information - - - @Override - public String getComponentName() { - //// Rocket - return trans.get("Rocket.compname.Rocket"); - } - - @Override - public Coordinate getComponentCG() { - return new Coordinate(0, 0, 0, 0); - } - - @Override - public double getComponentMass() { - return 0; - } - - @Override - public double getLongitudinalUnitInertia() { - return 0; - } - - @Override - public double getRotationalUnitInertia() { - return 0; - } - - @Override - public Collection getComponentBounds() { - return Collections.emptyList(); - } - - @Override - public boolean isAerodynamic() { - return false; - } - - @Override - public boolean isMassive() { - return false; - } - - @Override - public boolean allowsChildren() { - return true; - } - - /** - * Allows only Stage components to be added to the type Rocket. - */ - @Override - public boolean isCompatible(Class type) { - return (Stage.class.isAssignableFrom(type)); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java b/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java deleted file mode 100644 index 9000a540..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java +++ /dev/null @@ -1,1937 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.Collection; -import java.util.EventListener; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.Color; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Invalidator; -import net.sf.openrocket.util.LineStyle; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.SafetyMutex; -import net.sf.openrocket.util.SimpleStack; -import net.sf.openrocket.util.UniqueID; - - -public abstract class RocketComponent implements ChangeSource, Cloneable, Iterable { - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - /* - * Text is suitable to the form - * Position relative to: - */ - public enum Position { - /** Position relative to the top of the parent component. */ - //// Top of the parent component - TOP(trans.get("RocketComponent.Position.TOP")), - /** Position relative to the middle of the parent component. */ - //// Middle of the parent component - MIDDLE(trans.get("RocketComponent.Position.MIDDLE")), - /** Position relative to the bottom of the parent component. */ - //// Bottom of the parent component - BOTTOM(trans.get("RocketComponent.Position.BOTTOM")), - /** Position after the parent component (for body components). */ - //// After the parent component - AFTER(trans.get("RocketComponent.Position.AFTER")), - /** Specify an absolute X-coordinate position. */ - //// Tip of the nose cone - ABSOLUTE(trans.get("RocketComponent.Position.ABSOLUTE")); - - private String title; - - Position(String title) { - this.title = title; - } - - @Override - public String toString() { - return title; - } - } - - /** - * A safety mutex that can be used to prevent concurrent access to this component. - */ - protected SafetyMutex mutex = SafetyMutex.newInstance(); - - //////// Parent/child trees - /** - * Parent component of the current component, or null if none exists. - */ - private RocketComponent parent = null; - - /** - * List of child components of this component. - */ - private ArrayList<RocketComponent> children = new ArrayList<RocketComponent>(); - - - //////// Parameters common to all components: - - /** - * Characteristic length of the component. This is used in calculating the coordinate - * transformations and positions of other components in reference to this component. - * This may and should be used as the "true" length of the component, where applicable. - * By default it is zero, i.e. no translation. - */ - protected double length = 0; - - /** - * Positioning of this component relative to the parent component. - */ - protected Position relativePosition; - - /** - * Offset of the position of this component relative to the normal position given by - * relativePosition. By default zero, i.e. no position change. - */ - protected double position = 0; - - - // Color of the component, null means to use the default color - private Color color = null; - private LineStyle lineStyle = null; - - - // Override mass/CG - private double overrideMass = 0; - private boolean massOverriden = false; - private double overrideCGX = 0; - private boolean cgOverriden = false; - - private boolean overrideSubcomponents = false; - - - // User-given name of the component - private String name = null; - - // User-specified comment - private String comment = ""; - - // Unique ID of the component - private String id = null; - - // Preset component this component is based upon - private ComponentPreset presetComponent = null; - - - /** - * Used to invalidate the component after calling {@link #copyFrom(RocketComponent)}. - */ - private Invalidator invalidator = new Invalidator(this); - - - //// NOTE !!! All fields must be copied in the method copyFrom()! //// - - - - /** - * Default constructor. Sets the name of the component to the component's static name - * and the relative position of the component. - */ - public RocketComponent(Position relativePosition) { - // These must not fire any events, due to Rocket undo system initialization - this.name = getComponentName(); - this.relativePosition = relativePosition; - newID(); - } - - //////////// Methods that must be implemented //////////// - - - /** - * Static component name. The name may not vary of the parameters, it must be static. - */ - public abstract String getComponentName(); // Static component type name - - /** - * Return the component mass (regardless of mass overriding). - */ - public abstract double getComponentMass(); // Mass of non-overridden component - - /** - * Return the component CG and mass (regardless of CG or mass overriding). - */ - public abstract Coordinate getComponentCG(); // CG of non-overridden component - - - /** - * Return the longitudinal (around the y- or z-axis) unitary moment of inertia. - * The unitary moment of inertia is the moment of inertia with the assumption that - * the mass of the component is one kilogram. The inertia is measured in - * respect to the non-overridden CG. - * - * @return the longitudinal unitary moment of inertia of this component. - */ - public abstract double getLongitudinalUnitInertia(); - - - /** - * Return the rotational (around the x-axis) unitary moment of inertia. - * The unitary moment of inertia is the moment of inertia with the assumption that - * the mass of the component is one kilogram. The inertia is measured in - * respect to the non-overridden CG. - * - * @return the rotational unitary moment of inertia of this component. - */ - public abstract double getRotationalUnitInertia(); - - - /** - * Test whether this component allows any children components. This method must - * return true if and only if {@link #isCompatible(Class)} returns true for any - * rocket component class. - * - * @return <code>true</code> if children can be attached to this component, <code>false</code> otherwise. - */ - public abstract boolean allowsChildren(); - - /** - * Test whether the given component type can be added to this component. This type safety - * is enforced by the <code>addChild()</code> methods. The return value of this method - * may change to reflect the current state of this component (e.g. two components of some - * type cannot be placed as children). - * - * @param type The RocketComponent class type to add. - * @return Whether such a component can be added. - */ - public abstract boolean isCompatible(Class<? extends RocketComponent> type); - - - /* Non-abstract helper method */ - /** - * Test whether the given component can be added to this component. This is equivalent - * to calling <code>isCompatible(c.getClass())</code>. - * - * @param c Component to test. - * @return Whether the component can be added. - * @see #isCompatible(Class) - */ - public final boolean isCompatible(RocketComponent c) { - mutex.verify(); - return isCompatible(c.getClass()); - } - - - - /** - * Return a collection of bounding coordinates. The coordinates must be such that - * the component is fully enclosed in their convex hull. - * - * @return a collection of coordinates that bound the component. - */ - public abstract Collection<Coordinate> getComponentBounds(); - - /** - * Return true if the component may have an aerodynamic effect on the rocket. - */ - public abstract boolean isAerodynamic(); - - /** - * Return true if the component may have an effect on the rocket's mass. - */ - public abstract boolean isMassive(); - - - - - - //////////// Methods that may be overridden //////////// - - - /** - * Shift the coordinates in the array corresponding to radial movement. A component - * that has a radial position must shift the coordinates in this array suitably. - * If the component is clustered, then a new array must be returned with a - * coordinate for each cluster. - * <p> - * The default implementation simply returns the array, and thus produces no shift. - * - * @param c an array of coordinates to shift. - * @return an array of shifted coordinates. The method may modify the contents - * of the passed array and return the array itself. - */ - public Coordinate[] shiftCoordinates(Coordinate[] c) { - checkState(); - return c; - } - - - /** - * Called when any component in the tree fires a ComponentChangeEvent. This is by - * default a no-op, but subclasses may override this method to e.g. invalidate - * cached data. The overriding method *must* call - * <code>super.componentChanged(e)</code> at some point. - * - * @param e The event fired - */ - protected void componentChanged(ComponentChangeEvent e) { - // No-op - checkState(); - } - - - - - /** - * Return the user-provided name of the component, or the component base - * name if the user-provided name is empty. This can be used in the UI. - * - * @return A string describing the component. - */ - @Override - public final String toString() { - mutex.verify(); - if (name.length() == 0) - return getComponentName(); - else - return name; - } - - - /** - * Create a string describing the basic component structure from this component downwards. - * @return a string containing the rocket structure - */ - public final String toDebugString() { - mutex.lock("toDebugString"); - try { - StringBuilder sb = new StringBuilder(); - toDebugString(sb); - return sb.toString(); - } finally { - mutex.unlock("toDebugString"); - } - } - - private void toDebugString(StringBuilder sb) { - sb.append(this.getClass().getSimpleName()).append('@').append(System.identityHashCode(this)); - sb.append("[\"").append(this.getName()).append('"'); - for (RocketComponent c : this.children) { - sb.append("; "); - c.toDebugString(sb); - } - sb.append(']'); - } - - - /** - * Make a deep copy of the rocket component tree structure from this component - * downwards for copying purposes. Each component in the copy will be assigned - * a new component ID, making it a safe copy. This method does not fire any events. - * - * @return A deep copy of the structure. - */ - public final RocketComponent copy() { - RocketComponent clone = copyWithOriginalID(); - - Iterator<RocketComponent> iterator = clone.iterator(true); - while (iterator.hasNext()) { - iterator.next().newID(); - } - return clone; - } - - - - /** - * Make a deep copy of the rocket component tree structure from this component - * downwards while maintaining the component ID's. The purpose of this method is - * to allow copies to be created with the original ID's for the purpose of the - * undo/redo mechanism. This method should not be used for other purposes, - * such as copy/paste. This method does not fire any events. - * <p> - * This method must be overridden by any component that refers to mutable objects, - * or if some fields should not be copied. This should be performed by - * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying - * the appropriate fields. - * <p> - * This is not performed as serializing/deserializing for performance reasons. - * - * @return A deep copy of the structure. - */ - protected RocketComponent copyWithOriginalID() { - mutex.lock("copyWithOriginalID"); - try { - checkState(); - RocketComponent clone; - try { - clone = (RocketComponent) this.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException encountered, report a bug!", e); - } - - // Reset the mutex - clone.mutex = SafetyMutex.newInstance(); - - // Reset all parent/child information - clone.parent = null; - clone.children = new ArrayList<RocketComponent>(); - - // Add copied children to the structure without firing events. - for (RocketComponent child : this.children) { - RocketComponent childCopy = child.copyWithOriginalID(); - // Don't use add method since it fires events - clone.children.add(childCopy); - childCopy.parent = clone; - } - - this.checkComponentStructure(); - clone.checkComponentStructure(); - - return clone; - } finally { - mutex.unlock("copyWithOriginalID"); - } - } - - - ////////////// Methods that may not be overridden //////////// - - - - ////////// Common parameter setting/getting ////////// - - /** - * Return the color of the object to use in 2D figures, or <code>null</code> - * to use the default color. - */ - public final Color getColor() { - mutex.verify(); - return color; - } - - /** - * Set the color of the object to use in 2D figures. - */ - public final void setColor(Color c) { - if ((color == null && c == null) || - (color != null && color.equals(c))) - return; - - checkState(); - this.color = c; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - public final LineStyle getLineStyle() { - mutex.verify(); - return lineStyle; - } - - public final void setLineStyle(LineStyle style) { - if (this.lineStyle == style) - return; - checkState(); - this.lineStyle = style; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - - - /** - * Get the current override mass. The mass is not necessarily in use - * at the moment. - * - * @return the override mass - */ - public final double getOverrideMass() { - mutex.verify(); - return overrideMass; - } - - /** - * Set the current override mass. The mass is not set to use by this - * method. - * - * @param m the override mass - */ - public final void setOverrideMass(double m) { - if (MathUtil.equals(m, overrideMass)) - return; - checkState(); - overrideMass = Math.max(m, 0); - if (massOverriden) - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - /** - * Return whether mass override is active for this component. This does NOT - * take into account whether a parent component is overriding the mass. - * - * @return whether the mass is overridden - */ - public final boolean isMassOverridden() { - mutex.verify(); - return massOverriden; - } - - /** - * Set whether the mass is currently overridden. - * - * @param o whether the mass is overridden - */ - public final void setMassOverridden(boolean o) { - if (massOverriden == o) { - return; - } - checkState(); - massOverriden = o; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - - /** - * Return the current override CG. The CG is not necessarily overridden. - * - * @return the override CG - */ - public final Coordinate getOverrideCG() { - mutex.verify(); - return getComponentCG().setX(overrideCGX); - } - - /** - * Return the x-coordinate of the current override CG. - * - * @return the x-coordinate of the override CG. - */ - public final double getOverrideCGX() { - mutex.verify(); - return overrideCGX; - } - - /** - * Set the current override CG to (x,0,0). - * - * @param x the x-coordinate of the override CG to set. - */ - public final void setOverrideCGX(double x) { - if (MathUtil.equals(overrideCGX, x)) - return; - checkState(); - this.overrideCGX = x; - if (isCGOverridden()) - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - else - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - /** - * Return whether the CG is currently overridden. - * - * @return whether the CG is overridden - */ - public final boolean isCGOverridden() { - mutex.verify(); - return cgOverriden; - } - - /** - * Set whether the CG is currently overridden. - * - * @param o whether the CG is overridden - */ - public final void setCGOverridden(boolean o) { - if (cgOverriden == o) { - return; - } - checkState(); - cgOverriden = o; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - /** - * Return whether the mass and/or CG override overrides all subcomponent values - * as well. The default implementation is a normal getter/setter implementation, - * however, subclasses are allowed to override this behavior if some subclass - * always or never overrides subcomponents. In this case the subclass should - * also override {@link #isOverrideSubcomponentsEnabled()} to return - * <code>false</code>. - * - * @return whether the current mass and/or CG override overrides subcomponents as well. - */ - public boolean getOverrideSubcomponents() { - mutex.verify(); - return overrideSubcomponents; - } - - - /** - * Set whether the mass and/or CG override overrides all subcomponent values - * as well. See {@link #getOverrideSubcomponents()} for details. - * - * @param override whether the mass and/or CG override overrides all subcomponent. - */ - public void setOverrideSubcomponents(boolean override) { - if (overrideSubcomponents == override) { - return; - } - checkState(); - overrideSubcomponents = override; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - /** - * Return whether the option to override all subcomponents is enabled or not. - * The default implementation returns <code>false</code> if neither mass nor - * CG is overridden, <code>true</code> otherwise. - * <p> - * This method may be overridden if the setting of overriding subcomponents - * cannot be set. - * - * @return whether the option to override subcomponents is currently enabled. - */ - public boolean isOverrideSubcomponentsEnabled() { - mutex.verify(); - return isCGOverridden() || isMassOverridden(); - } - - - - - /** - * Get the user-defined name of the component. - */ - public final String getName() { - mutex.verify(); - return name; - } - - /** - * Set the user-defined name of the component. If name==null, sets the name to - * the default name, currently the component name. - */ - public final void setName(String name) { - if (this.name.equals(name)) { - return; - } - checkState(); - if (name == null || name.matches("^\\s*$")) - this.name = getComponentName(); - else - this.name = name; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - /** - * Return the comment of the component. The component may contain multiple lines - * using \n as a newline separator. - * - * @return the comment of the component. - */ - public final String getComment() { - mutex.verify(); - return comment; - } - - /** - * Set the comment of the component. - * - * @param comment the comment of the component. - */ - public final void setComment(String comment) { - if (this.comment.equals(comment)) - return; - checkState(); - if (comment == null) - this.comment = ""; - else - this.comment = comment; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - - /** - * Return the preset component that this component is based upon. - * - * @return the preset component, or <code>null</code> if this is not based on a preset. - */ - public final ComponentPreset getPresetComponent() { - return presetComponent; - } - - /** - * Return the most compatible preset type for this component. - * This method should be overridden by components which have presets - * - * @return the most compatible ComponentPreset.Type or <code>null</code> if no presets are compatible. - */ - public ComponentPreset.Type getPresetType() { - return null; - } - - /** - * Set the preset component this component is based upon and load all of the - * preset values. - * - * @param preset the preset component to load, or <code>null</code> to clear the preset. - */ - public final void loadPreset(ComponentPreset preset) { - if (presetComponent == preset) { - return; - } - - if (preset == null) { - clearPreset(); - return; - } - - // TODO - do we need to this compatibility check? - /* - if (preset.getComponentClass() != this.getClass()) { - throw new IllegalArgumentException("Attempting to load preset of type " + preset.getComponentClass() - + " into component of type " + this.getClass()); - } - */ - - RocketComponent root = getRoot(); - final Rocket rocket; - if (root instanceof Rocket) { - rocket = (Rocket) root; - } else { - rocket = null; - } - - try { - if (rocket != null) { - rocket.freeze(); - } - - loadFromPreset(preset); - - this.presetComponent = preset; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - - } finally { - if (rocket != null) { - rocket.thaw(); - } - } - } - - - /** - * Load component properties from the specified preset. The preset is guaranteed - * to be of the correct type. - * <p> - * This method should fire the appropriate events related to the changes. The rocket - * is frozen by the caller, so the events will be automatically combined. - * <p> - * This method must FIRST perform the preset loading and THEN call super.loadFromPreset(). - * This is because mass setting requires the dimensions to be set beforehand. - * - * @param preset the preset to load from - */ - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.LENGTH) ) { - this.length = preset.get(ComponentPreset.LENGTH); - } - } - - - /** - * Clear the current component preset. This does not affect the component properties - * otherwise. - */ - public final void clearPreset() { - if (presetComponent == null) - return; - presetComponent = null; - fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); - } - - - - /** - * Returns the unique ID of the component. - * - * @return the ID of the component. - */ - public final String getID() { - return id; - } - - /** - * Generate a new ID for this component. - */ - private final void newID() { - mutex.verify(); - this.id = UniqueID.uuid(); - } - - - - - /** - * Get the characteristic length of the component, for example the length of a body tube - * of the length of the root chord of a fin. This is used in positioning the component - * relative to its parent. - * - * If the length of a component is settable, the class must define the setter method - * itself. - */ - public final double getLength() { - mutex.verify(); - return length; - } - - /** - * Get the positioning of the component relative to its parent component. - * This is one of the enums of {@link Position}. A setter method is not provided, - * but can be provided by a subclass. - */ - public final Position getRelativePosition() { - mutex.verify(); - return relativePosition; - } - - - /** - * Set the positioning of the component relative to its parent component. - * The actual position of the component is maintained to the best ability. - * <p> - * The default implementation is of protected visibility, since many components - * do not support setting the relative position. A component that does support - * it should override this with a public method that simply calls this - * supermethod AND fire a suitable ComponentChangeEvent. - * - * @param position the relative positioning. - */ - protected void setRelativePosition(RocketComponent.Position position) { - if (this.relativePosition == position) - return; - checkState(); - - // Update position so as not to move the component - if (this.parent != null) { - double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x; - - switch (position) { - case ABSOLUTE: - this.position = this.toAbsolute(Coordinate.NUL)[0].x; - break; - - case TOP: - this.position = thisPos; - break; - - case MIDDLE: - this.position = thisPos - (this.parent.length - this.length) / 2; - break; - - case BOTTOM: - this.position = thisPos - (this.parent.length - this.length); - break; - - default: - throw new BugException("Unknown position type: " + position); - } - } - - this.relativePosition = position; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - /** - * Determine position relative to given position argument. Note: This is a side-effect free method. No state - * is modified. - * - * @param thePosition the relative position to be used as the basis for the computation - * @param relativeTo the position is computed relative the the given component - * - * @return double position of the component relative to the parent, with respect to <code>position</code> - */ - public double asPositionValue(Position thePosition, RocketComponent relativeTo) { - double result = this.position; - if (relativeTo != null) { - double thisPos = this.toRelative(Coordinate.NUL, relativeTo)[0].x; - - switch (thePosition) { - case ABSOLUTE: - result = this.toAbsolute(Coordinate.NUL)[0].x; - break; - case TOP: - result = thisPos; - break; - case MIDDLE: - result = thisPos - (relativeTo.length - this.length) / 2; - break; - case BOTTOM: - result = thisPos - (relativeTo.length - this.length); - break; - default: - throw new BugException("Unknown position type: " + thePosition); - } - } - return result; - } - - /** - * Get the position value of the component. The exact meaning of the value is - * dependent on the current relative positioning. - * - * @return the positional value. - */ - public final double getPositionValue() { - mutex.verify(); - return position; - } - - - /** - * Set the position value of the component. The exact meaning of the value - * depends on the current relative positioning. - * <p> - * The default implementation is of protected visibility, since many components - * do not support setting the relative position. A component that does support - * it should override this with a public method that simply calls this - * supermethod AND fire a suitable ComponentChangeEvent. - * - * @param value the position value of the component. - */ - public void setPositionValue(double value) { - if (MathUtil.equals(this.position, value)) - return; - checkState(); - this.position = value; - } - - - - /////////// Coordinate changes /////////// - - /** - * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null). - */ - public Coordinate[] toAbsolute(Coordinate c) { - checkState(); - return toRelative(c, null); - } - - - /** - * Return coordinate <code>c</code> described in the coordinate system of - * <code>dest</code>. If <code>dest</code> is <code>null</code> returns - * absolute coordinates. - * <p> - * This method returns an array of coordinates, each of which represents a - * position of the coordinate in clustered cases. The array is guaranteed - * to contain at least one element. - * <p> - * The current implementation does not support rotating components. - * - * @param c Coordinate in the component's coordinate system. - * @param dest Destination component coordinate system. - * @return an array of coordinates describing <code>c</code> in coordinates - * relative to <code>dest</code>. - */ - public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) { - checkState(); - mutex.lock("toRelative"); - try { - double absoluteX = Double.NaN; - RocketComponent search = dest; - Coordinate[] array = new Coordinate[1]; - array[0] = c; - - RocketComponent component = this; - while ((component != search) && (component.parent != null)) { - - array = component.shiftCoordinates(array); - - switch (component.relativePosition) { - case TOP: - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(component.position, 0, 0); - } - break; - - case MIDDLE: - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(component.position + - (component.parent.length - component.length) / 2, 0, 0); - } - break; - - case BOTTOM: - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(component.position + - (component.parent.length - component.length), 0, 0); - } - break; - - case AFTER: - // Add length of all previous brother-components with POSITION_RELATIVE_AFTER - int index = component.parent.children.indexOf(component); - assert (index >= 0); - for (index--; index >= 0; index--) { - RocketComponent comp = component.parent.children.get(index); - double componentLength = comp.getTotalLength(); - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(componentLength, 0, 0); - } - } - for (int i = 0; i < array.length; i++) { - array[i] = array[i].add(component.position + component.parent.length, 0, 0); - } - break; - - case ABSOLUTE: - search = null; // Requires back-search if dest!=null - if (Double.isNaN(absoluteX)) { - absoluteX = component.position; - } - break; - - default: - throw new BugException("Unknown relative positioning type of component" + - component + ": " + component.relativePosition); - } - - component = component.parent; // parent != null - } - - if (!Double.isNaN(absoluteX)) { - for (int i = 0; i < array.length; i++) { - array[i] = array[i].setX(absoluteX + c.x); - } - } - - // Check whether destination has been found or whether to backtrack - // TODO: LOW: Backtracking into clustered components uses only one component - if ((dest != null) && (component != dest)) { - Coordinate[] origin = dest.toAbsolute(Coordinate.NUL); - for (int i = 0; i < array.length; i++) { - array[i] = array[i].sub(origin[0]); - } - } - - return array; - } finally { - mutex.unlock("toRelative"); - } - } - - - /** - * Recursively sum the lengths of all subcomponents that have position - * Position.AFTER. - * - * @return Sum of the lengths. - */ - private final double getTotalLength() { - checkState(); - this.checkComponentStructure(); - mutex.lock("getTotalLength"); - try { - double l = 0; - if (relativePosition == Position.AFTER) - l = length; - for (int i = 0; i < children.size(); i++) - l += children.get(i).getTotalLength(); - return l; - } finally { - mutex.unlock("getTotalLength"); - } - } - - - - /////////// Total mass and CG calculation //////////// - - /** - * Return the (possibly overridden) mass of component. - * - * @return The mass of the component or the given override mass. - */ - public final double getMass() { - mutex.verify(); - if (massOverriden) - return overrideMass; - return getComponentMass(); - } - - /** - * Return the (possibly overridden) center of gravity and mass. - * - * Returns the CG with the weight of the coordinate set to the weight of the component. - * Both CG and mass may be separately overridden. - * - * @return The CG of the component or the given override CG. - */ - public final Coordinate getCG() { - checkState(); - if (cgOverriden) - return getOverrideCG().setWeight(getMass()); - - if (massOverriden) - return getComponentCG().setWeight(getMass()); - - return getComponentCG(); - } - - - /** - * Return the longitudinal (around the y- or z-axis) moment of inertia of this component. - * The moment of inertia is scaled in reference to the (possibly overridden) mass - * and is relative to the non-overridden CG. - * - * @return the longitudinal moment of inertia of this component. - */ - public final double getLongitudinalInertia() { - checkState(); - return getLongitudinalUnitInertia() * getMass(); - } - - /** - * Return the rotational (around the y- or z-axis) moment of inertia of this component. - * The moment of inertia is scaled in reference to the (possibly overridden) mass - * and is relative to the non-overridden CG. - * - * @return the rotational moment of inertia of this component. - */ - public final double getRotationalInertia() { - checkState(); - return getRotationalUnitInertia() * getMass(); - } - - - - /////////// Children handling /////////// - - - /** - * Adds a child to the rocket component tree. The component is added to the end - * of the component's child list. This is a helper method that calls - * {@link #addChild(RocketComponent,int)}. - * - * @param component The component to add. - * @throws IllegalArgumentException if the component is already part of some - * component tree. - * @see #addChild(RocketComponent,int) - */ - public final void addChild(RocketComponent component) { - checkState(); - addChild(component, children.size()); - } - - - /** - * Adds a child to the rocket component tree. The component is added to - * the given position of the component's child list. - * <p> - * This method may be overridden to enforce more strict component addition rules. - * The tests should be performed first and then this method called. - * - * @param component The component to add. - * @param index Position to add component to. - * @throws IllegalArgumentException If the component is already part of - * some component tree. - */ - public void addChild(RocketComponent component, int index) { - checkState(); - - if (component.parent != null) { - throw new IllegalArgumentException("component " + component.getComponentName() + - " is already in a tree"); - } - - // Ensure that the no loops are created in component tree [A -> X -> Y -> B, B.addChild(A)] - if (this.getRoot().equals(component)) { - throw new IllegalStateException("Component " + component.getComponentName() + - " is a parent of " + this.getComponentName() + ", attempting to create cycle in tree."); - } - - if (!isCompatible(component)) { - throw new IllegalStateException("Component " + component.getComponentName() + - " not currently compatible with component " + getComponentName()); - } - - children.add(index, component); - component.parent = this; - - this.checkComponentStructure(); - component.checkComponentStructure(); - - fireAddRemoveEvent(component); - } - - /** - * Removes a child from the rocket component tree. - * - * @param n remove the n'th child. - * @throws IndexOutOfBoundsException if n is out of bounds - */ - public final void removeChild(int n) { - checkState(); - RocketComponent component = children.remove(n); - component.parent = null; - - this.checkComponentStructure(); - component.checkComponentStructure(); - - fireAddRemoveEvent(component); - } - - /** - * Removes a child from the rocket component tree. Does nothing if the component - * is not present as a child. - * - * @param component the component to remove - * @return whether the component was a child - */ - public final boolean removeChild(RocketComponent component) { - checkState(); - - component.checkComponentStructure(); - - if (children.remove(component)) { - component.parent = null; - - this.checkComponentStructure(); - component.checkComponentStructure(); - - fireAddRemoveEvent(component); - return true; - } - return false; - } - - - - - /** - * Move a child to another position. - * - * @param component the component to move - * @param index the component's new position - * @throws IllegalArgumentException If an illegal placement was attempted. - */ - public final void moveChild(RocketComponent component, int index) { - checkState(); - if (children.remove(component)) { - children.add(index, component); - - this.checkComponentStructure(); - component.checkComponentStructure(); - - fireAddRemoveEvent(component); - } - } - - - /** - * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the - * type of component removed. - */ - private void fireAddRemoveEvent(RocketComponent component) { - Iterator<RocketComponent> iter = component.iterator(true); - int type = ComponentChangeEvent.TREE_CHANGE; - while (iter.hasNext()) { - RocketComponent c = iter.next(); - if (c.isAerodynamic()) - type |= ComponentChangeEvent.AERODYNAMIC_CHANGE; - if (c.isMassive()) - type |= ComponentChangeEvent.MASS_CHANGE; - } - - fireComponentChangeEvent(type); - } - - - public final int getChildCount() { - checkState(); - this.checkComponentStructure(); - return children.size(); - } - - public final RocketComponent getChild(int n) { - checkState(); - this.checkComponentStructure(); - return children.get(n); - } - - public final List<RocketComponent> getChildren() { - checkState(); - this.checkComponentStructure(); - return children.clone(); - } - - - /** - * Returns the position of the child in this components child list, or -1 if the - * component is not a child of this component. - * - * @param child The child to search for. - * @return Position in the list or -1 if not found. - */ - public final int getChildPosition(RocketComponent child) { - checkState(); - this.checkComponentStructure(); - return children.indexOf(child); - } - - /** - * Get the parent component of this component. Returns <code>null</code> if the component - * has no parent. - * - * @return The parent of this component or <code>null</code>. - */ - public final RocketComponent getParent() { - checkState(); - return parent; - } - - /** - * Get the root component of the component tree. - * - * @return The root component of the component tree. - */ - public final RocketComponent getRoot() { - checkState(); - RocketComponent gp = this; - while (gp.parent != null) - gp = gp.parent; - return gp; - } - - /** - * Returns the root Rocket component of this component tree. Throws an - * IllegalStateException if the root component is not a Rocket. - * - * @return The root Rocket component of the component tree. - * @throws IllegalStateException If the root component is not a Rocket. - */ - public final Rocket getRocket() { - checkState(); - RocketComponent r = getRoot(); - if (r instanceof Rocket) - return (Rocket) r; - throw new IllegalStateException("getRocket() called with root component " - + r.getComponentName()); - } - - - /** - * Return the Stage component that this component belongs to. Throws an - * IllegalStateException if a Stage is not in the parentage of this component. - * - * @return The Stage component this component belongs to. - * @throws IllegalStateException if a Stage component is not in the parentage. - */ - public final Stage getStage() { - checkState(); - RocketComponent c = this; - while (c != null) { - if (c instanceof Stage) - return (Stage) c; - c = c.getParent(); - } - throw new IllegalStateException("getStage() called without Stage as a parent."); - } - - /** - * Return the stage number of the stage this component belongs to. The stages - * are numbered from zero upwards. - * - * @return the stage number this component belongs to. - */ - public final int getStageNumber() { - checkState(); - if (parent == null) { - throw new IllegalArgumentException("getStageNumber() called for root component"); - } - - RocketComponent stage = this; - while (!(stage instanceof Stage)) { - stage = stage.parent; - if (stage == null || stage.parent == null) { - throw new IllegalStateException("getStageNumber() could not find parent " + - "stage."); - } - } - return stage.parent.getChildPosition(stage); - } - - - /** - * Find a component with the given ID. The component tree is searched from this component - * down (including this component) for the ID and the corresponding component is returned, - * or null if not found. - * - * @param idToFind ID to search for. - * @return The component with the ID, or null if not found. - */ - public final RocketComponent findComponent(String idToFind) { - checkState(); - Iterator<RocketComponent> iter = this.iterator(true); - while (iter.hasNext()) { - RocketComponent c = iter.next(); - if (c.getID().equals(idToFind)) - return c; - } - return null; - } - - - // TODO: Move these methods elsewhere (used only in SymmetricComponent) - public final RocketComponent getPreviousComponent() { - checkState(); - this.checkComponentStructure(); - if (parent == null) - return null; - int pos = parent.getChildPosition(this); - if (pos < 0) { - StringBuffer sb = new StringBuffer(); - sb.append("Inconsistent internal state: "); - sb.append("this=").append(this).append('[') - .append(System.identityHashCode(this)).append(']'); - sb.append(" parent.children=["); - for (int i = 0; i < parent.children.size(); i++) { - RocketComponent c = parent.children.get(i); - sb.append(c).append('[').append(System.identityHashCode(c)).append(']'); - if (i < parent.children.size() - 1) - sb.append(", "); - } - sb.append(']'); - throw new IllegalStateException(sb.toString()); - } - assert (pos >= 0); - if (pos == 0) - return parent; - RocketComponent c = parent.getChild(pos - 1); - while (c.getChildCount() > 0) - c = c.getChild(c.getChildCount() - 1); - return c; - } - - // TODO: Move these methods elsewhere (used only in SymmetricComponent) - public final RocketComponent getNextComponent() { - checkState(); - if (getChildCount() > 0) - return getChild(0); - - RocketComponent current = this; - RocketComponent nextParent = this.parent; - - while (nextParent != null) { - int pos = nextParent.getChildPosition(current); - if (pos < nextParent.getChildCount() - 1) - return nextParent.getChild(pos + 1); - - current = nextParent; - nextParent = current.parent; - } - return null; - } - - - /////////// Event handling ////////// - // - // Listener lists are provided by the root Rocket component, - // a single listener list for the whole rocket. - // - - /** - * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root - * component, which must be of type Rocket (which overrides this method). Events of all - * subcomponents are sent to all listeners. - * - * @throws IllegalStateException - if the root component is not a Rocket - */ - public void addComponentChangeListener(ComponentChangeListener l) { - checkState(); - getRocket().addComponentChangeListener(l); - } - - /** - * Removes a ComponentChangeListener from the rocket tree. The listener is removed from - * the root component, which must be of type Rocket (which overrides this method). - * Does nothing if the root component is not a Rocket. (The asymmetry is so - * that listeners can always be removed just in case.) - * - * @param l Listener to remove - */ - public void removeComponentChangeListener(ComponentChangeListener l) { - if (parent != null) { - getRoot().removeComponentChangeListener(l); - } - } - - - /** - * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to - * <code>addComponentChangeListener()</code> except that it uses a - * <code>ChangeListener</code>. The same events are dispatched to the - * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass - * of <code>ChangeEvent</code>. - * - * @throws IllegalStateException - if the root component is not a <code>Rocket</code> - */ - @Override - public void addChangeListener(EventListener l) { - checkState(); - getRocket().addChangeListener(l); - } - - /** - * Removes a ChangeListener from the rocket tree. This is identical to - * removeComponentChangeListener() except it uses a ChangeListener. - * Does nothing if the root component is not a Rocket. (The asymmetry is so - * that listeners can always be removed just in case.) - * - * @param l Listener to remove - */ - @Override - public void removeChangeListener(EventListener l) { - if (this.parent != null) { - getRoot().removeChangeListener(l); - } - } - - - /** - * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the - * root component, which must be of type Rocket (which overrides this method). - * Events of all subcomponents are sent to all listeners. - * - * If the component tree root is not a Rocket, the event is ignored. This is the - * case when constructing components not in any Rocket tree. In this case it - * would be impossible for the component to have listeners in any case. - * - * @param e Event to send - */ - protected void fireComponentChangeEvent(ComponentChangeEvent e) { - checkState(); - if (parent == null) { - /* Ignore if root invalid. */ - log.debug("Attempted firing event " + e + " with root " + this.getComponentName() + ", ignoring event"); - return; - } - getRoot().fireComponentChangeEvent(e); - } - - - /** - * Fires a ComponentChangeEvent of the given type. The source of the event is set to - * this component. - * - * @param type Type of event - * @see #fireComponentChangeEvent(ComponentChangeEvent) - */ - protected void fireComponentChangeEvent(int type) { - fireComponentChangeEvent(new ComponentChangeEvent(this, type)); - } - - - /** - * Checks whether this component has been invalidated and should no longer be used. - * This is a safety check that in-place replaced components are no longer used. - * All non-trivial methods (with the exception of methods simply getting a property) - * should call this method before changing or computing anything. - * - * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}. - */ - protected void checkState() { - invalidator.check(true); - mutex.verify(); - } - - - /** - * Check that the local component structure is correct. This can be called after changing - * the component structure in order to verify the integrity. - * <p> - * TODO: Remove this after the "inconsistent internal state" bug has been corrected - */ - public void checkComponentStructure() { - if (this.parent != null) { - // Test that this component is found in parent's children with == operator - if (!containsExact(this.parent.children, this)) { - throw new BugException("Inconsistent component structure detected, parent does not contain this " + - "component as a child, parent=" + parent.toDebugString() + " this=" + this.toDebugString()); - } - } - for (RocketComponent child : this.children) { - if (child.parent != this) { - throw new BugException("Inconsistent component structure detected, child does not have this component " + - "as the parent, this=" + this.toDebugString() + " child=" + child.toDebugString() + - " child.parent=" + (child.parent == null ? "null" : child.parent.toDebugString())); - } - } - } - - // Check whether the list contains exactly the searched-for component (with == operator) - private boolean containsExact(List<RocketComponent> haystack, RocketComponent needle) { - for (RocketComponent c : haystack) { - if (needle == c) { - return true; - } - } - return false; - } - - - /////////// Iterators ////////// - - /** - * Returns an iterator that iterates over all children and sub-children. - * <p> - * The iterator iterates through all children below this object, including itself if - * <code>returnSelf</code> is true. The order of the iteration is not specified - * (it may be specified in the future). - * <p> - * If an iterator iterating over only the direct children of the component is required, - * use <code>component.getChildren().iterator()</code>. - * - * TODO: HIGH: Remove this after merges have been done - * - * @param returnSelf boolean value specifying whether the component itself should be - * returned - * @return An iterator for the children and sub-children. - * @deprecated Use {@link #iterator(boolean)} instead - */ - @Deprecated - public final Iterator<RocketComponent> deepIterator(boolean returnSelf) { - return iterator(returnSelf); - } - - - /** - * Returns an iterator that iterates over all children and sub-children, including itself. - * <p> - * This method is equivalent to <code>deepIterator(true)</code>. - * - * TODO: HIGH: Remove this after merges have been done - * - * @return An iterator for this component, its children and sub-children. - * @deprecated Use {@link #iterator()} instead - */ - @Deprecated - public final Iterator<RocketComponent> deepIterator() { - return iterator(); - } - - - - /** - * Returns an iterator that iterates over all children and sub-children. - * <p> - * The iterator iterates through all children below this object, including itself if - * <code>returnSelf</code> is true. The order of the iteration is not specified - * (it may be specified in the future). - * <p> - * If an iterator iterating over only the direct children of the component is required, - * use <code>component.getChildren().iterator()</code>. - * - * @param returnSelf boolean value specifying whether the component itself should be - * returned - * @return An iterator for the children and sub-children. - */ - public final Iterator<RocketComponent> iterator(boolean returnSelf) { - checkState(); - return new RocketComponentIterator(this, returnSelf); - } - - - /** - * Returns an iterator that iterates over this component, its children and sub-children. - * <p> - * This method is equivalent to <code>iterator(true)</code>. - * - * @return An iterator for this component, its children and sub-children. - */ - @Override - public final Iterator<RocketComponent> iterator() { - return iterator(true); - } - - /** - * Retrieve the List of MotorMounts in the Rocket. - * - * Each element returned will a RocketComponent which implements MotorMount. Further isMotorMount() - * returns true. - * - * @return List<MotorMount> - */ - public final List<MotorMount> getMotorMounts() { - Iterator<RocketComponent> it = iterator(); - List<MotorMount> mmts = new ArrayList<MotorMount>(); - - while (it.hasNext()) { - RocketComponent c = it.next(); - if (c instanceof MotorMount) { - if ( ((MotorMount)c).isMotorMount() ) { - mmts.add((MotorMount) c); - } - } - } - return mmts; - } - - /** - * Compare component equality based on the ID of this component. Only the - * ID and class type is used for a basis of comparison. - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (this.getClass() != obj.getClass()) - return false; - RocketComponent other = (RocketComponent) obj; - return this.id.equals(other.id); - } - - - - @Override - public int hashCode() { - return id.hashCode(); - } - - - - //////////// Helper methods for subclasses - - - - - /** - * Helper method to add rotationally symmetric bounds at the specified coordinates. - * The X-axis value is <code>x</code> and the radius at the specified position is - * <code>r</code>. - */ - protected static final void addBound(Collection<Coordinate> bounds, double x, double r) { - bounds.add(new Coordinate(x, -r, -r)); - bounds.add(new Coordinate(x, r, -r)); - bounds.add(new Coordinate(x, r, r)); - bounds.add(new Coordinate(x, -r, r)); - } - - - protected static final Coordinate ringCG(double outerRadius, double innerRadius, - double x1, double x2, double density) { - return new Coordinate((x1 + x2) / 2, 0, 0, - ringMass(outerRadius, innerRadius, x2 - x1, density)); - } - - protected static final double ringVolume( double outerRadius, double innerRadius, double length ) { - return ringMass( outerRadius, innerRadius, length, 1.0 ); - } - - protected static final double ringMass(double outerRadius, double innerRadius, - double length, double density) { - return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) * - length * density; - } - - protected static final double ringLongitudinalUnitInertia(double outerRadius, - double innerRadius, double length) { - // 1/12 * (3 * (r1^2 + r2^2) + h^2) - return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12; - } - - protected static final double ringRotationalUnitInertia(double outerRadius, - double innerRadius) { - // 1/2 * (r1^2 + r2^2) - return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2; - } - - - - //////////// OTHER - - - /** - * Loads the RocketComponent fields from the given component. This method is meant - * for in-place replacement of a component. It is used with the undo/redo - * mechanism and when converting a finset into a freeform fin set. - * This component must not have a parent, otherwise this method will fail. - * <p> - * The child components in the source tree are copied into the current tree, however, - * the original components should not be used since they represent old copies of the - * components. It is recommended to invalidate them by calling {@link #invalidate()}. - * <p> - * This method returns a list of components that should be invalidated after references - * to them have been removed (for example by firing appropriate events). The list contains - * all children and sub-children of the current component and the entire component - * tree of <code>src</code>. - * - * @return a list of components that should not be used after this call. - */ - protected List<RocketComponent> copyFrom(RocketComponent src) { - checkState(); - List<RocketComponent> toInvalidate = new ArrayList<RocketComponent>(); - - if (this.parent != null) { - throw new UnsupportedOperationException("copyFrom called for non-root component, parent=" + - this.parent.toDebugString() + ", this=" + this.toDebugString()); - } - - // Add current structure to be invalidated - Iterator<RocketComponent> iterator = this.iterator(false); - while (iterator.hasNext()) { - toInvalidate.add(iterator.next()); - } - - // Remove previous components - for (RocketComponent child : this.children) { - child.parent = null; - } - this.children.clear(); - - // Copy new children to this component - for (RocketComponent c : src.children) { - RocketComponent copy = c.copyWithOriginalID(); - this.children.add(copy); - copy.parent = this; - } - - this.checkComponentStructure(); - src.checkComponentStructure(); - - // Set all parameters - this.length = src.length; - this.relativePosition = src.relativePosition; - this.position = src.position; - this.color = src.color; - this.lineStyle = src.lineStyle; - this.overrideMass = src.overrideMass; - this.massOverriden = src.massOverriden; - this.overrideCGX = src.overrideCGX; - this.cgOverriden = src.cgOverriden; - this.overrideSubcomponents = src.overrideSubcomponents; - this.name = src.name; - this.comment = src.comment; - this.id = src.id; - - // Add source components to invalidation tree - for (RocketComponent c : src) { - toInvalidate.add(c); - } - - return toInvalidate; - } - - protected void invalidate() { - invalidator.invalidate(); - } - - - ////////// Iterator implementation /////////// - - /** - * Private inner class to implement the Iterator. - * - * This iterator is fail-fast if the root of the structure is a Rocket. - */ - private static class RocketComponentIterator implements Iterator<RocketComponent> { - // Stack holds iterators which still have some components left. - private final SimpleStack<Iterator<RocketComponent>> iteratorStack = new SimpleStack<Iterator<RocketComponent>>(); - - private final Rocket root; - private final int treeModID; - - private final RocketComponent original; - private boolean returnSelf = false; - - // Construct iterator with component's child's iterator, if it has elements - public RocketComponentIterator(RocketComponent c, boolean returnSelf) { - - RocketComponent gp = c.getRoot(); - if (gp instanceof Rocket) { - root = (Rocket) gp; - treeModID = root.getTreeModID(); - } else { - root = null; - treeModID = -1; - } - - Iterator<RocketComponent> i = c.children.iterator(); - if (i.hasNext()) - iteratorStack.push(i); - - this.original = c; - this.returnSelf = returnSelf; - } - - @Override - public boolean hasNext() { - checkID(); - if (returnSelf) - return true; - return !iteratorStack.isEmpty(); // Elements remain if stack is not empty - } - - @Override - public RocketComponent next() { - Iterator<RocketComponent> i; - - checkID(); - - // Return original component first - if (returnSelf) { - returnSelf = false; - return original; - } - - // Peek first iterator from stack, throw exception if empty - i = iteratorStack.peek(); - if (i == null) { - throw new NoSuchElementException("No further elements in RocketComponent iterator"); - } - - // Retrieve next component of the iterator, remove iterator from stack if empty - RocketComponent c = i.next(); - if (!i.hasNext()) - iteratorStack.pop(); - - // Add iterator of component children to stack if it has children - i = c.children.iterator(); - if (i.hasNext()) - iteratorStack.push(i); - - return c; - } - - private void checkID() { - if (root != null) { - if (root.getTreeModID() != treeModID) { - throw new IllegalStateException("Rocket modified while being iterated"); - } - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() not supported by " + - "RocketComponent iterator"); - } - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/RocketUtils.java b/core/src/net/sf/openrocket/rocketcomponent/RocketUtils.java deleted file mode 100644 index 71360b9a..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/RocketUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import java.util.Collection; - -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.util.Coordinate; - -public abstract class RocketUtils { - - public static double getLength(Rocket rocket) { - double length = 0; - Collection<Coordinate> bounds = rocket.getDefaultConfiguration().getBounds(); - if (!bounds.isEmpty()) { - double minX = Double.POSITIVE_INFINITY, maxX = Double.NEGATIVE_INFINITY; - for (Coordinate c : bounds) { - if (c.x < minX) - minX = c.x; - if (c.x > maxX) - maxX = c.x; - } - length = maxX - minX; - } - return length; - } - - public static Coordinate getCG(Rocket rocket, MassCalcType calcType) { - MassCalculator massCalculator = new BasicMassCalculator(); - Coordinate cg = massCalculator.getCG(rocket.getDefaultConfiguration(), calcType); - return cg; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ShockCord.java b/core/src/net/sf/openrocket/rocketcomponent/ShockCord.java deleted file mode 100644 index 8012a87e..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ShockCord.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; - -public class ShockCord extends MassObject { - private static final Translator trans = Application.getTranslator(); - - private Material material; - private double cordLength; - - public ShockCord() { - material = Application.getPreferences().getDefaultComponentMaterial(ShockCord.class, Material.Type.LINE); - cordLength = 0.4; - } - - - - public Material getMaterial() { - return material; - } - - public void setMaterial(Material m) { - if (m.getType() != Material.Type.LINE) - throw new BugException("Attempting to set non-linear material."); - if (material.equals(m)) - return; - this.material = m; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - public double getCordLength() { - return cordLength; - } - - public void setCordLength(double length) { - length = MathUtil.max(length, 0); - if (MathUtil.equals(length, this.length)) - return; - this.cordLength = length; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - @Override - public double getComponentMass() { - return material.getDensity() * cordLength; - } - - @Override - public String getComponentName() { - //// Shock cord - return trans.get("ShockCord.ShockCord"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class<? extends RocketComponent> type) { - return false; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java b/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java deleted file mode 100644 index f6f342c6..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -/** - * A RingComponent that comes on top of another tube. It's defined by the inner - * radius and thickness. The inner radius can be automatic, in which case it - * takes the radius of the parent component. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Sleeve extends RingComponent { - private static final Translator trans = Application.getTranslator(); - - protected double innerRadius = 0; - protected double thickness = 0; - - - public Sleeve() { - super(); - setInnerRadiusAutomatic(true); - setThickness(0.001); - setLength(0.05); - } - - - @Override - public double getOuterRadius() { - return getInnerRadius() + thickness; - } - - @Override - public void setOuterRadius(double r) { - if (MathUtil.equals(getOuterRadius(), r)) - return; - - innerRadius = Math.max(r - thickness, 0); - if (thickness > r) - thickness = r; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - @Override - public double getInnerRadius() { - // Implement parent inner radius automation - if (isInnerRadiusAutomatic() && getParent() instanceof RadialParent) { - RocketComponent parent = getParent(); - double pos1 = this.toRelative(Coordinate.NUL, parent)[0].x; - double pos2 = this.toRelative(new Coordinate(getLength()), parent)[0].x; - pos1 = MathUtil.clamp(pos1, 0, parent.getLength()); - pos2 = MathUtil.clamp(pos2, 0, parent.getLength()); - innerRadius = Math.max(((RadialParent) parent).getOuterRadius(pos1), - ((RadialParent) parent).getOuterRadius(pos2)); - } - - return innerRadius; - } - - @Override - public void setInnerRadius(double r) { - r = Math.max(r, 0); - if (MathUtil.equals(innerRadius, r)) - return; - innerRadius = r; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - @Override - public double getThickness() { - return thickness; - } - - @Override - public void setThickness(double t) { - t = Math.max(t, 0); - if (MathUtil.equals(thickness, t)) - return; - thickness = t; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - @Override - public void setInnerRadiusAutomatic(boolean auto) { - super.setOuterRadiusAutomatic(auto); - } - - @Override - public String getComponentName() { - return trans.get ("Sleeve.Sleeve"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class<? extends RocketComponent> type) { - return false; - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Stage.java b/core/src/net/sf/openrocket/rocketcomponent/Stage.java deleted file mode 100644 index 6ea9c297..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Stage.java +++ /dev/null @@ -1,152 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - -public class Stage extends ComponentAssembly { - - private static final Translator trans = Application.getTranslator(); - - - public static enum SeparationEvent { - //// Upper stage motor ignition - UPPER_IGNITION("Stage.SeparationEvent.UPPER_IGNITION") { - @Override - public boolean isSeparationEvent(FlightEvent e, Stage stage) { - if (e.getType() != FlightEvent.Type.IGNITION) - return false; - - int ignition = e.getSource().getStageNumber(); - int mount = stage.getStageNumber(); - return (mount == ignition + 1); - } - }, - //// Current stage motor ignition - IGNITION("Stage.SeparationEvent.IGNITION") { - @Override - public boolean isSeparationEvent(FlightEvent e, Stage stage) { - if (e.getType() != FlightEvent.Type.IGNITION) - return false; - - int ignition = e.getSource().getStageNumber(); - int mount = stage.getStageNumber(); - return (mount == ignition); - } - }, - //// Current stage motor burnout - BURNOUT("Stage.SeparationEvent.BURNOUT") { - @Override - public boolean isSeparationEvent(FlightEvent e, Stage stage) { - if (e.getType() != FlightEvent.Type.BURNOUT) - return false; - - int ignition = e.getSource().getStageNumber(); - int mount = stage.getStageNumber(); - return (mount == ignition); - } - }, - //// Current stage ejection charge - EJECTION("Stage.SeparationEvent.EJECTION") { - @Override - public boolean isSeparationEvent(FlightEvent e, Stage stage) { - if (e.getType() != FlightEvent.Type.EJECTION_CHARGE) - return false; - - int ignition = e.getSource().getStageNumber(); - int mount = stage.getStageNumber(); - return (mount == ignition); - } - }, - //// Launch - LAUNCH("Stage.SeparationEvent.LAUNCH") { - @Override - public boolean isSeparationEvent(FlightEvent e, Stage stage) { - return e.getType() == FlightEvent.Type.LAUNCH; - } - }, - //// Never - NEVER("Stage.SeparationEvent.NEVER") { - @Override - public boolean isSeparationEvent(FlightEvent e, Stage stage) { - return false; - } - }, - ; - - - private final String description; - - SeparationEvent(String description) { - this.description = description; - } - - /** - * Test whether a specific event is a stage separation event. - */ - public abstract boolean isSeparationEvent(FlightEvent e, Stage stage); - - @Override - public String toString() { - return trans.get(description); - } - }; - - - private SeparationEvent separationEvent = SeparationEvent.UPPER_IGNITION; - private double separationDelay = 0; - - - @Override - public String getComponentName() { - //// Stage - return trans.get("Stage.Stage"); - } - - - public SeparationEvent getSeparationEvent() { - return separationEvent; - } - - - public void setSeparationEvent(SeparationEvent separationEvent) { - if (separationEvent == this.separationEvent) - return; - this.separationEvent = separationEvent; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - public double getSeparationDelay() { - return separationDelay; - } - - - public void setSeparationDelay(double separationDelay) { - if (MathUtil.equals(separationDelay, this.separationDelay)) - return; - this.separationDelay = separationDelay; - fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); - } - - - - @Override - public boolean allowsChildren() { - return true; - } - - /** - * Check whether the given type can be added to this component. A Stage allows - * only BodyComponents to be added. - * - * @param type The RocketComponent class type to add. - * - * @return Whether such a component can be added. - */ - @Override - public boolean isCompatible(Class<? extends RocketComponent> type) { - return BodyComponent.class.isAssignableFrom(type); - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Streamer.java b/core/src/net/sf/openrocket/rocketcomponent/Streamer.java deleted file mode 100644 index 058392e9..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Streamer.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; - -public class Streamer extends RecoveryDevice { - - public static final double DEFAULT_CD = 0.6; - - public static final double MAX_COMPUTED_CD = 0.4; - - private static final Translator trans = Application.getTranslator(); - - private double stripLength; - private double stripWidth; - - - public Streamer() { - this.stripLength = 0.5; - this.stripWidth = 0.05; - } - - - public double getStripLength() { - return stripLength; - } - - public void setStripLength(double stripLength) { - if (MathUtil.equals(this.stripLength, stripLength)) - return; - this.stripLength = stripLength; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public double getStripWidth() { - return stripWidth; - } - - public void setStripWidth(double stripWidth) { - if (MathUtil.equals(this.stripWidth, stripWidth)) - return; - this.stripWidth = stripWidth; - this.length = stripWidth; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public void setLength(double length) { - setStripWidth(length); - } - - - public double getAspectRatio() { - if (stripWidth > 0.0001) - return stripLength / stripWidth; - return 1000; - } - - public void setAspectRatio(double ratio) { - if (MathUtil.equals(getAspectRatio(), ratio)) - return; - - ratio = Math.max(ratio, 0.01); - double area = getArea(); - stripWidth = MathUtil.safeSqrt(area / ratio); - stripLength = ratio * stripWidth; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public double getArea() { - return stripWidth * stripLength; - } - - public void setArea(double area) { - if (MathUtil.equals(getArea(), area)) - return; - - double ratio = Math.max(getAspectRatio(), 0.01); - stripWidth = MathUtil.safeSqrt(area / ratio); - stripLength = ratio * stripWidth; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - @Override - public Type getPresetType() { - return ComponentPreset.Type.STREAMER; - } - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.LENGTH)) { - this.stripLength = preset.get(ComponentPreset.LENGTH); - } - if ( preset.has(ComponentPreset.WIDTH)) { - this.stripWidth = preset.get(ComponentPreset.WIDTH); - } - super.loadFromPreset(preset); - // Fix the length to the stripWidth since RocketComponent assigns ComponentPreset.LENGTH to length. - this.length = this.stripWidth; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - @Override - public double getComponentCD(double mach) { - double density = this.getMaterial().getDensity(); - double cd; - - cd = 0.034 * ((density + 0.025) / 0.105) * (stripLength + 1) / stripLength; - cd = MathUtil.min(cd, MAX_COMPUTED_CD); - return cd; - } - - @Override - public String getComponentName() { - return trans.get ("Streamer.Streamer"); - } - - @Override - public boolean allowsChildren() { - return false; - } - - @Override - public boolean isCompatible(Class<? extends RocketComponent> type) { - return false; - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java b/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java deleted file mode 100644 index b7143c68..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.startup.Application; - -public abstract class StructuralComponent extends InternalComponent { - - private Material material; - - public StructuralComponent() { - super(); - material = Application.getPreferences().getDefaultComponentMaterial(this.getClass(), Material.Type.BULK); - } - - @Override - protected void loadFromPreset(ComponentPreset preset) { - super.loadFromPreset(preset); - if ( preset.has(ComponentPreset.MATERIAL ) ) { - Material mat = preset.get(ComponentPreset.MATERIAL); - if ( mat != null ) { - this.material = mat; - } /* - TODO - - else if (c.isMassOverridden()) { - double mass = c.getOverrideMass(); - double volume = getComponentVolume(); - double density; - if (volume > 0.00001) { - density = mass / volume; - } else { - density = 1000; - } - mat = Material.newMaterial(Type.BULK, mat.getName(), density, true); - setMaterial(mat); - } - */ - } - } - - public final Material getMaterial() { - return material; - } - - public final void setMaterial(Material mat) { - if (mat.getType() != Material.Type.BULK) { - throw new IllegalArgumentException("Attempted to set non-bulk material "+mat); - } - if (mat.equals(material)) - return; - this.material = mat; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/SymmetricComponent.java b/core/src/net/sf/openrocket/rocketcomponent/SymmetricComponent.java deleted file mode 100644 index 7b455fa8..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/SymmetricComponent.java +++ /dev/null @@ -1,600 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import static net.sf.openrocket.util.MathUtil.pow2; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - - -/** - * Class for an axially symmetric rocket component generated by rotating - * a function y=f(x) >= 0 around the x-axis (eg. tube, cone, etc.) - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - -public abstract class SymmetricComponent extends BodyComponent implements RadialParent { - public static final double DEFAULT_RADIUS = 0.025; - public static final double DEFAULT_THICKNESS = 0.002; - - private static final int DIVISIONS = 100; // No. of divisions when integrating - - protected boolean filled = false; - protected double thickness = DEFAULT_THICKNESS; - - - // Cached data, default values signify not calculated - private double wetArea = -1; - private double planArea = -1; - private double planCenter = -1; - private double volume = -1; - private double fullVolume = -1; - private double longitudinalInertia = -1; - private double rotationalInertia = -1; - private Coordinate cg = null; - - - - public SymmetricComponent() { - super(); - } - - - /** - * Return the component radius at position x. - * @param x Position on x-axis. - * @return Radius of the component at the given position, or 0 if outside - * the component. - */ - public abstract double getRadius(double x); - - @Override - public abstract double getInnerRadius(double x); - - public abstract double getForeRadius(); - - public abstract boolean isForeRadiusAutomatic(); - - public abstract double getAftRadius(); - - public abstract boolean isAftRadiusAutomatic(); - - - // Implement the Radial interface: - @Override - public final double getOuterRadius(double x) { - return getRadius(x); - } - - - @Override - public final double getRadius(double x, double theta) { - return getRadius(x); - } - - @Override - public final double getInnerRadius(double x, double theta) { - return getInnerRadius(x); - } - - - - /** - * Return the component wall thickness. - */ - public double getThickness() { - if (filled) - return Math.max(getForeRadius(), getAftRadius()); - return Math.min(thickness, Math.max(getForeRadius(), getAftRadius())); - } - - - /** - * Set the component wall thickness. Values greater than the maximum radius are not - * allowed, and will result in setting the thickness to the maximum radius. - */ - public void setThickness(double thickness) { - if ((this.thickness == thickness) && !filled) - return; - this.thickness = MathUtil.clamp(thickness, 0, Math.max(getForeRadius(), getAftRadius())); - filled = false; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - clearPreset(); - } - - - /** - * Returns whether the component is set as filled. If it is set filled, then the - * wall thickness will have no effect. - */ - public boolean isFilled() { - return filled; - } - - - /** - * Sets whether the component is set as filled. If the component is filled, then - * the wall thickness will have no effect. - */ - public void setFilled(boolean filled) { - if (this.filled == filled) - return; - this.filled = filled; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - clearPreset(); - } - - - /** - * Adds component bounds at a number of points between 0...length. - */ - @Override - public Collection<Coordinate> getComponentBounds() { - List<Coordinate> list = new ArrayList<Coordinate>(20); - for (int n = 0; n <= 5; n++) { - double x = n * length / 5; - double r = getRadius(x); - addBound(list, x, r); - } - return list; - } - - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.THICKNESS) ) { - this.thickness = preset.get(ComponentPreset.THICKNESS); - this.filled = false; - } - if ( preset.has(ComponentPreset.FILLED)) { - this.filled = true; - } - - super.loadFromPreset(preset); - } - - - - - /** - * Calculate volume of the component by integrating over the length of the component. - * The method caches the result, so subsequent calls are instant. Subclasses may - * override this method for simple shapes and use this method as necessary. - * - * @return The volume of the component. - */ - @Override - public double getComponentVolume() { - if (volume < 0) - integrate(); - return volume; - } - - - /** - * Calculate full (filled) volume of the component by integrating over the length - * of the component. The method caches the result, so subsequent calls are instant. - * Subclasses may override this method for simple shapes and use this method as - * necessary. - * - * @return The filled volume of the component. - */ - public double getFullVolume() { - if (fullVolume < 0) - integrate(); - return fullVolume; - } - - - /** - * Calculate the wetted area of the component by integrating over the length - * of the component. The method caches the result, so subsequent calls are instant. - * Subclasses may override this method for simple shapes and use this method as - * necessary. - * - * @return The wetted area of the component. - */ - public double getComponentWetArea() { - if (wetArea < 0) - integrate(); - return wetArea; - } - - - /** - * Calculate the planform area of the component by integrating over the length of - * the component. The method caches the result, so subsequent calls are instant. - * Subclasses may override this method for simple shapes and use this method as - * necessary. - * - * @return The planform area of the component. - */ - public double getComponentPlanformArea() { - if (planArea < 0) - integrate(); - return planArea; - } - - - /** - * Calculate the planform center X-coordinate of the component by integrating over - * the length of the component. The planform center is defined as - * <pre> integrate(x*2*r(x)) / planform area </pre> - * The method caches the result, so subsequent calls are instant. Subclasses may - * override this method for simple shapes and use this method as necessary. - * - * @return The planform center of the component. - */ - public double getComponentPlanformCenter() { - if (planCenter < 0) - integrate(); - return planCenter; - } - - - /** - * Calculate CG of the component by integrating over the length of the component. - * The method caches the result, so subsequent calls are instant. Subclasses may - * override this method for simple shapes and use this method as necessary. - * - * @return The CG+mass of the component. - */ - @Override - public Coordinate getComponentCG() { - if (cg == null) - integrate(); - return cg; - } - - - @Override - public double getLongitudinalUnitInertia() { - if (longitudinalInertia < 0) { - if (getComponentVolume() > 0.0000001) // == 0.1cm^3 - integrateInertiaVolume(); - else - integrateInertiaSurface(); - } - return longitudinalInertia; - } - - - @Override - public double getRotationalUnitInertia() { - if (rotationalInertia < 0) { - if (getComponentVolume() > 0.0000001) - integrateInertiaVolume(); - else - integrateInertiaSurface(); - } - return rotationalInertia; - } - - - - /** - * Performs integration over the length of the component and updates the cached variables. - */ - private void integrate() { - double x, r1, r2; - double cgx; - - // Check length > 0 - if (length <= 0) { - wetArea = 0; - planArea = 0; - planCenter = 0; - volume = 0; - cg = Coordinate.NUL; - return; - } - - - // Integrate for volume, CG, wetted area and planform area - - final double step = length / DIVISIONS; - final double pi3 = Math.PI / 3.0; - r1 = getRadius(0); - x = 0; - wetArea = 0; - planArea = 0; - planCenter = 0; - fullVolume = 0; - volume = 0; - cgx = 0; - - for (int n = 1; n <= DIVISIONS; n++) { - /* - * r1 and r2 are the two radii - * x is the position of r1 - * hyp is the length of the hypotenuse from r1 to r2 - * height if the y-axis height of the component if not filled - */ - /* - * l is the step size for the current loop. Could also be called delta-x. - * - * to account for accumulated errors in the x position during the loop - * during the last iteration (n== DIVISIONS) we recompute l to be - * whatever is left. - */ - double l = (n==DIVISIONS) ? length -x : step; - - // Further to prevent round off error from the previous statement, - // we clamp r2 to length at the last iteration. - r2 = getRadius((n==DIVISIONS) ? length : x + l); - - final double hyp = MathUtil.hypot(r2 - r1, l); - - // Volume differential elements - final double dV; - final double dFullV; - - dFullV = pi3 * l * (r1 * r1 + r1 * r2 + r2 * r2); - - if ( filled ) { - dV = dFullV; - } else { - // hollow - // Thickness is normal to the surface of the component - // here we use simple trig to project the Thickness - // on to the y dimension (radius). - double height = thickness * hyp / l; - if (r1 < height || r2 < height) { - // Filled portion of piece - dV = dFullV; - } else { - // Hollow portion of piece - dV = MathUtil.max(Math.PI* l * height * (r1 + r2 - height), 0); - } - } - - // Add to the volume-related components - volume += dV; - fullVolume += dFullV; - cgx += (x + l / 2) * dV; - - // Wetted area ( * PI at the end) - wetArea += hyp * (r1 + r2); - - // Planform area & center - final double p = l * (r1 + r2); - planArea += p; - planCenter += (x + l / 2) * p; - - // Update for next iteration - r1 = r2; - x += l; - } - - wetArea *= Math.PI; - - if (planArea > 0) - planCenter /= planArea; - - if (volume < 0.0000000001) { // 0.1 mm^3 - volume = 0; - cg = new Coordinate(length / 2, 0, 0, 0); - } else { - // the mass of this shape is the material density * volume. - // it cannot come from super.getComponentMass() since that - // includes the shoulders - cg = new Coordinate(cgx / volume, 0, 0, getMaterial().getDensity() * volume ); - } - } - - - /** - * Integrate the longitudinal and rotational inertia based on component volume. - * This method may be used only if the total volume is zero. - */ - private void integrateInertiaVolume() { - double x, r1, r2; - - final double l = length / DIVISIONS; - final double pil = Math.PI * l; // PI * l - final double pil3 = Math.PI * l / 3; // PI * l/3 - - r1 = getRadius(0); - x = 0; - longitudinalInertia = 0; - rotationalInertia = 0; - - double vol = 0; - - for (int n = 1; n <= DIVISIONS; n++) { - /* - * r1 and r2 are the two radii, outer is their average - * x is the position of r1 - * hyp is the length of the hypotenuse from r1 to r2 - * height if the y-axis height of the component if not filled - */ - r2 = getRadius(x + l); - final double outer = (r1 + r2) / 2; - - - // Volume differential elements - final double inner; - final double dV; - - if (filled || r1 < thickness || r2 < thickness) { - inner = 0; - dV = pil3 * (r1 * r1 + r1 * r2 + r2 * r2); - } else { - final double hyp = MathUtil.hypot(r2 - r1, l); - final double height = thickness * hyp / l; - dV = pil * height * (r1 + r2 - height); - inner = Math.max(outer - height, 0); - } - - rotationalInertia += dV * (pow2(outer) + pow2(inner)) / 2; - longitudinalInertia += dV * ((3 * (pow2(outer) + pow2(inner)) + pow2(l)) / 12 - + pow2(x + l / 2)); - - vol += dV; - - // Update for next iteration - r1 = r2; - x += l; - } - - if (MathUtil.equals(vol, 0)) { - integrateInertiaSurface(); - return; - } - - rotationalInertia /= vol; - longitudinalInertia /= vol; - - // Shift longitudinal inertia to CG - longitudinalInertia = Math.max(longitudinalInertia - pow2(getComponentCG().x), 0); - } - - - - /** - * Integrate the longitudinal and rotational inertia based on component surface area. - * This method may be used only if the total volume is zero. - */ - private void integrateInertiaSurface() { - double x, r1, r2; - - final double l = length / DIVISIONS; - - r1 = getRadius(0); - //System.out.println(r1); - x = 0; - - longitudinalInertia = 0; - rotationalInertia = 0; - - double surface = 0; - - for (int n = 1; n <= DIVISIONS; n++) { - /* - * r1 and r2 are the two radii, outer is their average - * x is the position of r1 - * hyp is the length of the hypotenuse from r1 to r2 - * height if the y-axis height of the component if not filled - */ - r2 = getRadius(x + l); - final double hyp = MathUtil.hypot(r2 - r1, l); - final double outer = (r1 + r2) / 2; - - final double dS = hyp * (r1 + r2) * Math.PI; - - rotationalInertia += dS * pow2(outer); - longitudinalInertia += dS * ((6 * pow2(outer) + pow2(l)) / 12 + pow2(x + l / 2)); - - surface += dS; - - // Update for next iteration - r1 = r2; - x += l; - } - - if (MathUtil.equals(surface, 0)) { - longitudinalInertia = 0; - rotationalInertia = 0; - return; - } - - longitudinalInertia /= surface; - rotationalInertia /= surface; - - // Shift longitudinal inertia to CG - longitudinalInertia = Math.max(longitudinalInertia - pow2(getComponentCG().x), 0); - } - - - - - /** - * Invalidates the cached volume and CG information. - */ - @Override - protected void componentChanged(ComponentChangeEvent e) { - super.componentChanged(e); - if (!e.isOtherChange()) { - wetArea = -1; - planArea = -1; - planCenter = -1; - volume = -1; - fullVolume = -1; - longitudinalInertia = -1; - rotationalInertia = -1; - cg = null; - } - } - - - - /////////// Auto radius helper methods - - - /** - * Returns the automatic radius for this component towards the - * front of the rocket. The automatics will not search towards the - * rear of the rocket for a suitable radius. A positive return value - * indicates a preferred radius, a negative value indicates that a - * match was not found. - */ - protected abstract double getFrontAutoRadius(); - - /** - * Returns the automatic radius for this component towards the - * end of the rocket. The automatics will not search towards the - * front of the rocket for a suitable radius. A positive return value - * indicates a preferred radius, a negative value indicates that a - * match was not found. - */ - protected abstract double getRearAutoRadius(); - - - - /** - * Return the previous symmetric component, or null if none exists. - * NOTE: This method currently assumes that there are no external - * "pods". - * - * @return the previous SymmetricComponent, or null. - */ - protected final SymmetricComponent getPreviousSymmetricComponent() { - RocketComponent c; - for (c = this.getPreviousComponent(); c != null; c = c.getPreviousComponent()) { - if (c instanceof SymmetricComponent) { - return (SymmetricComponent) c; - } - if (!(c instanceof Stage) && - (c.relativePosition == RocketComponent.Position.AFTER)) - return null; // Bad component type as "parent" - } - return null; - } - - /** - * Return the next symmetric component, or null if none exists. - * NOTE: This method currently assumes that there are no external - * "pods". - * - * @return the next SymmetricComponent, or null. - */ - protected final SymmetricComponent getNextSymmetricComponent() { - RocketComponent c; - for (c = this.getNextComponent(); c != null; c = c.getNextComponent()) { - if (c instanceof SymmetricComponent) { - return (SymmetricComponent) c; - } - if (!(c instanceof Stage) && - (c.relativePosition == RocketComponent.Position.AFTER)) - return null; // Bad component type as "parent" - } - return null; - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java b/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java deleted file mode 100644 index c2d0a9bd..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -/** - * An inner component that consists of a hollow cylindrical component. This can be - * an inner tube, tube coupler, centering ring, bulkhead etc. - * - * The properties include the inner and outer radii, length and radial position. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public abstract class ThicknessRingComponent extends RingComponent { - - protected double outerRadius = 0; - protected double thickness = 0; - - @Override - protected void loadFromPreset(ComponentPreset preset) { - if ( preset.has(ComponentPreset.OUTER_DIAMETER) ) { - this.outerRadiusAutomatic = false; - this.innerRadiusAutomatic = false; - double outerDiameter = preset.get(ComponentPreset.OUTER_DIAMETER); - this.outerRadius = outerDiameter/2.0; - if ( preset.has(ComponentPreset.INNER_DIAMETER) ) { - double innerDiameter = preset.get(ComponentPreset.INNER_DIAMETER); - this.thickness = (outerDiameter-innerDiameter) / 2.0; - } - } - super.loadFromPreset(preset); - - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - - } - - @Override - public double getOuterRadius() { - if (isOuterRadiusAutomatic() && getParent() instanceof RadialParent) { - RocketComponent parent = getParent(); - double pos1 = this.toRelative(Coordinate.NUL, parent)[0].x; - double pos2 = this.toRelative(new Coordinate(getLength()), parent)[0].x; - pos1 = MathUtil.clamp(pos1, 0, parent.getLength()); - pos2 = MathUtil.clamp(pos2, 0, parent.getLength()); - outerRadius = Math.min(((RadialParent)parent).getInnerRadius(pos1), - ((RadialParent)parent).getInnerRadius(pos2)); - } - - return outerRadius; - } - - - @Override - public void setOuterRadius(double r) { - r = Math.max(r,0); - if (MathUtil.equals(outerRadius, r) && !isOuterRadiusAutomatic()) - return; - - outerRadius = r; - outerRadiusAutomatic = false; - - if (thickness > outerRadius) - thickness = outerRadius; - - clearPreset(); - - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - @Override - public double getThickness() { - return Math.min(thickness, getOuterRadius()); - } - @Override - public void setThickness(double thickness) { - double outer = getOuterRadius(); - - thickness = MathUtil.clamp(thickness, 0, outer); - if (MathUtil.equals(getThickness(), thickness)) - return; - - this.thickness = thickness; - - clearPreset(); - - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - @Override - public double getInnerRadius() { - return Math.max(getOuterRadius()-thickness, 0); - } - @Override - public void setInnerRadius(double r) { - r = Math.max(r,0); - setThickness(getOuterRadius() - r); - } - - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Transition.java b/core/src/net/sf/openrocket/rocketcomponent/Transition.java deleted file mode 100644 index 6b12f156..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Transition.java +++ /dev/null @@ -1,935 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -import java.util.Collection; - -import static java.lang.Math.sin; -import static net.sf.openrocket.util.MathUtil.pow2; -import static net.sf.openrocket.util.MathUtil.pow3; - - -public class Transition extends SymmetricComponent { - private static final Translator trans = Application.getTranslator(); - private static final double CLIP_PRECISION = 0.0001; - - - private Shape type; - private double shapeParameter; - private boolean clipped; // Not to be read - use isClipped(), which may be overriden - - private double radius1, radius2; - private boolean autoRadius1, autoRadius2; // Whether the start radius is automatic - - - private double foreShoulderRadius; - private double foreShoulderThickness; - private double foreShoulderLength; - private boolean foreShoulderCapped; - private double aftShoulderRadius; - private double aftShoulderThickness; - private double aftShoulderLength; - private boolean aftShoulderCapped; - - - // Used to cache the clip length - private double clipLength = -1; - - public Transition() { - super(); - - this.radius1 = DEFAULT_RADIUS; - this.radius2 = DEFAULT_RADIUS; - this.length = DEFAULT_RADIUS * 3; - this.autoRadius1 = true; - this.autoRadius2 = true; - - this.type = Shape.CONICAL; - this.shapeParameter = 0; - this.clipped = true; - } - - //////// Length //////// - @Override - public void setLength( double length ) { - if ( this.length == length ) { - return; - } - // Need to clearPreset when length changes. - clearPreset(); - super.setLength( length ); - } - - - //////// Fore radius //////// - - - @Override - public double getForeRadius() { - if (isForeRadiusAutomatic()) { - // Get the automatic radius from the front - double r = -1; - SymmetricComponent c = this.getPreviousSymmetricComponent(); - if (c != null) { - r = c.getFrontAutoRadius(); - } - if (r < 0) - r = DEFAULT_RADIUS; - return r; - } - return radius1; - } - - public void setForeRadius(double radius) { - if ((this.radius1 == radius) && (autoRadius1 == false)) - return; - - this.autoRadius1 = false; - this.radius1 = Math.max(radius, 0); - - if (this.thickness > this.radius1 && this.thickness > this.radius2) - this.thickness = Math.max(this.radius1, this.radius2); - - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public boolean isForeRadiusAutomatic() { - return autoRadius1; - } - - public void setForeRadiusAutomatic(boolean auto) { - if (autoRadius1 == auto) - return; - - autoRadius1 = auto; - - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - //////// Aft radius ///////// - - @Override - public double getAftRadius() { - if (isAftRadiusAutomatic()) { - // Return the auto radius from the rear - double r = -1; - SymmetricComponent c = this.getNextSymmetricComponent(); - if (c != null) { - r = c.getRearAutoRadius(); - } - if (r < 0) - r = DEFAULT_RADIUS; - return r; - } - return radius2; - } - - - - public void setAftRadius(double radius) { - if ((this.radius2 == radius) && (autoRadius2 == false)) - return; - - this.autoRadius2 = false; - this.radius2 = Math.max(radius, 0); - - if (this.thickness > this.radius1 && this.thickness > this.radius2) - this.thickness = Math.max(this.radius1, this.radius2); - - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - @Override - public boolean isAftRadiusAutomatic() { - return autoRadius2; - } - - public void setAftRadiusAutomatic(boolean auto) { - if (autoRadius2 == auto) - return; - - autoRadius2 = auto; - - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - //// Radius automatics - - @Override - protected double getFrontAutoRadius() { - if (isAftRadiusAutomatic()) - return -1; - return getAftRadius(); - } - - - @Override - protected double getRearAutoRadius() { - if (isForeRadiusAutomatic()) - return -1; - return getForeRadius(); - } - - - - - //////// Type & shape ///////// - - public Shape getType() { - return type; - } - - public void setType(Shape type) { - if (type == null) { - throw new IllegalArgumentException("setType called with null argument"); - } - if (this.type == type) - return; - this.type = type; - this.clipped = type.isClippable(); - this.shapeParameter = type.defaultParameter(); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public double getShapeParameter() { - return shapeParameter; - } - - public void setShapeParameter(double n) { - if (shapeParameter == n) - return; - this.shapeParameter = MathUtil.clamp(n, type.minParameter(), type.maxParameter()); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public boolean isClipped() { - if (!type.isClippable()) - return false; - return clipped; - } - - public void setClipped(boolean c) { - if (clipped == c) - return; - clipped = c; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public boolean isClippedEnabled() { - return type.isClippable(); - } - - public double getShapeParameterMin() { - return type.minParameter(); - } - - public double getShapeParameterMax() { - return type.maxParameter(); - } - - - //////// Shoulders //////// - - public double getForeShoulderRadius() { - return foreShoulderRadius; - } - - public void setForeShoulderRadius(double foreShoulderRadius) { - if (MathUtil.equals(this.foreShoulderRadius, foreShoulderRadius)) - return; - this.foreShoulderRadius = foreShoulderRadius; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public double getForeShoulderThickness() { - return foreShoulderThickness; - } - - public void setForeShoulderThickness(double foreShoulderThickness) { - if (MathUtil.equals(this.foreShoulderThickness, foreShoulderThickness)) - return; - this.foreShoulderThickness = foreShoulderThickness; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public double getForeShoulderLength() { - return foreShoulderLength; - } - - public void setForeShoulderLength(double foreShoulderLength) { - if (MathUtil.equals(this.foreShoulderLength, foreShoulderLength)) - return; - this.foreShoulderLength = foreShoulderLength; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public boolean isForeShoulderCapped() { - return foreShoulderCapped; - } - - public void setForeShoulderCapped(boolean capped) { - if (this.foreShoulderCapped == capped) - return; - this.foreShoulderCapped = capped; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - public double getAftShoulderRadius() { - return aftShoulderRadius; - } - - public void setAftShoulderRadius(double aftShoulderRadius) { - if (MathUtil.equals(this.aftShoulderRadius, aftShoulderRadius)) - return; - this.aftShoulderRadius = aftShoulderRadius; - clearPreset(); - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public double getAftShoulderThickness() { - return aftShoulderThickness; - } - - public void setAftShoulderThickness(double aftShoulderThickness) { - if (MathUtil.equals(this.aftShoulderThickness, aftShoulderThickness)) - return; - this.aftShoulderThickness = aftShoulderThickness; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public double getAftShoulderLength() { - return aftShoulderLength; - } - - public void setAftShoulderLength(double aftShoulderLength) { - if (MathUtil.equals(this.aftShoulderLength, aftShoulderLength)) - return; - this.aftShoulderLength = aftShoulderLength; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - public boolean isAftShoulderCapped() { - return aftShoulderCapped; - } - - public void setAftShoulderCapped(boolean capped) { - if (this.aftShoulderCapped == capped) - return; - this.aftShoulderCapped = capped; - fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); - } - - - - - /////////// Shape implementations //////////// - - - - /** - * Return the radius at point x of the transition. - */ - @Override - public double getRadius(double x) { - if (x < 0 || x > length) - return 0; - - double r1 = getForeRadius(); - double r2 = getAftRadius(); - - if (r1 == r2) - return r1; - - if (r1 > r2) { - x = length - x; - double tmp = r1; - r1 = r2; - r2 = tmp; - } - - if (isClipped()) { - // Check clip calculation - if (clipLength < 0) - calculateClip(r1, r2); - return type.getRadius(clipLength + x, r2, clipLength + length, shapeParameter); - } else { - // Not clipped - return r1 + type.getRadius(x, r2 - r1, length, shapeParameter); - } - } - - /** - * Numerically solve clipLength from the equation - * r1 == type.getRadius(clipLength,r2,clipLength+length) - * using a binary search. It assumes getOuterRadius() to be monotonically increasing. - */ - private void calculateClip(double r1, double r2) { - double min = 0, max = length; - - if (r1 >= r2) { - double tmp = r1; - r1 = r2; - r2 = tmp; - } - - if (r1 == 0) { - clipLength = 0; - return; - } - - if (length <= 0) { - clipLength = 0; - return; - } - - // Required: - // getR(min,min+length,r2) - r1 < 0 - // getR(max,max+length,r2) - r1 > 0 - - int n = 0; - while (type.getRadius(max, r2, max + length, shapeParameter) - r1 < 0) { - min = max; - max *= 2; - n++; - if (n > 10) - break; - } - - while (true) { - clipLength = (min + max) / 2; - if ((max - min) < CLIP_PRECISION) - return; - double val = type.getRadius(clipLength, r2, clipLength + length, shapeParameter); - if (val - r1 > 0) { - max = clipLength; - } else { - min = clipLength; - } - } - } - - - @Override - public double getInnerRadius(double x) { - return Math.max(getRadius(x) - thickness, 0); - } - - - - @Override - public Collection<Coordinate> getComponentBounds() { - Collection<Coordinate> bounds = super.getComponentBounds(); - if (foreShoulderLength > 0.001) - addBound(bounds, -foreShoulderLength, foreShoulderRadius); - if (aftShoulderLength > 0.001) - addBound(bounds, getLength() + aftShoulderLength, aftShoulderRadius); - return bounds; - } - - @Override - public double getComponentVolume() { - double volume = super.getComponentVolume(); - if (getForeShoulderLength() > 0.001) { - final double or = getForeShoulderRadius(); - final double ir = Math.max(getForeShoulderRadius() - getForeShoulderThickness(), 0); - volume += ringVolume( or, ir, getForeShoulderLength() ); - } - if (isForeShoulderCapped()) { - final double ir = Math.max(getForeShoulderRadius() - getForeShoulderThickness(), 0); - volume += ringVolume(ir, 0, getForeShoulderThickness() ); - } - - if (getAftShoulderLength() > 0.001) { - final double or = getAftShoulderRadius(); - final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); - volume += ringVolume(or, ir, getAftShoulderLength() ); - } - if (isAftShoulderCapped()) { - final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); - volume += ringVolume(ir, 0, getAftShoulderThickness() ); - } - - return volume; - } - - @Override - public Coordinate getComponentCG() { - Coordinate cg = super.getComponentCG(); - if (getForeShoulderLength() > 0.001) { - final double ir = Math.max(getForeShoulderRadius() - getForeShoulderThickness(), 0); - cg = cg.average(ringCG(getForeShoulderRadius(), ir, -getForeShoulderLength(), 0, - getMaterial().getDensity())); - } - if (isForeShoulderCapped()) { - final double ir = Math.max(getForeShoulderRadius() - getForeShoulderThickness(), 0); - cg = cg.average(ringCG(ir, 0, -getForeShoulderLength(), - getForeShoulderThickness() - getForeShoulderLength(), - getMaterial().getDensity())); - } - - if (getAftShoulderLength() > 0.001) { - final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); - cg = cg.average(ringCG(getAftShoulderRadius(), ir, getLength(), - getLength() + getAftShoulderLength(), getMaterial().getDensity())); - } - if (isAftShoulderCapped()) { - final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); - cg = cg.average(ringCG(ir, 0, - getLength() + getAftShoulderLength() - getAftShoulderThickness(), - getLength() + getAftShoulderLength(), getMaterial().getDensity())); - } - return cg; - } - - - /* - * The moments of inertia are not explicitly corrected for the shoulders. - * However, since the mass is corrected, the inertia is automatically corrected - * to very nearly the correct value. - */ - - - - /** - * Returns the name of the component ("Transition"). - */ - @Override - public String getComponentName() { - //// Transition - return trans.get("Transition.Transition"); - } - - @Override - protected void componentChanged(ComponentChangeEvent e) { - super.componentChanged(e); - clipLength = -1; - } - - /** - * Check whether the given type can be added to this component. Transitions allow any - * InternalComponents to be added. - * - * @param ctype The RocketComponent class type to add. - * @return Whether such a component can be added. - */ - @Override - public boolean isCompatible(Class<? extends RocketComponent> ctype) { - if (InternalComponent.class.isAssignableFrom(ctype)) - return true; - return false; - } - - @Override - public Type getPresetType() { - return ComponentPreset.Type.TRANSITION; - } - - - @Override - protected void loadFromPreset(ComponentPreset preset) { - - boolean presetFilled = false; - if ( preset.has(ComponentPreset.FILLED ) ) { - presetFilled = preset.get( ComponentPreset.FILLED); - } - - if ( preset.has(ComponentPreset.SHAPE) ) { - Shape s = preset.get(ComponentPreset.SHAPE); - this.setType(s); - } - if ( preset.has(ComponentPreset.AFT_OUTER_DIAMETER) ) { - double outerDiameter = preset.get(ComponentPreset.AFT_OUTER_DIAMETER); - this.setAftRadiusAutomatic(false); - this.setAftRadius(outerDiameter/2.0); - } - if ( preset.has(ComponentPreset.AFT_SHOULDER_LENGTH) ) { - double d = preset.get(ComponentPreset.AFT_SHOULDER_LENGTH); - this.setAftShoulderLength(d); - } - if ( preset.has(ComponentPreset.AFT_SHOULDER_DIAMETER) ) { - double d = preset.get(ComponentPreset.AFT_SHOULDER_DIAMETER); - this.setAftShoulderRadius(d/2.0); - if ( presetFilled ) { - this.setAftShoulderThickness(d/2.0); - } - } - if ( preset.has(ComponentPreset.FORE_OUTER_DIAMETER) ) { - double outerDiameter = preset.get(ComponentPreset.FORE_OUTER_DIAMETER); - this.setForeRadiusAutomatic(false); - this.setForeRadius(outerDiameter/2.0); - } - if ( preset.has(ComponentPreset.FORE_SHOULDER_LENGTH) ) { - double d = preset.get(ComponentPreset.FORE_SHOULDER_LENGTH); - this.setForeShoulderLength(d); - } - if ( preset.has(ComponentPreset.FORE_SHOULDER_DIAMETER) ) { - double d = preset.get(ComponentPreset.FORE_SHOULDER_DIAMETER); - this.setForeShoulderRadius(d/2.0); - if ( presetFilled ) { - this.setForeShoulderThickness(d/2.0); - } - } - - super.loadFromPreset(preset); - - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - - } - - /** - * An enumeration listing the possible shapes of transitions. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - public static enum Shape { - - /** - * Conical shape. - */ - //// Conical - CONICAL(trans.get("Shape.Conical"), - //// A conical nose cone has a profile of a triangle. - trans.get("Shape.Conical.desc1"), - //// A conical transition has straight sides. - trans.get("Shape.Conical.desc2")) { - @Override - public double getRadius(double x, double radius, double length, double param) { - assert x >= 0; - assert x <= length; - assert radius >= 0; - return radius * x / length; - } - }, - - /** - * Ogive shape. The shape parameter is the portion of an extended tangent ogive - * that will be used. That is, for param==1 a tangent ogive will be produced, and - * for smaller values the shape straightens out into a cone at param==0. - */ - //// Ogive - OGIVE(trans.get("Shape.Ogive"), - //// An ogive nose cone has a profile that is a segment of a circle. The shape parameter value 1 produces a <b>tangent ogive</b>, which has a smooth transition to the body tube, values less than 1 produce <b>secant ogives</b>. - trans.get("Shape.Ogive.desc1"), - //// An ogive transition has a profile that is a segment of a circle. The shape parameter value 1 produces a <b>tangent ogive</b>, which has a smooth transition to the body tube at the aft end, values less than 1 produce <b>secant ogives</b>. - trans.get("Shape.Ogive.desc2")) { - @Override - public boolean usesParameter() { - return true; // Range 0...1 is default - } - - @Override - public double defaultParameter() { - return 1.0; // Tangent ogive by default - } - - @Override - public double getRadius(double x, double radius, double length, double param) { - assert x >= 0; - assert x <= length; - assert radius >= 0; - assert param >= 0; - assert param <= 1; - - // Impossible to calculate ogive for length < radius, scale instead - // TODO: LOW: secant ogive could be calculated lower - if (length < radius) { - x = x * radius / length; - length = radius; - } - - if (param < 0.001) - return CONICAL.getRadius(x, radius, length, param); - - // Radius of circle is: - double R = MathUtil.safeSqrt((pow2(length) + pow2(radius)) * - (pow2((2 - param) * length) + pow2(param * radius)) / (4 * pow2(param * radius))); - double L = length / param; - // double R = (radius + length*length/(radius*param*param))/2; - double y0 = MathUtil.safeSqrt(R * R - L * L); - return MathUtil.safeSqrt(R * R - (L - x) * (L - x)) - y0; - } - }, - - /** - * Ellipsoidal shape. - */ - //// Ellipsoid - ELLIPSOID(trans.get("Shape.Ellipsoid"), - //// An ellipsoidal nose cone has a profile of a half-ellipse with major axes of lengths 2×<i>Length</i> and <i>Diameter</i>. - trans.get("Shape.Ellipsoid.desc1"), - //// An ellipsoidal transition has a profile of a half-ellipse with major axes of lengths 2×<i>Length</i> and <i>Diameter</i>. If the transition is not clipped, then the profile is extended at the center by the corresponding radius. - trans.get("Shape.Ellipsoid.desc2"), true) { - @Override - public double getRadius(double x, double radius, double length, double param) { - assert x >= 0; - assert x <= length; - assert radius >= 0; - x = x * radius / length; - return MathUtil.safeSqrt(2 * radius * x - x * x); // radius/length * sphere - } - }, - - //// Power series - POWER(trans.get("Shape.Powerseries"), - trans.get("Shape.Powerseries.desc1"), - trans.get("Shape.Powerseries.desc2"), true) { - @Override - public boolean usesParameter() { // Range 0...1 - return true; - } - - @Override - public double defaultParameter() { - return 0.5; - } - - @Override - public double getRadius(double x, double radius, double length, double param) { - assert x >= 0; - assert x <= length; - assert radius >= 0; - assert param >= 0; - assert param <= 1; - if (param <= 0.00001) { - if (x <= 0.00001) - return 0; - else - return radius; - } - return radius * Math.pow(x / length, param); - } - - }, - - //// Parabolic series - PARABOLIC(trans.get("Shape.Parabolicseries"), - ////A parabolic series nose cone has a profile of a parabola. The shape parameter defines the segment of the parabola to utilize. The shape parameter 1.0 produces a <b>full parabola</b> which is tangent to the body tube, 0.75 produces a <b>3/4 parabola</b>, 0.5 procudes a <b>1/2 parabola</b> and 0 produces a <b>conical</b> nose cone. - trans.get("Shape.Parabolicseries.desc1"), - ////A parabolic series transition has a profile of a parabola. The shape parameter defines the segment of the parabola to utilize. The shape parameter 1.0 produces a <b>full parabola</b> which is tangent to the body tube at the aft end, 0.75 produces a <b>3/4 parabola</b>, 0.5 procudes a <b>1/2 parabola</b> and 0 produces a <b>conical</b> transition. - trans.get("Shape.Parabolicseries.desc2")) { - - // In principle a parabolic transition is clippable, but the difference is - // negligible. - - @Override - public boolean usesParameter() { // Range 0...1 - return true; - } - - @Override - public double defaultParameter() { - return 1.0; - } - - @Override - public double getRadius(double x, double radius, double length, double param) { - assert x >= 0; - assert x <= length; - assert radius >= 0; - assert param >= 0; - assert param <= 1; - - return radius * ((2 * x / length - param * pow2(x / length)) / (2 - param)); - } - }, - - //// Haack series - HAACK(trans.get("Shape.Haackseries"), - //// The Haack series nose cones are designed to minimize drag. The shape parameter 0 produces an <b>LD-Haack</b> or <b>Von Karman</b> nose cone, which minimizes drag for fixed length and diameter, while a value of 0.333 produces an <b>LV-Haack</b> nose cone, which minimizes drag for fixed length and volume. - trans.get("Shape.Haackseries.desc1"), - //// The Haack series <i>nose cones</i> are designed to minimize drag. These transition shapes are their equivalents, but do not necessarily produce optimal drag for transitions. The shape parameter 0 produces an <b>LD-Haack</b> or <b>Von Karman</b> shape, while a value of 0.333 produces an <b>LV-Haack</b> shape. - trans.get("Shape.Haackseries.desc2"), true) { - - @Override - public boolean usesParameter() { - return true; - } - - @Override - public double maxParameter() { - return 1.0 / 3.0; // Range 0...1/3 - } - - @Override - public double getRadius(double x, double radius, double length, double param) { - assert x >= 0; - assert x <= length; - assert radius >= 0; - assert param >= 0; - assert param <= 2; - - double theta = Math.acos(1 - 2 * x / length); - if (MathUtil.equals(param, 0)) { - return radius * MathUtil.safeSqrt((theta - sin(2 * theta) / 2) / Math.PI); - } - return radius * MathUtil.safeSqrt((theta - sin(2 * theta) / 2 + param * pow3(sin(theta))) / Math.PI); - } - }, - - // POLYNOMIAL("Smooth polynomial", - // "A polynomial is fitted such that the nose cone profile is horizontal "+ - // "at the aft end of the transition. The angle at the tip is defined by "+ - // "the shape parameter.", - // "A polynomial is fitted such that the transition profile is horizontal "+ - // "at the aft end of the transition. The angle at the fore end is defined "+ - // "by the shape parameter.") { - // @Override - // public boolean usesParameter() { - // return true; - // } - // @Override - // public double maxParameter() { - // return 3.0; // Range 0...3 - // } - // @Override - // public double defaultParameter() { - // return 0.0; - // } - // public double getRadius(double x, double radius, double length, double param) { - // assert x >= 0; - // assert x <= length; - // assert radius >= 0; - // assert param >= 0; - // assert param <= 3; - // // p(x) = (k-2)x^3 + (3-2k)x^2 + k*x - // x = x/length; - // return radius*((((param-2)*x + (3-2*param))*x + param)*x); - // } - // } - ; - - // Privete fields of the shapes - private final String name; - private final String transitionDesc; - private final String noseconeDesc; - private final boolean canClip; - - // Non-clippable constructor - Shape(String name, String noseconeDesc, String transitionDesc) { - this(name, noseconeDesc, transitionDesc, false); - } - - // Clippable constructor - Shape(String name, String noseconeDesc, String transitionDesc, boolean canClip) { - this.name = name; - this.canClip = canClip; - this.noseconeDesc = noseconeDesc; - this.transitionDesc = transitionDesc; - } - - - /** - * Return the name of the transition shape name. - */ - public String getName() { - return name; - } - - /** - * Get a description of the Transition shape. - */ - public String getTransitionDescription() { - return transitionDesc; - } - - /** - * Get a description of the NoseCone shape. - */ - public String getNoseConeDescription() { - return noseconeDesc; - } - - /** - * Check whether the shape differs in clipped mode. The clipping should be - * enabled by default if possible. - */ - public boolean isClippable() { - return canClip; - } - - /** - * Return whether the shape uses the shape parameter. (Default false.) - */ - public boolean usesParameter() { - return false; - } - - /** - * Return the minimum value of the shape parameter. (Default 0.) - */ - public double minParameter() { - return 0.0; - } - - /** - * Return the maximum value of the shape parameter. (Default 1.) - */ - public double maxParameter() { - return 1.0; - } - - /** - * Return the default value of the shape parameter. (Default 0.) - */ - public double defaultParameter() { - return 0.0; - } - - /** - * Calculate the basic radius of a transition with the given radius, length and - * shape parameter at the point x from the tip of the component. It is assumed - * that the fore radius if zero and the aft radius is <code>radius >= 0</code>. - * Boattails are achieved by reversing the component. - * - * @param x Position from the tip of the component. - * @param radius Aft end radius >= 0. - * @param length Length of the transition >= 0. - * @param param Valid shape parameter. - * @return The basic radius at the given position. - */ - public abstract double getRadius(double x, double radius, double length, double param); - - - /** - * Returns the name of the shape (same as getName()). - */ - @Override - public String toString() { - return name; - } - - /** - * Lookup the Shape given the localized name. This differs from the standard valueOf as that looks up - * based on the canonical name, not the localized name which is an instance var. - * - * @param localizedName - * @return - */ - public static Shape toShape(String localizedName) { - Shape[] values = Shape.values(); - for (Shape value : values) { - if (value.getName().equals(localizedName)) { - return value; - } - } - return null; - } - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/TrapezoidFinSet.java b/core/src/net/sf/openrocket/rocketcomponent/TrapezoidFinSet.java deleted file mode 100644 index 24c773e5..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/TrapezoidFinSet.java +++ /dev/null @@ -1,185 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -import java.util.ArrayList; -import java.util.List; - -/** - * A set of trapezoidal fins. The root and tip chords are perpendicular to the rocket - * base line, while the leading and aft edges may be slanted. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - -public class TrapezoidFinSet extends FinSet { - private static final Translator trans = Application.getTranslator(); - - public static final double MAX_SWEEP_ANGLE = (89 * Math.PI / 180.0); - - /* - * sweep tipChord - * | |___________ - * | / | - * | / | - * | / | height - * / | - * __________/________________|_____________ - * length - * == rootChord - */ - - // rootChord == length - private double tipChord = 0; - private double height = 0; - private double sweep = 0; - - - public TrapezoidFinSet() { - this(3, 0.05, 0.05, 0.025, 0.03); - } - - // TODO: HIGH: height=0 -> CP = NaN - public TrapezoidFinSet(int fins, double rootChord, double tipChord, double sweep, - double height) { - super(); - - this.setFinCount(fins); - this.length = rootChord; - this.tipChord = tipChord; - this.sweep = sweep; - this.height = height; - } - - - public void setFinShape(double rootChord, double tipChord, double sweep, double height, - double thickness) { - if (this.length == rootChord && this.tipChord == tipChord && this.sweep == sweep && - this.height == height && this.thickness == thickness) - return; - this.length = rootChord; - this.tipChord = tipChord; - this.sweep = sweep; - this.height = height; - this.thickness = thickness; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public double getRootChord() { - return length; - } - - public void setRootChord(double r) { - if (length == r) - return; - length = Math.max(r, 0); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - public double getTipChord() { - return tipChord; - } - - public void setTipChord(double r) { - if (tipChord == r) - return; - tipChord = Math.max(r, 0); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - /** - * Get the sweep length. - */ - public double getSweep() { - return sweep; - } - - /** - * Set the sweep length. - */ - public void setSweep(double r) { - if (sweep == r) - return; - sweep = r; - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - /** - * Get the sweep angle. This is calculated from the true sweep and height, and is not - * stored separately. - */ - public double getSweepAngle() { - if (height == 0) { - if (sweep > 0) - return Math.PI / 2; - if (sweep < 0) - return -Math.PI / 2; - return 0; - } - return Math.atan(sweep / height); - } - - /** - * Sets the sweep by the sweep angle. The sweep is calculated and set by this method, - * and the angle itself is not stored. - */ - public void setSweepAngle(double r) { - if (r > MAX_SWEEP_ANGLE) - r = MAX_SWEEP_ANGLE; - if (r < -MAX_SWEEP_ANGLE) - r = -MAX_SWEEP_ANGLE; - double sweep = Math.tan(r) * height; - if (Double.isNaN(sweep) || Double.isInfinite(sweep)) - return; - setSweep(sweep); - } - - public double getHeight() { - return height; - } - - public void setHeight(double r) { - if (height == r) - return; - height = Math.max(r, 0); - fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); - } - - - - /** - * Returns the geometry of a trapezoidal fin. - */ - @Override - public Coordinate[] getFinPoints() { - List<Coordinate> list = new ArrayList<Coordinate>(4); - - list.add(Coordinate.NUL); - list.add(new Coordinate(sweep, height)); - if (tipChord > 0.0001) { - list.add(new Coordinate(sweep + tipChord, height)); - } - list.add(new Coordinate(MathUtil.max(length, 0.0001), 0)); - - return list.toArray(new Coordinate[list.size()]); - } - - /** - * Returns the span of a trapezoidal fin. - */ - @Override - public double getSpan() { - return height; - } - - - @Override - public String getComponentName() { - //// Trapezoidal fin set - return trans.get("TrapezoidFinSet.TrapezoidFinSet"); - } - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/TubeCoupler.java b/core/src/net/sf/openrocket/rocketcomponent/TubeCoupler.java deleted file mode 100644 index 4f50099c..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/TubeCoupler.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPreset.Type; -import net.sf.openrocket.startup.Application; - - -public class TubeCoupler extends ThicknessRingComponent implements RadialParent { - private static final Translator trans = Application.getTranslator(); - - public TubeCoupler() { - setOuterRadiusAutomatic(true); - setThickness(0.002); - setLength(0.06); - } - - @Override - public Type getPresetType() { - return ComponentPreset.Type.TUBE_COUPLER; - } - - - // Make setter visible - @Override - public void setOuterRadiusAutomatic(boolean auto) { - super.setOuterRadiusAutomatic(auto); - } - - - @Override - public String getComponentName() { - //// Tube coupler - return trans.get("TubeCoupler.TubeCoupler"); - } - - @Override - public boolean allowsChildren() { - return true; - } - - /** - * Allow all InternalComponents to be added to this component. - */ - @Override - public boolean isCompatible(Class<? extends RocketComponent> type) { - return InternalComponent.class.isAssignableFrom(type); - } - - - @Override - public double getInnerRadius(double x) { - return getInnerRadius(); - } - - - @Override - public double getOuterRadius(double x) { - return getOuterRadius(); - } -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Visitable.java b/core/src/net/sf/openrocket/rocketcomponent/Visitable.java deleted file mode 100644 index 5f46b7ff..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Visitable.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Visitable.java - */ -package net.sf.openrocket.rocketcomponent; - -/** - * This interface describes a portion of the Visitor pattern, using generics to assure type-safety. - * The elements of the concrete object hierarchy are only visitable by an associated hierarchy of visitors, - * while these visitors are only able to visit the elements of that hierarchy. - * - * The key concept regarding the Visitor pattern is to realize that Java will only "discriminate" the type of an - * object being called, not the type of an object being passed. - * - * In order for the type of two objects to be determinable to the JVM, each object must be the receiver of an - * invocation. Here, when accept is called on a Visitable, the concrete type of the Visitable becomes "known" but the - * concrete type of the argument is still unknown. <code>visit</code> is then called on the parameter object, passing - * the Visitable back, which has type and identity. Flow of control has now been 'double-dispatched' such that the - * type (and identity) of both objects are known. - * - * Specifically, this interface is to be implemented by every class in the RocketComponent hierarchy that - * can be visited AND which are sufficiently specialized from their super class. If they only provide - * constraints to their superclass (such as TubeCoupler), then the implementation of this interface at - * the superclass level is sufficient. - * - * Admittedly, the syntax is a bit contorted here, as it is necessarily self-referential for type-safety. - * - * <V> The visitor type - * <T> The visitable (the concrete class that implements this interface) - */ -public interface Visitable<V extends Visitor<V, T>, T extends Visitable<V, T>> { - - /** - * Any class in the hierarchy that allows itself to be visited will implement this method. The normal - * behavior is that the visitor will invoke this method of a Visitable, passing itself. The Visitable - * turns around calls the Visitor back. This idiom is also known as 'double-dispatching'. - * - * @param visitor the visitor that will be called back - */ - public void accept(V visitor); - -} diff --git a/core/src/net/sf/openrocket/rocketcomponent/Visitor.java b/core/src/net/sf/openrocket/rocketcomponent/Visitor.java deleted file mode 100644 index edb39f2b..00000000 --- a/core/src/net/sf/openrocket/rocketcomponent/Visitor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Visitor.java - */ -package net.sf.openrocket.rocketcomponent; - -/** - * This interface describes a portion of the Visitor pattern, using generics to assure type-safety. - * The elements of the concrete object hierarchy are only visitable by an associated hierarchy of visitors, - * while these visitors are only able to visit the elements of that hierarchy. - * - * The key concept regarding the Visitor pattern is to realize that Java will only "discriminate" the type of an - * object being called, not the type of an object being passed. - * - * In order for the type of two objects to be determinable to the JVM, each object must be the receiver of an - * invocation. Here, when accept is called on a Visitable, the concrete type of the Visitable becomes "known" but the - * concrete type of the argument is still unknown. <code>visit</code> is then called on the parameter object, passing - * the Visitable back, which has type and identity. Flow of control has now been 'double-dispatched' such that the - * type (and identity) of both objects are known. - * - * Specifically, this interface is to be implemented by every class in the RocketComponent hierarchy that - * can be visited AND which are sufficiently specialized from their super class. If they only provide - * constraints to their superclass (such as TubeCoupler), then the implementation of this interface at - * the superclass level is sufficient. - * - * Admittedly, the syntax is a bit contorted here, as it is necessarily self-referential for type-safety. - * - * <V> The visitor type (the concrete class that implements this interface) - * <T> The visitable - */ -public interface Visitor<V extends Visitor<V, T>, T extends Visitable<V, T>> { - - /** - * The callback method. This method is the 2nd leg of the double-dispatch, having been invoked from a - * corresponding <code>accept</code>. - * - * @param visitable the instance of the Visitable (the target of what is being visiting) - */ - void visit(T visitable); -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java b/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java deleted file mode 100644 index 0aab853a..00000000 --- a/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java +++ /dev/null @@ -1,234 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.motor.MotorInstanceConfiguration; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.SimulationListenerHelper; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Quaternion; - -public abstract class AbstractSimulationStepper implements SimulationStepper { - - /** - * Compute the atmospheric conditions, allowing listeners to override. - * - * @param status the simulation status - * @return the atmospheric conditions to use - * @throws SimulationException if a listener throws SimulationException - */ - protected AtmosphericConditions modelAtmosphericConditions(SimulationStatus status) throws SimulationException { - AtmosphericConditions conditions; - - // Call pre-listener - conditions = SimulationListenerHelper.firePreAtmosphericModel(status); - if (conditions != null) { - return conditions; - } - - // Compute conditions - double altitude = status.getRocketPosition().z + status.getSimulationConditions().getLaunchSite().getAltitude(); - conditions = status.getSimulationConditions().getAtmosphericModel().getConditions(altitude); - - // Call post-listener - conditions = SimulationListenerHelper.firePostAtmosphericModel(status, conditions); - - checkNaN(conditions.getPressure()); - checkNaN(conditions.getTemperature()); - - return conditions; - } - - - - /** - * Compute the wind to use, allowing listeners to override. - * - * @param status the simulation status - * @return the wind conditions to use - * @throws SimulationException if a listener throws SimulationException - */ - protected Coordinate modelWindVelocity(SimulationStatus status) throws SimulationException { - Coordinate wind; - - // Call pre-listener - wind = SimulationListenerHelper.firePreWindModel(status); - if (wind != null) { - return wind; - } - - // Compute conditions - double altitude = status.getRocketPosition().z + status.getSimulationConditions().getLaunchSite().getAltitude(); - wind = status.getSimulationConditions().getWindModel().getWindVelocity(status.getSimulationTime(), altitude); - - // Call post-listener - wind = SimulationListenerHelper.firePostWindModel(status, wind); - - checkNaN(wind); - - return wind; - } - - - - /** - * Compute the gravity to use, allowing listeners to override. - * - * @param status the simulation status - * @return the gravitational acceleration to use - * @throws SimulationException if a listener throws SimulationException - */ - protected double modelGravity(SimulationStatus status) throws SimulationException { - double gravity; - - // Call pre-listener - gravity = SimulationListenerHelper.firePreGravityModel(status); - if (!Double.isNaN(gravity)) { - return gravity; - } - - // Compute conditions - gravity = status.getSimulationConditions().getGravityModel().getGravity(status.getRocketWorldPosition()); - - // Call post-listener - gravity = SimulationListenerHelper.firePostGravityModel(status, gravity); - - checkNaN(gravity); - - return gravity; - } - - - - /** - * Compute the mass data to use, allowing listeners to override. - * - * @param status the simulation status - * @return the mass data to use - * @throws SimulationException if a listener throws SimulationException - */ - protected MassData calculateMassData(SimulationStatus status) throws SimulationException { - MassData mass; - Coordinate cg; - double longitudinalInertia, rotationalInertia, propellantMass; - - // Call pre-listener - mass = SimulationListenerHelper.firePreMassCalculation(status); - if (mass != null) { - return mass; - } - - MassCalculator calc = status.getSimulationConditions().getMassCalculator(); - cg = calc.getCG(status.getConfiguration(), status.getMotorConfiguration()); - longitudinalInertia = calc.getLongitudinalInertia(status.getConfiguration(), status.getMotorConfiguration()); - rotationalInertia = calc.getRotationalInertia(status.getConfiguration(), status.getMotorConfiguration()); - propellantMass = calc.getPropellantMass(status.getConfiguration(), status.getMotorConfiguration()); - mass = new MassData(cg, longitudinalInertia, rotationalInertia, propellantMass); - - // Call post-listener - mass = SimulationListenerHelper.firePostMassCalculation(status, mass); - - checkNaN(mass.getCG()); - checkNaN(mass.getLongitudinalInertia()); - checkNaN(mass.getRotationalInertia()); - checkNaN(mass.getPropellantMass()); - - return mass; - } - - - - - - /** - * Calculate the average thrust produced by the motors in the current configuration, allowing - * listeners to override. The average is taken between <code>status.time</code> and - * <code>status.time + timestep</code>. - * <p> - * TODO: HIGH: This method does not take into account any moments generated by off-center motors. - * - * @param status the current simulation status. - * @param timestep the time step of the current iteration. - * @param acceleration the current (approximate) acceleration - * @param atmosphericConditions the current atmospheric conditions - * @param stepMotors whether to step the motors forward or work on a clone object - * @return the average thrust during the time step. - */ - protected double calculateThrust(SimulationStatus status, double timestep, - double acceleration, AtmosphericConditions atmosphericConditions, - boolean stepMotors) throws SimulationException { - double thrust; - - // Pre-listeners - thrust = SimulationListenerHelper.firePreThrustCalculation(status); - if (!Double.isNaN(thrust)) { - return thrust; - } - - Configuration configuration = status.getConfiguration(); - - // Iterate over the motors and calculate combined thrust - MotorInstanceConfiguration mic = status.getMotorConfiguration(); - if (!stepMotors) { - mic = mic.clone(); - } - mic.step(status.getSimulationTime() + timestep, acceleration, atmosphericConditions); - thrust = 0; - for (MotorId id : mic.getMotorIDs()) { - if (configuration.isComponentActive((RocketComponent) mic.getMotorMount(id))) { - MotorInstance motor = mic.getMotorInstance(id); - thrust += motor.getThrust(); - } - } - - // Post-listeners - thrust = SimulationListenerHelper.firePostThrustCalculation(status, thrust); - - checkNaN(thrust); - - return thrust; - } - - - /** - * Check that the provided value is not NaN. - * - * @param d the double value to check. - * @throws BugException if the value is NaN. - */ - protected void checkNaN(double d) { - if (Double.isNaN(d)) { - throw new BugException("Simulation resulted in not-a-number (NaN) value, please report a bug."); - } - } - - /** - * Check that the provided coordinate is not NaN. - * - * @param c the coordinate value to check. - * @throws BugException if the value is NaN. - */ - protected void checkNaN(Coordinate c) { - if (c.isNaN()) { - throw new BugException("Simulation resulted in not-a-number (NaN) value, please report a bug, c=" + c); - } - } - - - /** - * Check that the provided quaternion is not NaN. - * - * @param q the quaternion value to check. - * @throws BugException if the value is NaN. - */ - protected void checkNaN(Quaternion q) { - if (q.isNaN()) { - throw new BugException("Simulation resulted in not-a-number (NaN) value, please report a bug, q=" + q); - } - } -} diff --git a/core/src/net/sf/openrocket/simulation/AccelerationData.java b/core/src/net/sf/openrocket/simulation/AccelerationData.java deleted file mode 100644 index 31d19ba9..00000000 --- a/core/src/net/sf/openrocket/simulation/AccelerationData.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Quaternion; - -public final class AccelerationData { - - private Coordinate linearAccelerationRC; - private Coordinate rotationalAccelerationRC; - private Coordinate linearAccelerationWC; - private Coordinate rotationalAccelerationWC; - // Rotates from rocket coordinates to world coordinates - private final Quaternion rotation; - - - public AccelerationData(Coordinate linearAccelerationRC, Coordinate rotationalAccelerationRC, - Coordinate linearAccelerationWC, Coordinate rotationalAccelerationWC, - Quaternion rotation) { - - if ((linearAccelerationRC == null && linearAccelerationWC == null) || - (rotationalAccelerationRC == null && rotationalAccelerationWC == null) || - rotation == null) { - throw new IllegalArgumentException("Parameter is null: " + - " linearAccelerationRC=" + linearAccelerationRC + - " linearAccelerationWC=" + linearAccelerationWC + - " rotationalAccelerationRC=" + rotationalAccelerationRC + - " rotationalAccelerationWC=" + rotationalAccelerationWC + - " rotation=" + rotation); - } - this.linearAccelerationRC = linearAccelerationRC; - this.rotationalAccelerationRC = rotationalAccelerationRC; - this.linearAccelerationWC = linearAccelerationWC; - this.rotationalAccelerationWC = rotationalAccelerationWC; - this.rotation = rotation; - } - - - - - public Coordinate getLinearAccelerationRC() { - if (linearAccelerationRC == null) { - linearAccelerationRC = rotation.invRotate(linearAccelerationWC); - } - return linearAccelerationRC; - } - - public Coordinate getRotationalAccelerationRC() { - if (rotationalAccelerationRC == null) { - rotationalAccelerationRC = rotation.invRotate(rotationalAccelerationWC); - } - return rotationalAccelerationRC; - } - - public Coordinate getLinearAccelerationWC() { - if (linearAccelerationWC == null) { - linearAccelerationWC = rotation.rotate(linearAccelerationRC); - } - return linearAccelerationWC; - } - - public Coordinate getRotationalAccelerationWC() { - if (rotationalAccelerationWC == null) { - rotationalAccelerationWC = rotation.rotate(rotationalAccelerationRC); - } - return rotationalAccelerationWC; - } - - public Quaternion getRotation() { - return rotation; - } - - - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof AccelerationData)) - return false; - AccelerationData other = (AccelerationData) obj; - return (this.getLinearAccelerationRC().equals(other.getLinearAccelerationRC()) && - this.getRotationalAccelerationRC().equals(other.getRotationalAccelerationRC())); - } - - @Override - public int hashCode() { - return getLinearAccelerationRC().hashCode() ^ getRotationalAccelerationRC().hashCode(); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java b/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java deleted file mode 100644 index 17352062..00000000 --- a/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java +++ /dev/null @@ -1,584 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.motor.MotorInstanceConfiguration; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.simulation.exception.MotorIgnitionException; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.exception.SimulationLaunchException; -import net.sf.openrocket.simulation.listeners.SimulationListenerHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Pair; -import net.sf.openrocket.util.Quaternion; - - -public class BasicEventSimulationEngine implements SimulationEngine { - - private static final Translator trans = Application.getTranslator(); - private static final LogHelper log = Application.getLogger(); - - // TODO: MEDIUM: Allow selecting steppers - private SimulationStepper flightStepper = new RK4SimulationStepper(); - private SimulationStepper landingStepper = new BasicLandingStepper(); - - private SimulationStepper currentStepper; - - private SimulationStatus status; - - - @Override - public FlightData simulate(SimulationConditions simulationConditions) throws SimulationException { - Set<MotorId> motorBurntOut = new HashSet<MotorId>(); - - // Set up flight data - FlightData flightData = new FlightData(); - - // Set up rocket configuration - Configuration configuration = setupConfiguration(simulationConditions); - MotorInstanceConfiguration motorConfiguration = setupMotorConfiguration(configuration); - if (motorConfiguration.getMotorIDs().isEmpty()) { - throw new MotorIgnitionException("No motors defined in the simulation."); - } - - // Initialize the simulation - currentStepper = flightStepper; - status = initialStatus(configuration, motorConfiguration, simulationConditions, flightData); - status = currentStepper.initialize(status); - - - SimulationListenerHelper.fireStartSimulation(status); - // Get originating position (in case listener has modified launch position) - Coordinate origin = status.getRocketPosition(); - Coordinate originVelocity = status.getRocketVelocity(); - - try { - double maxAlt = Double.NEGATIVE_INFINITY; - - // Start the simulation - while (handleEvents()) { - - // Take the step - double oldAlt = status.getRocketPosition().z; - - if (SimulationListenerHelper.firePreStep(status)) { - // Step at most to the next event - double maxStepTime = Double.MAX_VALUE; - FlightEvent nextEvent = status.getEventQueue().peek(); - if (nextEvent != null) { - maxStepTime = MathUtil.max(nextEvent.getTime() - status.getSimulationTime(), 0.001); - } - log.verbose("BasicEventSimulationEngine: Taking simulation step at t=" + status.getSimulationTime()); - currentStepper.step(status, maxStepTime); - } - SimulationListenerHelper.firePostStep(status); - - - // Check for NaN values in the simulation status - checkNaN(); - - // Add altitude event - addEvent(new FlightEvent(FlightEvent.Type.ALTITUDE, status.getSimulationTime(), - status.getConfiguration().getRocket(), - new Pair<Double, Double>(oldAlt, status.getRocketPosition().z))); - - if (status.getRocketPosition().z > maxAlt) { - maxAlt = status.getRocketPosition().z; - } - - - // Position relative to start location - Coordinate relativePosition = status.getRocketPosition().sub(origin); - - // Add appropriate events - if (!status.isLiftoff()) { - - // Avoid sinking into ground before liftoff - if (relativePosition.z < 0) { - status.setRocketPosition(origin); - status.setRocketVelocity(originVelocity); - } - // Detect lift-off - if (relativePosition.z > 0.02) { - addEvent(new FlightEvent(FlightEvent.Type.LIFTOFF, status.getSimulationTime())); - } - - } else { - - // Check ground hit after liftoff - if (status.getRocketPosition().z < 0) { - status.setRocketPosition(status.getRocketPosition().setZ(0)); - addEvent(new FlightEvent(FlightEvent.Type.GROUND_HIT, status.getSimulationTime())); - addEvent(new FlightEvent(FlightEvent.Type.SIMULATION_END, status.getSimulationTime())); - } - - } - - // Check for launch guide clearance - if (!status.isLaunchRodCleared() && - relativePosition.length() > status.getSimulationConditions().getLaunchRodLength()) { - addEvent(new FlightEvent(FlightEvent.Type.LAUNCHROD, status.getSimulationTime(), null)); - } - - - // Check for apogee - if (!status.isApogeeReached() && status.getRocketPosition().z < maxAlt - 0.01) { - addEvent(new FlightEvent(FlightEvent.Type.APOGEE, status.getSimulationTime(), - status.getConfiguration().getRocket())); - } - - - // Check for burnt out motors - for (MotorId motorId : status.getMotorConfiguration().getMotorIDs()) { - MotorInstance motor = status.getMotorConfiguration().getMotorInstance(motorId); - if (!motor.isActive() && motorBurntOut.add(motorId)) { - addEvent(new FlightEvent(FlightEvent.Type.BURNOUT, status.getSimulationTime(), - (RocketComponent) status.getMotorConfiguration().getMotorMount(motorId), motorId)); - } - } - - } - - } catch (SimulationException e) { - SimulationListenerHelper.fireEndSimulation(status, e); - throw e; - } - - SimulationListenerHelper.fireEndSimulation(status, null); - - flightData.addBranch(status.getFlightData()); - - if (!flightData.getWarningSet().isEmpty()) { - log.info("Warnings at the end of simulation: " + flightData.getWarningSet()); - } - - // TODO: HIGH: Simulate branches - return flightData; - } - - - - private SimulationStatus initialStatus(Configuration configuration, - MotorInstanceConfiguration motorConfiguration, - SimulationConditions simulationConditions, FlightData flightData) { - - SimulationStatus init = new SimulationStatus(); - init.setSimulationConditions(simulationConditions); - init.setConfiguration(configuration); - init.setMotorConfiguration(motorConfiguration); - - init.setSimulationTime(0); - init.setPreviousTimeStep(simulationConditions.getTimeStep()); - init.setRocketPosition(Coordinate.NUL); - init.setRocketVelocity(Coordinate.NUL); - init.setRocketWorldPosition(simulationConditions.getLaunchSite()); - - // Initialize to roll angle with least stability w.r.t. the wind - Quaternion o; - FlightConditions cond = new FlightConditions(configuration); - simulationConditions.getAerodynamicCalculator().getWorstCP(configuration, cond, null); - double angle = -cond.getTheta() - simulationConditions.getLaunchRodDirection(); - o = Quaternion.rotation(new Coordinate(0, 0, angle)); - - // Launch rod angle and direction - o = o.multiplyLeft(Quaternion.rotation(new Coordinate(0, simulationConditions.getLaunchRodAngle(), 0))); - o = o.multiplyLeft(Quaternion.rotation(new Coordinate(0, 0, simulationConditions.getLaunchRodDirection()))); - - init.setRocketOrientationQuaternion(o); - init.setRocketRotationVelocity(Coordinate.NUL); - - - /* - * Calculate the effective launch rod length taking into account launch lugs. - * If no lugs are found, assume a tower launcher of full length. - */ - double length = simulationConditions.getLaunchRodLength(); - double lugPosition = Double.NaN; - for (RocketComponent c : configuration) { - if (c instanceof LaunchLug) { - double pos = c.toAbsolute(new Coordinate(c.getLength()))[0].x; - if (Double.isNaN(lugPosition) || pos > lugPosition) { - lugPosition = pos; - } - } - } - if (!Double.isNaN(lugPosition)) { - double maxX = 0; - for (Coordinate c : configuration.getBounds()) { - if (c.x > maxX) - maxX = c.x; - } - if (maxX >= lugPosition) { - length = Math.max(0, length - (maxX - lugPosition)); - } - } - init.setEffectiveLaunchRodLength(length); - - - - init.setSimulationStartWallTime(System.nanoTime()); - - init.setMotorIgnited(false); - init.setLiftoff(false); - init.setLaunchRodCleared(false); - init.setApogeeReached(false); - - init.getEventQueue().add(new FlightEvent(FlightEvent.Type.LAUNCH, 0, simulationConditions.getRocket())); - - init.setFlightData(new FlightDataBranch("MAIN", FlightDataType.TYPE_TIME)); - init.setWarnings(flightData.getWarningSet()); - - return init; - } - - - - /** - * Create a rocket configuration from the launch conditions. - * - * @param simulation the launch conditions. - * @return a rocket configuration with all stages attached. - */ - private Configuration setupConfiguration(SimulationConditions simulation) { - Configuration configuration = new Configuration(simulation.getRocket()); - configuration.setAllStages(); - configuration.setMotorConfigurationID(simulation.getMotorConfigurationID()); - - return configuration; - } - - - - /** - * Create a new motor instance configuration for the rocket configuration. - * - * @param configuration the rocket configuration. - * @return a new motor instance configuration with all motors in place. - */ - private MotorInstanceConfiguration setupMotorConfiguration(Configuration configuration) { - MotorInstanceConfiguration motors = new MotorInstanceConfiguration(); - final String motorId = configuration.getMotorConfigurationID(); - - Iterator<MotorMount> iterator = configuration.motorIterator(); - while (iterator.hasNext()) { - MotorMount mount = iterator.next(); - RocketComponent component = (RocketComponent) mount; - Motor motor = mount.getMotor(motorId); - - if (motor != null) { - Coordinate[] positions = component.toAbsolute(mount.getMotorPosition(motorId)); - for (int i = 0; i < positions.length; i++) { - Coordinate position = positions[i]; - MotorId id = new MotorId(component.getID(), i + 1); - motors.addMotor(id, motor.getInstance(), mount, position); - } - } - } - return motors; - } - - /** - * Handles events occurring during the flight from the event queue. - * Each event that has occurred before or at the current simulation time is - * processed. Suitable events are also added to the flight data. - */ - private boolean handleEvents() throws SimulationException { - boolean ret = true; - FlightEvent event; - - for (event = nextEvent(); event != null; event = nextEvent()) { - - // Ignore events for components that are no longer attached to the rocket - if (event.getSource() != null && event.getSource().getParent() != null && - !status.getConfiguration().isStageActive(event.getSource().getStageNumber())) { - continue; - } - - // Call simulation listeners, allow aborting event handling - if (!SimulationListenerHelper.fireHandleFlightEvent(status, event)) { - continue; - } - - if (event.getType() != FlightEvent.Type.ALTITUDE) { - log.verbose("BasicEventSimulationEngine: Handling event " + event); - } - - if (event.getType() == FlightEvent.Type.IGNITION) { - MotorMount mount = (MotorMount) event.getSource(); - MotorId motorId = (MotorId) event.getData(); - MotorInstance instance = status.getMotorConfiguration().getMotorInstance(motorId); - if (!SimulationListenerHelper.fireMotorIgnition(status, motorId, mount, instance)) { - continue; - } - } - - if (event.getType() == FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT) { - RecoveryDevice device = (RecoveryDevice) event.getSource(); - if (!SimulationListenerHelper.fireRecoveryDeviceDeployment(status, device)) { - continue; - } - } - - - - // Check for motor ignition events, add ignition events to queue - for (MotorId id : status.getMotorConfiguration().getMotorIDs()) { - MotorMount mount = status.getMotorConfiguration().getMotorMount(id); - RocketComponent component = (RocketComponent) mount; - - if (mount.getIgnitionEvent().isActivationEvent(event, component)) { - addEvent(new FlightEvent(FlightEvent.Type.IGNITION, - status.getSimulationTime() + mount.getIgnitionDelay(), - component, id)); - } - } - - - // Check for stage separation event - for (int stageNo : status.getConfiguration().getActiveStages()) { - if (stageNo == 0) - continue; - - Stage stage = (Stage) status.getConfiguration().getRocket().getChild(stageNo); - if (stage.getSeparationEvent().isSeparationEvent(event, stage)) { - addEvent(new FlightEvent(FlightEvent.Type.STAGE_SEPARATION, - event.getTime() + stage.getSeparationDelay(), stage)); - } - } - - - // Check for recovery device deployment, add events to queue - Iterator<RocketComponent> rci = status.getConfiguration().iterator(); - while (rci.hasNext()) { - RocketComponent c = rci.next(); - if (!(c instanceof RecoveryDevice)) - continue; - if (((RecoveryDevice) c).getDeployEvent().isActivationEvent(event, c)) { - // Delay event by at least 1ms to allow stage separation to occur first - addEvent(new FlightEvent(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, - event.getTime() + Math.max(0.001, ((RecoveryDevice) c).getDeployDelay()), c)); - } - } - - - // Handle event - switch (event.getType()) { - - case LAUNCH: { - status.getFlightData().addEvent(event); - break; - } - - case IGNITION: { - // Ignite the motor - MotorMount mount = (MotorMount) event.getSource(); - RocketComponent component = (RocketComponent) mount; - MotorId motorId = (MotorId) event.getData(); - MotorInstanceConfiguration config = status.getMotorConfiguration(); - config.setMotorIgnitionTime(motorId, event.getTime()); - status.setMotorIgnited(true); - status.getFlightData().addEvent(event); - - break; - } - - case LIFTOFF: { - // Mark lift-off as occurred - status.setLiftoff(true); - status.getFlightData().addEvent(event); - break; - } - - case LAUNCHROD: { - // Mark launch rod as cleared - status.setLaunchRodCleared(true); - status.getFlightData().addEvent(event); - break; - } - - case BURNOUT: { - // If motor burnout occurs without lift-off, abort - if (!status.isLiftoff()) { - throw new SimulationLaunchException("Motor burnout without liftoff."); - } - // Add ejection charge event - String id = status.getConfiguration().getMotorConfigurationID(); - MotorMount mount = (MotorMount) event.getSource(); - double delay = mount.getMotorDelay(id); - if (delay != Motor.PLUGGED) { - addEvent(new FlightEvent(FlightEvent.Type.EJECTION_CHARGE, status.getSimulationTime() + delay, - event.getSource(), event.getData())); - } - status.getFlightData().addEvent(event); - break; - } - - case EJECTION_CHARGE: { - status.getFlightData().addEvent(event); - break; - } - - case STAGE_SEPARATION: { - // TODO: HIGH: Store lower stages to be simulated later - RocketComponent stage = event.getSource(); - int n = stage.getStageNumber(); - status.getConfiguration().setToStage(n - 1); - status.getFlightData().addEvent(event); - break; - } - - case APOGEE: - // Mark apogee as reached - status.setApogeeReached(true); - status.getFlightData().addEvent(event); - break; - - case RECOVERY_DEVICE_DEPLOYMENT: - RocketComponent c = event.getSource(); - int n = c.getStageNumber(); - // Ignore event if stage not active - if (status.getConfiguration().isStageActive(n)) { - // TODO: HIGH: Check stage activeness for other events as well? - - // Check whether any motor in the active stages is active anymore - for (MotorId motorId : status.getMotorConfiguration().getMotorIDs()) { - int stage = ((RocketComponent) status.getMotorConfiguration(). - getMotorMount(motorId)).getStageNumber(); - if (!status.getConfiguration().isStageActive(stage)) - continue; - if (!status.getMotorConfiguration().getMotorInstance(motorId).isActive()) - continue; - status.getWarnings().add(Warning.RECOVERY_DEPLOYMENT_WHILE_BURNING); - } - - // Check for launch rod - if (!status.isLaunchRodCleared()) { - status.getWarnings().add(Warning.RECOVERY_LAUNCH_ROD); - } - - // Check current velocity - if (status.getRocketVelocity().length() > 20) { - // TODO: LOW: Custom warning. - status.getWarnings().add(Warning.fromString(trans.get("Warning.RECOVERY_HIGH_SPEED") + - " (" - + UnitGroup.UNITS_VELOCITY.toStringUnit(status.getRocketVelocity().length()) - + ").")); - } - - status.setLiftoff(true); - status.getDeployedRecoveryDevices().add((RecoveryDevice) c); - - this.currentStepper = this.landingStepper; - this.status = currentStepper.initialize(status); - - status.getFlightData().addEvent(event); - } - break; - - case GROUND_HIT: - status.getFlightData().addEvent(event); - break; - - case SIMULATION_END: - ret = false; - status.getFlightData().addEvent(event); - break; - - case ALTITUDE: - break; - } - - } - - - // If no motor has ignited, abort - if (!status.isMotorIgnited()) { - throw new MotorIgnitionException("No motors ignited."); - } - - return ret; - } - - /** - * Add a flight event to the event queue unless a listener aborts adding it. - * - * @param event the event to add to the queue. - */ - private void addEvent(FlightEvent event) throws SimulationException { - if (SimulationListenerHelper.fireAddFlightEvent(status, event)) { - status.getEventQueue().add(event); - } - } - - - - /** - * Return the next flight event to handle, or null if no more events should be handled. - * This method jumps the simulation time forward in case no motors have been ignited. - * The flight event is removed from the event queue. - * - * @param status the simulation status - * @return the flight event to handle, or null - */ - private FlightEvent nextEvent() { - EventQueue queue = status.getEventQueue(); - FlightEvent event = queue.peek(); - if (event == null) - return null; - - // Jump to event if no motors have been ignited - if (!status.isMotorIgnited() && event.getTime() > status.getSimulationTime()) { - status.setSimulationTime(event.getTime()); - } - if (event.getTime() <= status.getSimulationTime()) { - return queue.poll(); - } else { - return null; - } - } - - - - private void checkNaN() throws SimulationException { - double d = 0; - boolean b = false; - d += status.getSimulationTime(); - d += status.getPreviousTimeStep(); - b |= status.getRocketPosition().isNaN(); - b |= status.getRocketVelocity().isNaN(); - b |= status.getRocketOrientationQuaternion().isNaN(); - b |= status.getRocketRotationVelocity().isNaN(); - d += status.getEffectiveLaunchRodLength(); - - if (Double.isNaN(d) || b) { - log.error("Simulation resulted in NaN value:" + - " simulationTime=" + status.getSimulationTime() + - " previousTimeStep=" + status.getPreviousTimeStep() + - " rocketPosition=" + status.getRocketPosition() + - " rocketVelocity=" + status.getRocketVelocity() + - " rocketOrientationQuaternion=" + status.getRocketOrientationQuaternion() + - " rocketRotationVelocity=" + status.getRocketRotationVelocity() + - " effectiveLaunchRodLength=" + status.getEffectiveLaunchRodLength()); - throw new SimulationException("Simulation resulted in not-a-number (NaN) value, please report a bug."); - } - } - - -} diff --git a/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java b/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java deleted file mode 100644 index 0d9c3954..00000000 --- a/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java +++ /dev/null @@ -1,141 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.GeodeticComputationStrategy; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.WorldCoordinate; - -public class BasicLandingStepper extends AbstractSimulationStepper { - - private static final double RECOVERY_TIME_STEP = 0.5; - - @Override - public SimulationStatus initialize(SimulationStatus status) throws SimulationException { - return status; - } - - @Override - public void step(SimulationStatus status, double maxTimeStep) throws SimulationException { - double totalCD = 0; - double refArea = status.getConfiguration().getReferenceArea(); - - // Get the atmospheric conditions - AtmosphericConditions atmosphere = modelAtmosphericConditions(status); - - //// Local wind speed and direction - Coordinate windSpeed = modelWindVelocity(status); - Coordinate airSpeed = status.getRocketVelocity().add(windSpeed); - - // Get total CD - double mach = airSpeed.length() / atmosphere.getMachSpeed(); - for (RecoveryDevice c : status.getDeployedRecoveryDevices()) { - totalCD += c.getCD(mach) * c.getArea() / refArea; - } - - // Compute drag force - double dynP = (0.5 * atmosphere.getDensity() * airSpeed.length2()); - double dragForce = totalCD * dynP * refArea; - MassData massData = calculateMassData(status); - double mass = massData.getCG().weight; - - - // Compute drag acceleration - Coordinate linearAcceleration; - if (airSpeed.length() > 0.001) { - linearAcceleration = airSpeed.normalize().multiply(-dragForce / mass); - } else { - linearAcceleration = Coordinate.NUL; - } - - // Add effect of gravity - double gravity = modelGravity(status); - linearAcceleration = linearAcceleration.sub(0, 0, gravity); - - - // Add coriolis acceleration - Coordinate coriolisAcceleration = status.getSimulationConditions().getGeodeticComputation().getCoriolisAcceleration( - status.getRocketWorldPosition(), status.getRocketVelocity()); - linearAcceleration = linearAcceleration.add(coriolisAcceleration); - - - - // Select time step - double timeStep = MathUtil.min(0.5 / linearAcceleration.length(), RECOVERY_TIME_STEP); - - // Perform Euler integration - status.setRocketPosition(status.getRocketPosition().add(status.getRocketVelocity().multiply(timeStep)). - add(linearAcceleration.multiply(MathUtil.pow2(timeStep) / 2))); - status.setRocketVelocity(status.getRocketVelocity().add(linearAcceleration.multiply(timeStep))); - status.setSimulationTime(status.getSimulationTime() + timeStep); - - - // Update the world coordinate - WorldCoordinate w = status.getSimulationConditions().getLaunchSite(); - w = status.getSimulationConditions().getGeodeticComputation().addCoordinate(w, status.getRocketPosition()); - status.setRocketWorldPosition(w); - - - // Store data - FlightDataBranch data = status.getFlightData(); - boolean extra = status.getSimulationConditions().isCalculateExtras(); - data.addPoint(); - - data.setValue(FlightDataType.TYPE_TIME, status.getSimulationTime()); - data.setValue(FlightDataType.TYPE_ALTITUDE, status.getRocketPosition().z); - data.setValue(FlightDataType.TYPE_POSITION_X, status.getRocketPosition().x); - data.setValue(FlightDataType.TYPE_POSITION_Y, status.getRocketPosition().y); - if (extra) { - data.setValue(FlightDataType.TYPE_POSITION_XY, - MathUtil.hypot(status.getRocketPosition().x, status.getRocketPosition().y)); - data.setValue(FlightDataType.TYPE_POSITION_DIRECTION, - Math.atan2(status.getRocketPosition().y, status.getRocketPosition().x)); - - data.setValue(FlightDataType.TYPE_VELOCITY_XY, - MathUtil.hypot(status.getRocketVelocity().x, status.getRocketVelocity().y)); - data.setValue(FlightDataType.TYPE_ACCELERATION_XY, - MathUtil.hypot(linearAcceleration.x, linearAcceleration.y)); - - data.setValue(FlightDataType.TYPE_ACCELERATION_TOTAL, linearAcceleration.length()); - - double Re = airSpeed.length() * - status.getConfiguration().getLength() / - atmosphere.getKinematicViscosity(); - data.setValue(FlightDataType.TYPE_REYNOLDS_NUMBER, Re); - } - - - data.setValue(FlightDataType.TYPE_LATITUDE, status.getRocketWorldPosition().getLatitudeRad()); - data.setValue(FlightDataType.TYPE_LONGITUDE, status.getRocketWorldPosition().getLongitudeRad()); - data.setValue(FlightDataType.TYPE_GRAVITY, gravity); - - if (status.getSimulationConditions().getGeodeticComputation() != GeodeticComputationStrategy.FLAT) { - data.setValue(FlightDataType.TYPE_CORIOLIS_ACCELERATION, coriolisAcceleration.length()); - } - - - data.setValue(FlightDataType.TYPE_VELOCITY_Z, status.getRocketVelocity().z); - data.setValue(FlightDataType.TYPE_ACCELERATION_Z, linearAcceleration.z); - - data.setValue(FlightDataType.TYPE_VELOCITY_TOTAL, airSpeed.length()); - data.setValue(FlightDataType.TYPE_MACH_NUMBER, mach); - - data.setValue(FlightDataType.TYPE_MASS, mass); - data.setValue(FlightDataType.TYPE_PROPELLANT_MASS, 0.0); // Is this a reasonable assumption? Probably. - - data.setValue(FlightDataType.TYPE_THRUST_FORCE, 0); - data.setValue(FlightDataType.TYPE_DRAG_FORCE, dragForce); - - data.setValue(FlightDataType.TYPE_WIND_VELOCITY, windSpeed.length()); - data.setValue(FlightDataType.TYPE_AIR_TEMPERATURE, atmosphere.getTemperature()); - data.setValue(FlightDataType.TYPE_AIR_PRESSURE, atmosphere.getPressure()); - data.setValue(FlightDataType.TYPE_SPEED_OF_SOUND, atmosphere.getMachSpeed()); - - data.setValue(FlightDataType.TYPE_TIME_STEP, timeStep); - data.setValue(FlightDataType.TYPE_COMPUTATION_TIME, - (System.nanoTime() - status.getSimulationStartWallTime()) / 1000000000.0); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/EventQueue.java b/core/src/net/sf/openrocket/simulation/EventQueue.java deleted file mode 100644 index 1ac9fb82..00000000 --- a/core/src/net/sf/openrocket/simulation/EventQueue.java +++ /dev/null @@ -1,65 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.PriorityQueue; - -import net.sf.openrocket.util.Monitorable; - -/** - * A sorted queue of FlightEvent objects. This queue maintains the events in time order - * and also keeps a modification count for the queue. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class EventQueue extends PriorityQueue<FlightEvent> implements Monitorable { - - private int modID = 0; - - public EventQueue() { - super(); - } - - public EventQueue(PriorityQueue<? extends FlightEvent> c) { - super(c); - } - - @Override - public boolean add(FlightEvent e) { - modID++; - return super.add(e); - } - - @Override - public void clear() { - modID++; - super.clear(); - } - - @Override - public boolean offer(FlightEvent e) { - modID++; - return super.offer(e); - } - - @Override - public FlightEvent poll() { - modID++; - return super.poll(); - } - - @Override - public boolean remove(Object o) { - modID++; - return super.remove(o); - } - - public int getModID() { - return modID; - } - - @Override - protected Object clone() throws CloneNotSupportedException { - // TODO Auto-generated method stub - return super.clone(); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/FlightData.java b/core/src/net/sf/openrocket/simulation/FlightData.java deleted file mode 100644 index c0fb90e8..00000000 --- a/core/src/net/sf/openrocket/simulation/FlightData.java +++ /dev/null @@ -1,312 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Mutable; - -/** - * A collection of various flight data. This is the result of a simulation, or importing - * data into the software. The data includes: - * <ul> - * <li>A number of generally interesting values of a simulation, such as max. altitude and velocity - * <li>A number (or zero) of flight data branches containing the actual data - * <li>A WarningSet including warnings that occurred during simulation - * </ul> - * <p> - * A FlightData object can be made immutable by calling {@link #immute()}. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class FlightData { - private static final LogHelper log = Application.getLogger(); - - /** - * An immutable FlightData object with NaN data. - */ - public static final FlightData NaN_DATA; - static { - FlightData data = new FlightData(); - data.immute(); - NaN_DATA = data; - } - - private Mutable mutable = new Mutable(); - - private final ArrayList<FlightDataBranch> branches = new ArrayList<FlightDataBranch>(); - - private final WarningSet warnings = new WarningSet(); - - private double maxAltitude = Double.NaN; - private double maxVelocity = Double.NaN; - private double maxAcceleration = Double.NaN; - private double maxMachNumber = Double.NaN; - private double timeToApogee = Double.NaN; - private double flightTime = Double.NaN; - private double groundHitVelocity = Double.NaN; - private double launchRodVelocity = Double.NaN; - private double deploymentVelocity = Double.NaN; - - - /** - * Create a FlightData object with no content. The resulting object is mutable. - */ - public FlightData() { - - } - - - /** - * Construct a FlightData object with no data branches but the specified - * summary information. The resulting object is mutable. - * - * @param maxAltitude maximum altitude. - * @param maxVelocity maximum velocity. - * @param maxAcceleration maximum acceleration. - * @param maxMachNumber maximum Mach number. - * @param timeToApogee time to apogee. - * @param flightTime total flight time. - * @param groundHitVelocity ground hit velocity. - * @param launchRodVelocity velocity at launch rod clearance - * @param deploymentVelocity velocity at deployment - */ - public FlightData(double maxAltitude, double maxVelocity, double maxAcceleration, - double maxMachNumber, double timeToApogee, double flightTime, - double groundHitVelocity, double launchRodVelocity, double deploymentVelocity) { - this.maxAltitude = maxAltitude; - this.maxVelocity = maxVelocity; - this.maxAcceleration = maxAcceleration; - this.maxMachNumber = maxMachNumber; - this.timeToApogee = timeToApogee; - this.flightTime = flightTime; - this.groundHitVelocity = groundHitVelocity; - this.launchRodVelocity = launchRodVelocity; - this.deploymentVelocity = deploymentVelocity; - } - - - /** - * Create a FlightData object with the specified branches. The resulting object is mutable. - * - * @param branches the branches. - */ - public FlightData(FlightDataBranch... branches) { - this(); - - for (FlightDataBranch b : branches) - this.addBranch(b); - - calculateIntrestingValues(); - } - - - - - /** - * Returns the warning set associated with this object. This WarningSet cannot be - * set, so simulations must use this warning set to store their warnings. - * The returned WarningSet should not be modified otherwise. - * - * @return the warnings generated during this simulation. - */ - public WarningSet getWarningSet() { - return warnings; - } - - - public void addBranch(FlightDataBranch branch) { - mutable.check(); - - branch.immute(); - branches.add(branch); - - if (branches.size() == 1) { - calculateIntrestingValues(); - } - } - - public int getBranchCount() { - return branches.size(); - } - - public FlightDataBranch getBranch(int n) { - return branches.get(n); - } - - - - public double getMaxAltitude() { - return maxAltitude; - } - - public double getMaxVelocity() { - return maxVelocity; - } - - /** - * NOTE: This value only takes into account flight phase. - */ - public double getMaxAcceleration() { - return maxAcceleration; - } - - public double getMaxMachNumber() { - return maxMachNumber; - } - - public double getTimeToApogee() { - return timeToApogee; - } - - public double getFlightTime() { - return flightTime; - } - - public double getGroundHitVelocity() { - return groundHitVelocity; - } - - public double getLaunchRodVelocity() { - return launchRodVelocity; - } - - - public double getDeploymentVelocity() { - return deploymentVelocity; - } - - - /** - * Calculate the max. altitude/velocity/acceleration, time to apogee, flight time - * and ground hit velocity. - */ - private void calculateIntrestingValues() { - if (branches.isEmpty()) - return; - - FlightDataBranch branch = branches.get(0); - maxAltitude = branch.getMaximum(FlightDataType.TYPE_ALTITUDE); - maxVelocity = branch.getMaximum(FlightDataType.TYPE_VELOCITY_TOTAL); - maxMachNumber = branch.getMaximum(FlightDataType.TYPE_MACH_NUMBER); - - flightTime = branch.getLast(FlightDataType.TYPE_TIME); - if (branch.getLast(FlightDataType.TYPE_ALTITUDE) < 10) { - groundHitVelocity = branch.getLast(FlightDataType.TYPE_VELOCITY_TOTAL); - } else { - groundHitVelocity = Double.NaN; - } - - - // Time to apogee - List<Double> time = branch.get(FlightDataType.TYPE_TIME); - List<Double> altitude = branch.get(FlightDataType.TYPE_ALTITUDE); - - if (time == null || altitude == null) { - timeToApogee = Double.NaN; - maxAcceleration = Double.NaN; - return; - } - int index = 0; - for (Double alt : altitude) { - if (alt != null) { - if (MathUtil.equals(alt, maxAltitude)) - break; - } - - index++; - } - if (index < time.size()) - timeToApogee = time.get(index); - else - timeToApogee = Double.NaN; - - - // Launch rod velocity - eventloop: for (FlightEvent event : branch.getEvents()) { - if (event.getType() == FlightEvent.Type.LAUNCHROD) { - double t = event.getTime(); - List<Double> velocity = branch.get(FlightDataType.TYPE_VELOCITY_TOTAL); - launchRodVelocity = MathUtil.interpolate( time, velocity, t); - } else if ( event.getType() == FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT) { - double t = event.getTime(); - List<Double> velocity = branch.get(FlightDataType.TYPE_VELOCITY_TOTAL); - deploymentVelocity = MathUtil.interpolate( time, velocity, t); - } - } - - // Max. acceleration (must be after apogee time) - if (branch.get(FlightDataType.TYPE_ACCELERATION_TOTAL) != null) { - maxAcceleration = calculateMaxAcceleration(); - } else { - maxAcceleration = Double.NaN; - } - - log.debug("Computed flight values:" + - " maxAltitude=" + maxAltitude + - " maxVelocity=" + maxVelocity + - " maxAcceleration=" + maxAcceleration + - " maxMachNumber=" + maxMachNumber + - " timeToApogee=" + timeToApogee + - " flightTime=" + flightTime + - " groundHitVelocity=" + groundHitVelocity + - " launchRodVelocity=" + launchRodVelocity); - } - - - public void immute() { - mutable.immute(); - warnings.immute(); - for (FlightDataBranch b : branches) { - b.immute(); - } - } - - - public boolean isMutable() { - return mutable.isMutable(); - } - - - - /** - * Find the maximum acceleration before apogee. - */ - private double calculateMaxAcceleration() { - - // End check at first recovery device deployment - double endTime = Double.MAX_VALUE; - - FlightDataBranch branch = this.getBranch(0); - for (FlightEvent event : branch.getEvents()) { - if (event.getType() == FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT) { - if (event.getTime() < endTime) { - endTime = event.getTime(); - } - } - } - - List<Double> time = branch.get(FlightDataType.TYPE_TIME); - List<Double> acceleration = branch.get(FlightDataType.TYPE_ACCELERATION_TOTAL); - - if (time == null || acceleration == null) { - return Double.NaN; - } - - double max = 0; - - for (int i = 0; i < time.size(); i++) { - if (time.get(i) >= endTime) { - break; - } - double a = acceleration.get(i); - if (a > max) - max = a; - } - - return max; - } -} diff --git a/core/src/net/sf/openrocket/simulation/FlightDataBranch.java b/core/src/net/sf/openrocket/simulation/FlightDataBranch.java deleted file mode 100644 index 76bef764..00000000 --- a/core/src/net/sf/openrocket/simulation/FlightDataBranch.java +++ /dev/null @@ -1,267 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.Mutable; - -/** - * A single branch of flight data. The data is ordered based on some variable, typically time. - * It also contains flight events that have occurred during simulation. - * <p> - * After instantiating a FlightDataBranch data and new variable types can be added to the branch. - * A new data point (a value for each variable defined) is created using {@link #addPoint()} after - * which the value for each variable type can be set using {@link #setValue(FlightDataType, double)}. - * Each variable type does NOT have to be set, unset values will default to NaN. New variable types - * not defined in the constructor can be added using {@link #setValue(FlightDataType, double)}, they - * will be created and all previous values will be set to NaN. - * <p> - * After populating a FlightDataBranch object it can be made immutable by calling {@link #immute()}. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class FlightDataBranch implements Monitorable { - - /** The name of this flight data branch. */ - private final String branchName; - - private final Map<FlightDataType, ArrayList<Double>> values = - new LinkedHashMap<FlightDataType, ArrayList<Double>>(); - - private final Map<FlightDataType, Double> maxValues = new HashMap<FlightDataType, Double>(); - private final Map<FlightDataType, Double> minValues = new HashMap<FlightDataType, Double>(); - - - private final ArrayList<FlightEvent> events = new ArrayList<FlightEvent>(); - - private Mutable mutable = new Mutable(); - - private int modID = 0; - - /** - * Sole constructor. Defines the name of the FlightDataBranch and at least one variable type. - * - * @param name the name of this FlightDataBranch. - * @param types data types to include (must include at least one type). - */ - public FlightDataBranch(String name, FlightDataType... types) { - if (types.length == 0) { - throw new IllegalArgumentException("Must specify at least one data type."); - } - - this.branchName = name; - - for (FlightDataType t : types) { - if (values.containsKey(t)) { - throw new IllegalArgumentException("Value type " + t + " specified multiple " + - "times in constructor."); - } - - values.put(t, new ArrayList<Double>()); - minValues.put(t, Double.NaN); - maxValues.put(t, Double.NaN); - } - } - - /** - * Makes an 'empty' flight data branch which has no data but all built in data types are defined. - */ - public FlightDataBranch() { - branchName = "Empty branch"; - for (FlightDataType type : FlightDataType.ALL_TYPES){ - this.setValue(type, Double.NaN); - } - this.immute(); - } - - /** - * Adds a new point into the data branch. The value for all types is set to NaN by default. - * - * @throws IllegalStateException if this object has been made immutable. - */ - public void addPoint() { - mutable.check(); - - for (FlightDataType t : values.keySet()) { - values.get(t).add(Double.NaN); - } - modID++; - } - - - /** - * Set the value for a specific data type at the latest point. New variable types can be - * added to the FlightDataBranch transparently. - * - * @param type the variable to set. - * @param value the value to set. - * @throws IllegalStateException if this object has been made immutable. - */ - public void setValue(FlightDataType type, double value) { - mutable.check(); - - ArrayList<Double> list = values.get(type); - - if (list == null) { - list = new ArrayList<Double>(); - int n = getLength(); - for (int i = 0; i < n; i++) { - list.add(Double.NaN); - } - values.put(type, list); - minValues.put(type, value); - maxValues.put(type, value); - } - - if (list.size() > 0){ - list.set(list.size() - 1, value); - } - - double min = minValues.get(type); - double max = maxValues.get(type); - - if (Double.isNaN(min) || (value < min)) { - minValues.put(type, value); - } - if (Double.isNaN(max) || (value > max)) { - maxValues.put(type, value); - } - modID++; - } - - - /** - * Return the branch name. - */ - public String getBranchName() { - return branchName; - } - - /** - * Return the variable types included in this branch. The types are sorted in their - * natural order. - */ - public FlightDataType[] getTypes() { - FlightDataType[] array = values.keySet().toArray(new FlightDataType[0]); - Arrays.sort(array); - return array; - } - - /** - * Return the number of data points in this branch. - */ - public int getLength() { - for (FlightDataType t : values.keySet()) { - return values.get(t).size(); - } - return 0; - } - - /** - * Return an array of values for the specified variable type. - * - * @param type the variable type. - * @return a list of the variable values, or <code>null</code> if - * the variable type hasn't been added to this branch. - */ - public List<Double> get(FlightDataType type) { - ArrayList<Double> list = values.get(type); - if (list == null) - return null; - return list.clone(); - } - - /** - * Return the last value of the specified type in the branch, or NaN if the type is - * unavailable. - * - * @param type the parameter type. - * @return the last value in this branch, or NaN. - */ - public double getLast(FlightDataType type) { - ArrayList<Double> list = values.get(type); - if (list == null || list.isEmpty()) - return Double.NaN; - return list.get(list.size() - 1); - } - - /** - * Return the minimum value of the specified type in the branch, or NaN if the type - * is unavailable. - * - * @param type the parameter type. - * @return the minimum value in this branch, or NaN. - */ - public double getMinimum(FlightDataType type) { - Double v = minValues.get(type); - if (v == null) - return Double.NaN; - return v; - } - - /** - * Return the maximum value of the specified type in the branch, or NaN if the type - * is unavailable. - * - * @param type the parameter type. - * @return the maximum value in this branch, or NaN. - */ - public double getMaximum(FlightDataType type) { - Double v = maxValues.get(type); - if (v == null) - return Double.NaN; - return v; - } - - - /** - * Add a flight event to this branch. - * - * @param event the event to add. - * @throws IllegalStateException if this branch has been made immutable. - */ - public void addEvent(FlightEvent event) { - mutable.check(); - events.add(event.resetSourceAndData()); - modID++; - } - - - /** - * Return the list of events. - * - * @return the list of events during the flight. - */ - public List<FlightEvent> getEvents() { - return events.clone(); - } - - - /** - * Make this FlightDataBranch immutable. Any calls to the set methods that would - * modify this object will after this call throw an <code>IllegalStateException</code>. - */ - public void immute() { - mutable.immute(); - } - - - /** - * Return whether this branch is still mutable. - */ - public boolean isMutable() { - return mutable.isMutable(); - } - - - @Override - public int getModID() { - return modID; - } - -} diff --git a/core/src/net/sf/openrocket/simulation/FlightDataType.java b/core/src/net/sf/openrocket/simulation/FlightDataType.java deleted file mode 100644 index adb4b51b..00000000 --- a/core/src/net/sf/openrocket/simulation/FlightDataType.java +++ /dev/null @@ -1,396 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.UnitGroup; - -/** - * A class defining a storable simulation variable type. This class defined numerous ready - * types, and allows also creating new types with any name. When retrieving types based on - * a name, you should use {@link #getType(String, UnitGroup)} to return the default unit type, - * or a new type if the name does not currently exist. - * <p> - * Each type has a type name (description), a unit group and a priority. The type is identified - * purely by its name case-insensitively. The unit group provides the units for the type. - * The priority is used to order the types. The pre-existing types are defined specific priority - * numbers, and other types have a default priority number that is after all other types. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class FlightDataType implements Comparable<FlightDataType> { - private static final Translator trans = Application.getTranslator(); - private static final LogHelper log = Application.getLogger(); - - /** Priority of custom-created variables */ - private static final int DEFAULT_PRIORITY = 999; - - /** List of existing types. MUST BE DEFINED BEFORE ANY TYPES!! */ - /** NOTE: The String key here is now the symbol */ - private static final Map<String, FlightDataType> EXISTING_TYPES = new HashMap<String, FlightDataType>(); - - - //// Time - public static final FlightDataType TYPE_TIME = newType(trans.get("FlightDataType.TYPE_TIME"), "t", UnitGroup.UNITS_FLIGHT_TIME, 1); - - //// Vertical position and motion - //// Altitude - public static final FlightDataType TYPE_ALTITUDE = newType(trans.get("FlightDataType.TYPE_ALTITUDE"), "h", UnitGroup.UNITS_DISTANCE, 10); - //// Vertical velocity - public static final FlightDataType TYPE_VELOCITY_Z = newType(trans.get("FlightDataType.TYPE_VELOCITY_Z"), "Vz", UnitGroup.UNITS_VELOCITY, 11); - //// Vertical acceleration - public static final FlightDataType TYPE_ACCELERATION_Z = newType(trans.get("FlightDataType.TYPE_ACCELERATION_Z"), "Az", UnitGroup.UNITS_ACCELERATION, 12); - - - //// Total motion - //// Total velocity - public static final FlightDataType TYPE_VELOCITY_TOTAL = newType(trans.get("FlightDataType.TYPE_VELOCITY_TOTAL"), "Vt", UnitGroup.UNITS_VELOCITY, 20); - //// Total acceleration - public static final FlightDataType TYPE_ACCELERATION_TOTAL = newType(trans.get("FlightDataType.TYPE_ACCELERATION_TOTAL"), "At", UnitGroup.UNITS_ACCELERATION, 21); - - - //// Lateral position and motion - //// Position upwind - public static final FlightDataType TYPE_POSITION_X = newType(trans.get("FlightDataType.TYPE_POSITION_X"), "Px", UnitGroup.UNITS_DISTANCE, 30); - //// Position parallel to wind - public static final FlightDataType TYPE_POSITION_Y = newType(trans.get("FlightDataType.TYPE_POSITION_Y"), "Py", UnitGroup.UNITS_DISTANCE, 31); - //// Lateral distance - public static final FlightDataType TYPE_POSITION_XY = newType(trans.get("FlightDataType.TYPE_POSITION_XY"), "Pl", UnitGroup.UNITS_DISTANCE, 32); - //// Lateral direction - public static final FlightDataType TYPE_POSITION_DIRECTION = newType(trans.get("FlightDataType.TYPE_POSITION_DIRECTION"), "\u03b8l", UnitGroup.UNITS_ANGLE, 33); - //// Lateral velocity - public static final FlightDataType TYPE_VELOCITY_XY = newType(trans.get("FlightDataType.TYPE_VELOCITY_XY"), "Vl", UnitGroup.UNITS_VELOCITY, 34); - //// Lateral acceleration - public static final FlightDataType TYPE_ACCELERATION_XY = newType(trans.get("FlightDataType.TYPE_ACCELERATION_XY"), "Al", UnitGroup.UNITS_ACCELERATION, 35); - //// Latitude - public static final FlightDataType TYPE_LATITUDE = newType(trans.get("FlightDataType.TYPE_LATITUDE"), "\u03c6", UnitGroup.UNITS_ANGLE, 36); - //// Longitude - public static final FlightDataType TYPE_LONGITUDE = newType(trans.get("FlightDataType.TYPE_LONGITUDE"), "\u03bb", UnitGroup.UNITS_ANGLE, 37); - - //// Gravity - public static final FlightDataType TYPE_GRAVITY = newType(trans.get("FlightDataType.TYPE_GRAVITY"), "g", UnitGroup.UNITS_ACCELERATION, 38); - - //// Angular motion - //// Angle of attack - public static final FlightDataType TYPE_AOA = newType(trans.get("FlightDataType.TYPE_AOA"), "\u03b1", UnitGroup.UNITS_ANGLE, 40); - //// Roll rate - public static final FlightDataType TYPE_ROLL_RATE = newType(trans.get("FlightDataType.TYPE_ROLL_RATE"), "d\u03a6", UnitGroup.UNITS_ROLL, 41); - //// Pitch rate - public static final FlightDataType TYPE_PITCH_RATE = newType(trans.get("FlightDataType.TYPE_PITCH_RATE"), "d\u03b8", UnitGroup.UNITS_ROLL, 42); - //// Yaw rate - public static final FlightDataType TYPE_YAW_RATE = newType(trans.get("FlightDataType.TYPE_YAW_RATE"), "d\u03a8", UnitGroup.UNITS_ROLL, 43); - - - //// Stability information - //// Mass - public static final FlightDataType TYPE_MASS = newType(trans.get("FlightDataType.TYPE_MASS"), "m", UnitGroup.UNITS_MASS, 50); - //// Propellant mass - public static final FlightDataType TYPE_PROPELLANT_MASS = newType(trans.get("FlightDataType.TYPE_PROPELLANT_MASS"), "mp", UnitGroup.UNITS_MASS, 51); - //// Longitudinal moment of inertia - public static final FlightDataType TYPE_LONGITUDINAL_INERTIA = newType(trans.get("FlightDataType.TYPE_LONGITUDINAL_INERTIA"), "Il", UnitGroup.UNITS_INERTIA, 52); - //// Rotational moment of inertia - public static final FlightDataType TYPE_ROTATIONAL_INERTIA = newType(trans.get("FlightDataType.TYPE_ROTATIONAL_INERTIA"), "Ir", UnitGroup.UNITS_INERTIA, 53); - //// CP location - public static final FlightDataType TYPE_CP_LOCATION = newType(trans.get("FlightDataType.TYPE_CP_LOCATION"), "Cp", UnitGroup.UNITS_LENGTH, 54); - //// CG location - public static final FlightDataType TYPE_CG_LOCATION = newType(trans.get("FlightDataType.TYPE_CG_LOCATION"), "Cg", UnitGroup.UNITS_LENGTH, 55); - //// Stability margin calibers - public static final FlightDataType TYPE_STABILITY = newType(trans.get("FlightDataType.TYPE_STABILITY"), "S", UnitGroup.UNITS_COEFFICIENT, 56); - - - //// Characteristic numbers - //// Mach number - public static final FlightDataType TYPE_MACH_NUMBER = newType(trans.get("FlightDataType.TYPE_MACH_NUMBER"), "M", UnitGroup.UNITS_COEFFICIENT, 60); - //// Reynolds number - public static final FlightDataType TYPE_REYNOLDS_NUMBER = newType(trans.get("FlightDataType.TYPE_REYNOLDS_NUMBER"), "R", UnitGroup.UNITS_COEFFICIENT, 61); - - - //// Thrust and drag - //// Thrust - public static final FlightDataType TYPE_THRUST_FORCE = newType(trans.get("FlightDataType.TYPE_THRUST_FORCE"), "Ft", UnitGroup.UNITS_FORCE, 70); - //// Drag force - public static final FlightDataType TYPE_DRAG_FORCE = newType(trans.get("FlightDataType.TYPE_DRAG_FORCE"), "Fd", UnitGroup.UNITS_FORCE, 71); - //// Drag coefficient - public static final FlightDataType TYPE_DRAG_COEFF = newType(trans.get("FlightDataType.TYPE_DRAG_COEFF"), "Cd", UnitGroup.UNITS_COEFFICIENT, 72); - //// Axial drag coefficient - public static final FlightDataType TYPE_AXIAL_DRAG_COEFF = newType(trans.get("FlightDataType.TYPE_AXIAL_DRAG_COEFF"), "Cda", UnitGroup.UNITS_COEFFICIENT, 73); - - - //// Component drag coefficients - //// Friction drag coefficient - public static final FlightDataType TYPE_FRICTION_DRAG_COEFF = newType(trans.get("FlightDataType.TYPE_FRICTION_DRAG_COEFF"), "Cdf", UnitGroup.UNITS_COEFFICIENT, 80); - //// Pressure drag coefficient - public static final FlightDataType TYPE_PRESSURE_DRAG_COEFF = newType(trans.get("FlightDataType.TYPE_PRESSURE_DRAG_COEFF"), "Cdp", UnitGroup.UNITS_COEFFICIENT, 81); - //// Base drag coefficient - public static final FlightDataType TYPE_BASE_DRAG_COEFF = newType(trans.get("FlightDataType.TYPE_BASE_DRAG_COEFF"), "Cdb", UnitGroup.UNITS_COEFFICIENT, 82); - - - //// Other coefficients - //// Normal force coefficient - public static final FlightDataType TYPE_NORMAL_FORCE_COEFF = newType(trans.get("FlightDataType.TYPE_NORMAL_FORCE_COEFF"), "Cn", UnitGroup.UNITS_COEFFICIENT, 90); - //// Pitch moment coefficient - public static final FlightDataType TYPE_PITCH_MOMENT_COEFF = newType(trans.get("FlightDataType.TYPE_PITCH_MOMENT_COEFF"), "C\u03b8", UnitGroup.UNITS_COEFFICIENT, 91); - //// Yaw moment coefficient - public static final FlightDataType TYPE_YAW_MOMENT_COEFF = newType(trans.get("FlightDataType.TYPE_YAW_MOMENT_COEFF"), "C\u03c4\u03a8", UnitGroup.UNITS_COEFFICIENT, 92); - //// Side force coefficient - public static final FlightDataType TYPE_SIDE_FORCE_COEFF = newType(trans.get("FlightDataType.TYPE_SIDE_FORCE_COEFF"), "C\u03c4s", UnitGroup.UNITS_COEFFICIENT, 93); - //// Roll moment coefficient - public static final FlightDataType TYPE_ROLL_MOMENT_COEFF = newType(trans.get("FlightDataType.TYPE_ROLL_MOMENT_COEFF"), "C\u03c4\u03a6", UnitGroup.UNITS_COEFFICIENT, 94); - //// Roll forcing coefficient - public static final FlightDataType TYPE_ROLL_FORCING_COEFF = newType(trans.get("FlightDataType.TYPE_ROLL_FORCING_COEFF"), "Cf\u03a6", UnitGroup.UNITS_COEFFICIENT, 95); - //// Roll damping coefficient - public static final FlightDataType TYPE_ROLL_DAMPING_COEFF = newType(trans.get("FlightDataType.TYPE_ROLL_DAMPING_COEFF"), "C\u03b6\u03a6", UnitGroup.UNITS_COEFFICIENT, 96); - - //// Pitch damping coefficient - public static final FlightDataType TYPE_PITCH_DAMPING_MOMENT_COEFF = newType(trans.get("FlightDataType.TYPE_PITCH_DAMPING_MOMENT_COEFF"), "C\u03b6\u03b8", UnitGroup.UNITS_COEFFICIENT, 97); - //// Yaw damping coefficient - public static final FlightDataType TYPE_YAW_DAMPING_MOMENT_COEFF = newType(trans.get("FlightDataType.TYPE_YAW_DAMPING_MOMENT_COEFF"), "C\u03b6\u03a8", UnitGroup.UNITS_COEFFICIENT, 98); - - //// Coriolis acceleration - public static final FlightDataType TYPE_CORIOLIS_ACCELERATION = newType(trans.get("FlightDataType.TYPE_CORIOLIS_ACCELERATION"), "Ac", UnitGroup.UNITS_ACCELERATION, 99); - - - //// Reference length + area - //// Reference length - public static final FlightDataType TYPE_REFERENCE_LENGTH = newType(trans.get("FlightDataType.TYPE_REFERENCE_LENGTH"), "Lr", UnitGroup.UNITS_LENGTH, 100); - //// Reference area - public static final FlightDataType TYPE_REFERENCE_AREA = newType(trans.get("FlightDataType.TYPE_REFERENCE_AREA"), "Ar", UnitGroup.UNITS_AREA, 101); - - - //// Orientation - //// Vertical orientation (zenith) - public static final FlightDataType TYPE_ORIENTATION_THETA = newType(trans.get("FlightDataType.TYPE_ORIENTATION_THETA"), "\u0398", UnitGroup.UNITS_ANGLE, 106); - //// Lateral orientation (azimuth) - public static final FlightDataType TYPE_ORIENTATION_PHI = newType(trans.get("FlightDataType.TYPE_ORIENTATION_PHI"), "\u03a6", UnitGroup.UNITS_ANGLE, 107); - - - //// Atmospheric conditions - //// Wind velocity - public static final FlightDataType TYPE_WIND_VELOCITY = newType(trans.get("FlightDataType.TYPE_WIND_VELOCITY"), "Vw", UnitGroup.UNITS_VELOCITY, 110); - //// Air temperature - public static final FlightDataType TYPE_AIR_TEMPERATURE = newType(trans.get("FlightDataType.TYPE_AIR_TEMPERATURE"), "T", UnitGroup.UNITS_TEMPERATURE, 111); - //// Air pressure - public static final FlightDataType TYPE_AIR_PRESSURE = newType(trans.get("FlightDataType.TYPE_AIR_PRESSURE"), "P", UnitGroup.UNITS_PRESSURE, 112); - //// Speed of sound - public static final FlightDataType TYPE_SPEED_OF_SOUND = newType(trans.get("FlightDataType.TYPE_SPEED_OF_SOUND"), "Vs", UnitGroup.UNITS_VELOCITY, 113); - - //// Simulation information - //// Simulation time step - public static final FlightDataType TYPE_TIME_STEP = newType(trans.get("FlightDataType.TYPE_TIME_STEP"), "dt", UnitGroup.UNITS_TIME_STEP, 200); - //// Computation time - public static final FlightDataType TYPE_COMPUTATION_TIME = newType(trans.get("FlightDataType.TYPE_COMPUTATION_TIME"), "tc", UnitGroup.UNITS_SHORT_TIME, 201); - - // An array of all the built in types - public static final FlightDataType[] ALL_TYPES = { - TYPE_TIME, - TYPE_ALTITUDE , - TYPE_VELOCITY_Z , - TYPE_ACCELERATION_Z, - TYPE_VELOCITY_TOTAL, - TYPE_ACCELERATION_TOTAL, - TYPE_POSITION_X, - TYPE_POSITION_Y, - TYPE_POSITION_XY, - TYPE_POSITION_DIRECTION, - TYPE_VELOCITY_XY, - TYPE_ACCELERATION_XY, - TYPE_LATITUDE, - TYPE_LONGITUDE, - TYPE_GRAVITY, - TYPE_AOA, - TYPE_ROLL_RATE, - TYPE_PITCH_RATE, - TYPE_YAW_RATE, - TYPE_MASS, - TYPE_PROPELLANT_MASS, - TYPE_LONGITUDINAL_INERTIA, - TYPE_ROTATIONAL_INERTIA, - TYPE_CP_LOCATION, - TYPE_CG_LOCATION, - TYPE_STABILITY, - TYPE_MACH_NUMBER, - TYPE_REYNOLDS_NUMBER, - TYPE_THRUST_FORCE, - TYPE_DRAG_FORCE, - TYPE_DRAG_COEFF, - TYPE_AXIAL_DRAG_COEFF, - TYPE_FRICTION_DRAG_COEFF, - TYPE_PRESSURE_DRAG_COEFF, - TYPE_BASE_DRAG_COEFF, - TYPE_NORMAL_FORCE_COEFF, - TYPE_PITCH_MOMENT_COEFF, - TYPE_YAW_MOMENT_COEFF, - TYPE_SIDE_FORCE_COEFF, - TYPE_ROLL_MOMENT_COEFF, - TYPE_ROLL_FORCING_COEFF, - TYPE_ROLL_DAMPING_COEFF, - TYPE_PITCH_DAMPING_MOMENT_COEFF, - TYPE_YAW_DAMPING_MOMENT_COEFF, - TYPE_CORIOLIS_ACCELERATION, - TYPE_REFERENCE_LENGTH, - TYPE_REFERENCE_AREA, - TYPE_ORIENTATION_THETA, - TYPE_ORIENTATION_PHI, - TYPE_WIND_VELOCITY, - TYPE_AIR_TEMPERATURE, - TYPE_AIR_PRESSURE, - TYPE_SPEED_OF_SOUND, - TYPE_TIME_STEP, - TYPE_COMPUTATION_TIME - }; - - /** - * Return a {@link FlightDataType} with a given string description, symbol and unitgroup. - * This returns an existing data type if the symbol matches that of an existing type. - * - * If the symbol matches but the unit and description information differ, then the old stored datatype - * is erased and the updated version based on the given parametes is returned. - * The only exception is if the description or unitgroup are undefined (null or empty string). In this case - * we just get these parameters from the existing type when making the new one. - * - * @param s the string description of the type. - * @param u the unit group the new type should belong to if a new group is created. - * @return a data type. - */ - @SuppressWarnings("null") - public static synchronized FlightDataType getType(String s, String symbol, UnitGroup u) { - - // if symbol is null : try finding by name - // if unit is null : don't do anything to the unit if found, just return datatype if found and generate an error and an empty unit otherwise - int oldPriority = DEFAULT_PRIORITY; - - //FlightDataType type = findFromSymbol(symbol); - FlightDataType type = EXISTING_TYPES.get(symbol); - - if (type != null) { - // found it from symbol - - // if name was not given (empty string), can use the one we found - if ( s == null || s.isEmpty()){ - s = type.getName(); - } - if ( u == null ){ - u = type.getUnitGroup(); - } - - // if something has changed, then we need to remove the old one - // otherwise, just return what we found - if ( !u.equals(type.getUnitGroup()) ) - { - oldPriority = type.priority; - EXISTING_TYPES.remove(type); - log.info("Unitgroup of type "+type.getName() + - ", has changed from "+type.getUnitGroup().toString() + - " to "+u.toString() + - ". Removing old version."); - } - else if (!s.equals(type.getName())) { - oldPriority = type.priority; - EXISTING_TYPES.remove(type); - log.info("Name of type "+type.getName()+", has changed to "+s+". Removing old version."); - } - else{ - return type; - } - } - - if (u == null){ - u = UnitGroup.UNITS_NONE; - log.error("Made a new flightdatatype, but did not know what units to use."); - } - - // make a new one - type = newType(s, symbol, u, oldPriority); - return type; - } - - /* - * Get the flightdatatype from existing types based on the symbol. - */ - /* - private static FlightDataType findFromSymbol(String symbol){ - for (FlightDataType t : EXISTING_TYPES.values()){ - if (t.getSymbol().equals(symbol)){ - return t; - } - } - return null; - } - */ - - /** - * Used while initializing the class. - */ - private static synchronized FlightDataType newType(String s, String symbol, UnitGroup u, int priority) { - FlightDataType type = new FlightDataType(s, symbol, u, priority); - //EXISTING_TYPES.put(s.toLowerCase(Locale.ENGLISH), type); - EXISTING_TYPES.put(symbol, type); - return type; - } - - - private final String name; - private final String symbol; - private final UnitGroup units; - private final int priority; - private final int hashCode; - - - private FlightDataType(String typeName, String symbol, UnitGroup units, int priority) { - if (typeName == null) - throw new IllegalArgumentException("typeName is null"); - if (units == null) - throw new IllegalArgumentException("units is null"); - this.name = typeName; - this.symbol = symbol; - this.units = units; - this.priority = priority; - this.hashCode = this.name.toLowerCase(Locale.ENGLISH).hashCode(); - } - - /* - public void setPriority(int p){ - this.priority = p; - } - */ - - public String getName() { - return name; - } - - public String getSymbol(){ - return symbol; - } - - public UnitGroup getUnitGroup() { - return units; - } - - @Override - public String toString() { - return name; //+" ("+symbol+") "+units.getDefaultUnit().toString(); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof FlightDataType)) - return false; - return this.name.equalsIgnoreCase(((FlightDataType) other).name); - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public int compareTo(FlightDataType o) { - if (this.priority != o.priority) - return this.priority - o.priority; - return this.name.compareToIgnoreCase(o.name); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/simulation/FlightEvent.java b/core/src/net/sf/openrocket/simulation/FlightEvent.java deleted file mode 100644 index 92f125c6..00000000 --- a/core/src/net/sf/openrocket/simulation/FlightEvent.java +++ /dev/null @@ -1,159 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; - - -/** - * A class that defines an event during the flight of a rocket. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class FlightEvent implements Comparable<FlightEvent> { - private static final Translator trans = Application.getTranslator(); - - /** - * The type of the flight event. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - public enum Type { - /** - * Rocket launch. - */ - LAUNCH(trans.get("FlightEvent.Type.LAUNCH")), - /** - * Ignition of a motor. Source is the motor mount the motor of which has ignited, - * and the data is the MotorId of the motor instance. - */ - IGNITION(trans.get("FlightEvent.Type.IGNITION")), - /** - * When the motor has lifted off the ground. - */ - LIFTOFF(trans.get("FlightEvent.Type.LIFTOFF")), - /** - * Launch rod has been cleared. - */ - LAUNCHROD(trans.get("FlightEvent.Type.LAUNCHROD")), - /** - * Burnout of a motor. Source is the motor mount the motor of which has burnt out, - * and the data is the MotorId of the motor instance. - */ - BURNOUT(trans.get("FlightEvent.Type.BURNOUT")), - /** - * Ejection charge of a motor fired. Source is the motor mount the motor of - * which has exploded its ejection charge, and data is the MotorId of the motor instance. - */ - EJECTION_CHARGE(trans.get("FlightEvent.Type.EJECTION_CHARGE")), - /** - * Separation of a stage. Source is the stage which is being separated from the upper stages. - */ - STAGE_SEPARATION(trans.get("FlightEvent.Type.STAGE_SEPARATION")), - /** - * Apogee has been reached. - */ - APOGEE(trans.get("FlightEvent.Type.APOGEE")), - /** - * Opening of a recovery device. Source is the RecoveryComponent which has opened. - */ - RECOVERY_DEVICE_DEPLOYMENT(trans.get("FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT")), - /** - * Ground has been hit after flight. - */ - GROUND_HIT(trans.get("FlightEvent.Type.GROUND_HIT")), - - /** - * End of simulation. Placing this to the queue will end the simulation. - */ - SIMULATION_END(trans.get("FlightEvent.Type.SIMULATION_END")), - - /** - * A change in altitude has occurred. Data is a <code>Pair<Double,Double></code> - * which contains the old and new altitudes. - */ - ALTITUDE(trans.get("FlightEvent.Type.ALTITUDE")); - - private final String name; - - private Type(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - } - - private final Type type; - private final double time; - private final RocketComponent source; - private final Object data; - - - public FlightEvent(Type type, double time) { - this(type, time, null); - } - - public FlightEvent(Type type, double time, RocketComponent source) { - this(type, time, source, null); - } - - public FlightEvent(Type type, double time, RocketComponent source, Object data) { - this.type = type; - this.time = time; - this.source = source; - this.data = data; - } - - - - public Type getType() { - return type; - } - - public double getTime() { - return time; - } - - public RocketComponent getSource() { - return source; - } - - public Object getData() { - return data; - } - - - /** - * Return a new FlightEvent with the same information as the current event - * but with <code>null</code> source. This is used to avoid memory leakage by - * retaining references to obsolete components. - * - * @return a new FlightEvent with same type, time and data. - */ - public FlightEvent resetSourceAndData() { - return new FlightEvent(type, time, null, null); - } - - - /** - * Compares this event to another event depending on the event time. Secondary - * sorting is performed based on the event type ordinal. - */ - @Override - public int compareTo(FlightEvent o) { - if (this.time < o.time) - return -1; - if (this.time > o.time) - return 1; - - return this.type.ordinal() - o.type.ordinal(); - } - - @Override - public String toString() { - return "FlightEvent[type=" + type.name() + ",time=" + time + ",source=" + source + "]"; - } -} diff --git a/core/src/net/sf/openrocket/simulation/MassData.java b/core/src/net/sf/openrocket/simulation/MassData.java deleted file mode 100644 index 74386364..00000000 --- a/core/src/net/sf/openrocket/simulation/MassData.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -/** - * An immutable value object containing the mass data of a rocket. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class MassData { - - private final Coordinate cg; - private final double longitudinalInertia; - private final double rotationalInertia; - private final double propellantMass; - - - public MassData(Coordinate cg, double longitudinalInertia, double rotationalInertia, double propellantMass) { - if (cg == null) { - throw new IllegalArgumentException("cg is null"); - } - this.cg = cg; - this.longitudinalInertia = longitudinalInertia; - this.rotationalInertia = rotationalInertia; - this.propellantMass = propellantMass; - } - - - - - public Coordinate getCG() { - return cg; - } - - public double getLongitudinalInertia() { - return longitudinalInertia; - } - - public double getRotationalInertia() { - return rotationalInertia; - } - - public double getPropellantMass() { - return propellantMass; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof MassData)) - return false; - - MassData other = (MassData) obj; - return (this.cg.equals(other.cg) && MathUtil.equals(this.longitudinalInertia, other.longitudinalInertia) && - MathUtil.equals(this.rotationalInertia, other.rotationalInertia)) && MathUtil.equals(this.propellantMass, other.propellantMass) ; - } - - - @Override - public int hashCode() { - return (int) (cg.hashCode() ^ Double.doubleToLongBits(longitudinalInertia) ^ Double.doubleToLongBits(rotationalInertia) ^ Double.doubleToLongBits(propellantMass) ); - } - - - @Override - public String toString() { - return "MassData [cg=" + cg + ", longitudinalInertia=" + longitudinalInertia - + ", rotationalInertia=" + rotationalInertia + ", propellantMass="+propellantMass + "]"; - } - -} diff --git a/core/src/net/sf/openrocket/simulation/RK4SimulationStatus.java b/core/src/net/sf/openrocket/simulation/RK4SimulationStatus.java deleted file mode 100644 index 505ff77c..00000000 --- a/core/src/net/sf/openrocket/simulation/RK4SimulationStatus.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.util.Coordinate; - -public class RK4SimulationStatus extends SimulationStatus { - private Coordinate launchRodDirection; - - private double previousAcceleration = 0; - private AtmosphericConditions previousAtmosphericConditions; - - // Used for determining when to store aerodynamic computation warnings: - private double maxZVelocity = 0; - private double startWarningTime = -1; - - - public void setLaunchRodDirection(Coordinate launchRodDirection) { - this.launchRodDirection = launchRodDirection; - } - - - public Coordinate getLaunchRodDirection() { - return launchRodDirection; - } - - - - public double getPreviousAcceleration() { - return previousAcceleration; - } - - - public void setPreviousAcceleration(double previousAcceleration) { - this.previousAcceleration = previousAcceleration; - } - - - public AtmosphericConditions getPreviousAtmosphericConditions() { - return previousAtmosphericConditions; - } - - - public void setPreviousAtmosphericConditions( - AtmosphericConditions previousAtmosphericConditions) { - this.previousAtmosphericConditions = previousAtmosphericConditions; - } - - - public double getMaxZVelocity() { - return maxZVelocity; - } - - - public void setMaxZVelocity(double maxZVelocity) { - this.maxZVelocity = maxZVelocity; - } - - - public double getStartWarningTime() { - return startWarningTime; - } - - - public void setStartWarningTime(double startWarningTime) { - this.startWarningTime = startWarningTime; - } - - - @Override - public RK4SimulationStatus clone() { - return (RK4SimulationStatus) super.clone(); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java b/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java deleted file mode 100644 index 8548ec91..00000000 --- a/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java +++ /dev/null @@ -1,727 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.Arrays; -import java.util.Random; - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.simulation.exception.SimulationCalculationException; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.SimulationListenerHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.GeodeticComputationStrategy; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.Quaternion; -import net.sf.openrocket.util.Rotation2D; -import net.sf.openrocket.util.WorldCoordinate; - -public class RK4SimulationStepper extends AbstractSimulationStepper { - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - - /** Random value with which to XOR the random seed value */ - private static final int SEED_RANDOMIZATION = 0x23E3A01F; - - - /** - * A recommended reasonably accurate time step. - */ - public static final double RECOMMENDED_TIME_STEP = 0.05; - - /** - * A recommended maximum angle step value. - */ - public static final double RECOMMENDED_ANGLE_STEP = 3 * Math.PI / 180; - - /** - * A random amount that is added to pitch and yaw coefficients, plus or minus. - */ - public static final double PITCH_YAW_RANDOM = 0.0005; - - /** - * Maximum roll step allowed. This is selected as an uneven division of the full - * circle so that the simulation will sample the most wind directions - */ - private static final double MAX_ROLL_STEP_ANGLE = 2 * 28.32 * Math.PI / 180; - // private static final double MAX_ROLL_STEP_ANGLE = 8.32 * Math.PI/180; - - private static final double MAX_ROLL_RATE_CHANGE = 2 * Math.PI / 180; - private static final double MAX_PITCH_CHANGE = 4 * Math.PI / 180; - - private static final double MIN_TIME_STEP = 0.001; - - - private Random random; - - - - - @Override - public RK4SimulationStatus initialize(SimulationStatus original) { - - RK4SimulationStatus status = new RK4SimulationStatus(); - - status.copyFrom(original); - - SimulationConditions sim = original.getSimulationConditions(); - - status.setLaunchRodDirection(new Coordinate( - Math.sin(sim.getLaunchRodAngle()) * Math.cos(sim.getLaunchRodDirection()), - Math.sin(sim.getLaunchRodAngle()) * Math.sin(sim.getLaunchRodDirection()), - Math.cos(sim.getLaunchRodAngle()) - )); - - this.random = new Random(original.getSimulationConditions().getRandomSeed() ^ SEED_RANDOMIZATION); - - return status; - } - - - - - @Override - public void step(SimulationStatus simulationStatus, double maxTimeStep) throws SimulationException { - - RK4SimulationStatus status = (RK4SimulationStatus) simulationStatus; - DataStore store = new DataStore(); - - //////// Perform RK4 integration: //////// - - RK4SimulationStatus status2; - RK4Parameters k1, k2, k3, k4; - - /* - * Start with previous time step which is used to compute the initial thrust estimate. - * Don't make it longer than maxTimeStep, but at least MIN_TIME_STEP. - */ - store.timestep = status.getPreviousTimeStep(); - store.timestep = MathUtil.max(MathUtil.min(store.timestep, maxTimeStep), MIN_TIME_STEP); - checkNaN(store.timestep); - - /* - * Compute the initial thrust estimate. This is used for the first time step computation. - */ - store.thrustForce = calculateThrust(status, store.timestep, status.getPreviousAcceleration(), - status.getPreviousAtmosphericConditions(), false); - - - /* - * Perform RK4 integration. Decide the time step length after the first step. - */ - - //// First position, k1 = f(t, y) - - k1 = computeParameters(status, store); - - /* - * Select the actual time step to use. It is the minimum of the following: - * dt[0]: the user-specified time step (or 1/5th of it if still on the launch rod) - * dt[1]: the value of maxTimeStep - * dt[2]: the maximum pitch step angle limit - * dt[3]: the maximum roll step angle limit - * dt[4]: the maximum roll rate change limit - * dt[5]: the maximum pitch change limit - * dt[6]: 1/10th of the launch rod length if still on the launch rod - * dt[7]: 1.50 times the previous time step - * - * The limits #5 and #6 are required since near the steady-state roll rate the roll rate - * may oscillate significantly even between the sub-steps of the RK4 integration. - * - * The step is still at least 1/20th of the user-selected time step. - */ - double[] dt = new double[8]; - Arrays.fill(dt, Double.MAX_VALUE); - - dt[0] = status.getSimulationConditions().getTimeStep(); - dt[1] = maxTimeStep; - dt[2] = status.getSimulationConditions().getMaximumAngleStep() / store.lateralPitchRate; - dt[3] = Math.abs(MAX_ROLL_STEP_ANGLE / store.flightConditions.getRollRate()); - dt[4] = Math.abs(MAX_ROLL_RATE_CHANGE / store.rollAcceleration); - dt[5] = Math.abs(MAX_PITCH_CHANGE / store.lateralPitchAcceleration); - if (!status.isLaunchRodCleared()) { - dt[0] /= 5.0; - dt[6] = status.getSimulationConditions().getLaunchRodLength() / k1.v.length() / 10; - } - dt[7] = 1.5 * status.getPreviousTimeStep(); - - store.timestep = Double.MAX_VALUE; - int limitingValue = -1; - for (int i = 0; i < dt.length; i++) { - if (dt[i] < store.timestep) { - store.timestep = dt[i]; - limitingValue = i; - } - } - - double minTimeStep = status.getSimulationConditions().getTimeStep() / 20; - if (store.timestep < minTimeStep) { - log.verbose("Too small time step " + store.timestep + " (limiting factor " + limitingValue + "), using " + - minTimeStep + " instead."); - store.timestep = minTimeStep; - } else { - log.verbose("Selected time step " + store.timestep + " (limiting factor " + limitingValue + ")"); - } - checkNaN(store.timestep); - - /* - * Compute the correct thrust for this time step. If the original thrust estimate differs more - * than 10% from the true value then recompute the RK4 step 1. The 10% error in step 1 is - * diminished by it affecting only 1/6th of the total, so it's an acceptable error. - */ - double thrustEstimate = store.thrustForce; - store.thrustForce = calculateThrust(status, store.timestep, store.longitudinalAcceleration, - store.atmosphericConditions, true); - double thrustDiff = Math.abs(store.thrustForce - thrustEstimate); - // Log if difference over 1%, recompute if over 10% - if (thrustDiff > 0.01 * thrustEstimate) { - if (thrustDiff > 0.1 * thrustEstimate + 0.001) { - log.debug("Thrust estimate differs from correct value by " + - (Math.rint(1000 * (thrustDiff + 0.000001) / thrustEstimate) / 10.0) + "%," + - " estimate=" + thrustEstimate + - " correct=" + store.thrustForce + - " timestep=" + store.timestep + - ", recomputing k1 parameters"); - k1 = computeParameters(status, store); - } else { - log.verbose("Thrust estimate differs from correct value by " + - (Math.rint(1000 * (thrustDiff + 0.000001) / thrustEstimate) / 10.0) + "%," + - " estimate=" + thrustEstimate + - " correct=" + store.thrustForce + - " timestep=" + store.timestep + - ", error acceptable"); - } - } - - // Store data - // TODO: MEDIUM: Store acceleration etc of entire RK4 step, store should be cloned or something... - storeData(status, store); - - - //// Second position, k2 = f(t + h/2, y + k1*h/2) - - status2 = status.clone(); - status2.setSimulationTime(status.getSimulationTime() + store.timestep / 2); - status2.setRocketPosition(status.getRocketPosition().add(k1.v.multiply(store.timestep / 2))); - status2.setRocketVelocity(status.getRocketVelocity().add(k1.a.multiply(store.timestep / 2))); - status2.setRocketOrientationQuaternion(status.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(k1.rv.multiply(store.timestep / 2)))); - status2.setRocketRotationVelocity(status.getRocketRotationVelocity().add(k1.ra.multiply(store.timestep / 2))); - - k2 = computeParameters(status2, store); - - - //// Third position, k3 = f(t + h/2, y + k2*h/2) - - status2 = status.clone(); - status2.setSimulationTime(status.getSimulationTime() + store.timestep / 2); - status2.setRocketPosition(status.getRocketPosition().add(k2.v.multiply(store.timestep / 2))); - status2.setRocketVelocity(status.getRocketVelocity().add(k2.a.multiply(store.timestep / 2))); - status2.setRocketOrientationQuaternion(status2.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(k2.rv.multiply(store.timestep / 2)))); - status2.setRocketRotationVelocity(status.getRocketRotationVelocity().add(k2.ra.multiply(store.timestep / 2))); - - k3 = computeParameters(status2, store); - - - //// Fourth position, k4 = f(t + h, y + k3*h) - - status2 = status.clone(); - status2.setSimulationTime(status.getSimulationTime() + store.timestep); - status2.setRocketPosition(status.getRocketPosition().add(k3.v.multiply(store.timestep))); - status2.setRocketVelocity(status.getRocketVelocity().add(k3.a.multiply(store.timestep))); - status2.setRocketOrientationQuaternion(status2.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(k3.rv.multiply(store.timestep)))); - status2.setRocketRotationVelocity(status.getRocketRotationVelocity().add(k3.ra.multiply(store.timestep))); - - k4 = computeParameters(status2, store); - - - //// Sum all together, y(n+1) = y(n) + h*(k1 + 2*k2 + 2*k3 + k4)/6 - - - - Coordinate deltaV, deltaP, deltaR, deltaO; - deltaV = k2.a.add(k3.a).multiply(2).add(k1.a).add(k4.a).multiply(store.timestep / 6); - deltaP = k2.v.add(k3.v).multiply(2).add(k1.v).add(k4.v).multiply(store.timestep / 6); - deltaR = k2.ra.add(k3.ra).multiply(2).add(k1.ra).add(k4.ra).multiply(store.timestep / 6); - deltaO = k2.rv.add(k3.rv).multiply(2).add(k1.rv).add(k4.rv).multiply(store.timestep / 6); - - - - status.setRocketVelocity(status.getRocketVelocity().add(deltaV)); - status.setRocketPosition(status.getRocketPosition().add(deltaP)); - status.setRocketRotationVelocity(status.getRocketRotationVelocity().add(deltaR)); - status.setRocketOrientationQuaternion(status.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(deltaO)).normalizeIfNecessary()); - - WorldCoordinate w = status.getSimulationConditions().getLaunchSite(); - w = status.getSimulationConditions().getGeodeticComputation().addCoordinate(w, status.getRocketPosition()); - status.setRocketWorldPosition(w); - - status.setSimulationTime(status.getSimulationTime() + store.timestep); - - status.setPreviousTimeStep(store.timestep); - - // Verify that values don't run out of range - if (status.getRocketVelocity().length2() > 1e18 || - status.getRocketPosition().length2() > 1e18 || - status.getRocketRotationVelocity().length2() > 1e18) { - throw new SimulationCalculationException(trans.get("error.valuesTooLarge")); - } - } - - - - - - private RK4Parameters computeParameters(RK4SimulationStatus status, DataStore dataStore) - throws SimulationException { - RK4Parameters params = new RK4Parameters(); - - // if (dataStore == null) { - // dataStore = new DataStore(); - // } - - calculateAcceleration(status, dataStore); - params.a = dataStore.linearAcceleration; - params.ra = dataStore.angularAcceleration; - params.v = status.getRocketVelocity(); - params.rv = status.getRocketRotationVelocity(); - - checkNaN(params.a); - checkNaN(params.ra); - checkNaN(params.v); - checkNaN(params.rv); - - return params; - } - - - - - - /** - * Calculate the linear and angular acceleration at the given status. The results - * are stored in the fields {@link #linearAcceleration} and {@link #angularAcceleration}. - * - * @param status the status of the rocket. - * @throws SimulationException - */ - private void calculateAcceleration(RK4SimulationStatus status, DataStore store) throws SimulationException { - - // Call pre-listeners - store.accelerationData = SimulationListenerHelper.firePreAccelerationCalculation(status); - if (store.accelerationData != null) { - return; - } - - // Compute the forces affecting the rocket - calculateForces(status, store); - - // Calculate mass data - store.massData = calculateMassData(status); - - - // Calculate the forces from the aerodynamic coefficients - - double dynP = (0.5 * store.flightConditions.getAtmosphericConditions().getDensity() * - MathUtil.pow2(store.flightConditions.getVelocity())); - double refArea = store.flightConditions.getRefArea(); - double refLength = store.flightConditions.getRefLength(); - - - // Linear forces in rocket coordinates - store.dragForce = store.forces.getCaxial() * dynP * refArea; - double fN = store.forces.getCN() * dynP * refArea; - double fSide = store.forces.getCside() * dynP * refArea; - - double forceZ = store.thrustForce - store.dragForce; - - store.linearAcceleration = new Coordinate(-fN / store.massData.getCG().weight, - -fSide / store.massData.getCG().weight, - forceZ / store.massData.getCG().weight); - - store.linearAcceleration = store.thetaRotation.rotateZ(store.linearAcceleration); - - // Convert into rocket world coordinates - store.linearAcceleration = status.getRocketOrientationQuaternion().rotate(store.linearAcceleration); - - // add effect of gravity - store.gravity = modelGravity(status); - store.linearAcceleration = store.linearAcceleration.sub(0, 0, store.gravity); - - // add effect of Coriolis acceleration - store.coriolisAcceleration = status.getSimulationConditions().getGeodeticComputation() - .getCoriolisAcceleration(status.getRocketWorldPosition(), status.getRocketVelocity()); - store.linearAcceleration = store.linearAcceleration.add(store.coriolisAcceleration); - - // If still on the launch rod, project acceleration onto launch rod direction and - // set angular acceleration to zero. - if (!status.isLaunchRodCleared()) { - - store.linearAcceleration = status.getLaunchRodDirection().multiply( - store.linearAcceleration.dot(status.getLaunchRodDirection())); - store.angularAcceleration = Coordinate.NUL; - store.rollAcceleration = 0; - store.lateralPitchAcceleration = 0; - - } else { - - // Shift moments to CG - double Cm = store.forces.getCm() - store.forces.getCN() * store.massData.getCG().x / refLength; - double Cyaw = store.forces.getCyaw() - store.forces.getCside() * store.massData.getCG().x / refLength; - - // Compute moments - double momX = -Cyaw * dynP * refArea * refLength; - double momY = Cm * dynP * refArea * refLength; - double momZ = store.forces.getCroll() * dynP * refArea * refLength; - - // Compute acceleration in rocket coordinates - store.angularAcceleration = new Coordinate(momX / store.massData.getLongitudinalInertia(), - momY / store.massData.getLongitudinalInertia(), - momZ / store.massData.getRotationalInertia()); - - store.rollAcceleration = store.angularAcceleration.z; - // TODO: LOW: This should be hypot, but does it matter? - store.lateralPitchAcceleration = MathUtil.max(Math.abs(store.angularAcceleration.x), - Math.abs(store.angularAcceleration.y)); - - store.angularAcceleration = store.thetaRotation.rotateZ(store.angularAcceleration); - - // Convert to world coordinates - store.angularAcceleration = status.getRocketOrientationQuaternion().rotate(store.angularAcceleration); - - } - - // Call post-listeners - store.accelerationData = SimulationListenerHelper.firePostAccelerationCalculation(status, store.accelerationData); - } - - - /** - * Calculate the aerodynamic forces into the data store. This method also handles - * whether to include aerodynamic computation warnings or not. - */ - private void calculateForces(RK4SimulationStatus status, DataStore store) throws SimulationException { - - // Call pre-listeners - store.forces = SimulationListenerHelper.firePreAerodynamicCalculation(status); - if (store.forces != null) { - return; - } - - // Compute flight conditions - calculateFlightConditions(status, store); - - /* - * Check whether to store warnings or not. Warnings are ignored when on the - * launch rod or 0.25 seconds after departure, and when the velocity has dropped - * below 20% of the max. velocity. - */ - WarningSet warnings = status.getWarnings(); - status.setMaxZVelocity(MathUtil.max(status.getMaxZVelocity(), status.getRocketVelocity().z)); - - if (!status.isLaunchRodCleared()) { - warnings = null; - } else { - if (status.getRocketVelocity().z < 0.2 * status.getMaxZVelocity()) - warnings = null; - if (status.getStartWarningTime() < 0) - status.setStartWarningTime(status.getSimulationTime() + 0.25); - } - if (status.getSimulationTime() < status.getStartWarningTime()) - warnings = null; - - - // Calculate aerodynamic forces - store.forces = status.getSimulationConditions().getAerodynamicCalculator() - .getAerodynamicForces(status.getConfiguration(), store.flightConditions, warnings); - - - // Add very small randomization to yaw & pitch moments to prevent over-perfect flight - // TODO: HIGH: This should rather be performed as a listener - store.forces.setCm(store.forces.getCm() + (PITCH_YAW_RANDOM * 2 * (random.nextDouble() - 0.5))); - store.forces.setCyaw(store.forces.getCyaw() + (PITCH_YAW_RANDOM * 2 * (random.nextDouble() - 0.5))); - - - // Call post-listeners - store.forces = SimulationListenerHelper.firePostAerodynamicCalculation(status, store.forces); - } - - - - /** - * Calculate and return the flight conditions for the current rocket status. - * Listeners can override these if necessary. - * <p> - * Additionally the fields thetaRotation and lateralPitchRate are defined in - * the data store, and can be used after calling this method. - */ - private void calculateFlightConditions(RK4SimulationStatus status, DataStore store) - throws SimulationException { - - // Call pre listeners, allow complete override - store.flightConditions = SimulationListenerHelper.firePreFlightConditions( - status); - if (store.flightConditions != null) { - // Compute the store values - store.thetaRotation = new Rotation2D(store.flightConditions.getTheta()); - store.lateralPitchRate = Math.hypot(store.flightConditions.getPitchRate(), store.flightConditions.getYawRate()); - return; - } - - - - //// Atmospheric conditions - AtmosphericConditions atmosphere = modelAtmosphericConditions(status); - store.flightConditions = new FlightConditions(status.getConfiguration()); - store.flightConditions.setAtmosphericConditions(atmosphere); - - - //// Local wind speed and direction - Coordinate windSpeed = modelWindVelocity(status); - Coordinate airSpeed = status.getRocketVelocity().add(windSpeed); - airSpeed = status.getRocketOrientationQuaternion().invRotate(airSpeed); - - - // Lateral direction: - double len = MathUtil.hypot(airSpeed.x, airSpeed.y); - if (len > 0.0001) { - store.thetaRotation = new Rotation2D(airSpeed.y / len, airSpeed.x / len); - store.flightConditions.setTheta(Math.atan2(airSpeed.y, airSpeed.x)); - } else { - store.thetaRotation = Rotation2D.ID; - store.flightConditions.setTheta(0); - } - - double velocity = airSpeed.length(); - store.flightConditions.setVelocity(velocity); - if (velocity > 0.01) { - // aoa must be calculated from the monotonous cosine - // sine can be calculated by a simple division - store.flightConditions.setAOA(Math.acos(airSpeed.z / velocity), len / velocity); - } else { - store.flightConditions.setAOA(0); - } - - - // Roll, pitch and yaw rate - Coordinate rot = status.getRocketOrientationQuaternion().invRotate(status.getRocketRotationVelocity()); - rot = store.thetaRotation.invRotateZ(rot); - - store.flightConditions.setRollRate(rot.z); - if (len < 0.001) { - store.flightConditions.setPitchRate(0); - store.flightConditions.setYawRate(0); - store.lateralPitchRate = 0; - } else { - store.flightConditions.setPitchRate(rot.y); - store.flightConditions.setYawRate(rot.x); - // TODO: LOW: set this as power of two? - store.lateralPitchRate = MathUtil.hypot(rot.x, rot.y); - } - - - // Call post listeners - FlightConditions c = SimulationListenerHelper.firePostFlightConditions( - status, store.flightConditions); - if (c != store.flightConditions) { - // Listeners changed the values, recalculate data store - store.flightConditions = c; - store.thetaRotation = new Rotation2D(store.flightConditions.getTheta()); - store.lateralPitchRate = Math.hypot(store.flightConditions.getPitchRate(), store.flightConditions.getYawRate()); - } - - } - - - - private void storeData(RK4SimulationStatus status, DataStore store) { - - FlightDataBranch data = status.getFlightData(); - boolean extra = status.getSimulationConditions().isCalculateExtras(); - - data.addPoint(); - data.setValue(FlightDataType.TYPE_TIME, status.getSimulationTime()); - data.setValue(FlightDataType.TYPE_ALTITUDE, status.getRocketPosition().z); - data.setValue(FlightDataType.TYPE_POSITION_X, status.getRocketPosition().x); - data.setValue(FlightDataType.TYPE_POSITION_Y, status.getRocketPosition().y); - - data.setValue(FlightDataType.TYPE_LATITUDE, status.getRocketWorldPosition().getLatitudeRad()); - data.setValue(FlightDataType.TYPE_LONGITUDE, status.getRocketWorldPosition().getLongitudeRad()); - if (status.getSimulationConditions().getGeodeticComputation() != GeodeticComputationStrategy.FLAT) { - data.setValue(FlightDataType.TYPE_CORIOLIS_ACCELERATION, store.coriolisAcceleration.length()); - } - - if (extra) { - data.setValue(FlightDataType.TYPE_POSITION_XY, - MathUtil.hypot(status.getRocketPosition().x, status.getRocketPosition().y)); - data.setValue(FlightDataType.TYPE_POSITION_DIRECTION, - Math.atan2(status.getRocketPosition().y, status.getRocketPosition().x)); - - data.setValue(FlightDataType.TYPE_VELOCITY_XY, - MathUtil.hypot(status.getRocketVelocity().x, status.getRocketVelocity().y)); - - if (store.linearAcceleration != null) { - data.setValue(FlightDataType.TYPE_ACCELERATION_XY, - MathUtil.hypot(store.linearAcceleration.x, store.linearAcceleration.y)); - - data.setValue(FlightDataType.TYPE_ACCELERATION_TOTAL, store.linearAcceleration.length()); - } - - if (store.flightConditions != null) { - double Re = (store.flightConditions.getVelocity() * - status.getConfiguration().getLength() / - store.flightConditions.getAtmosphericConditions().getKinematicViscosity()); - data.setValue(FlightDataType.TYPE_REYNOLDS_NUMBER, Re); - } - } - - data.setValue(FlightDataType.TYPE_VELOCITY_Z, status.getRocketVelocity().z); - if (store.linearAcceleration != null) { - data.setValue(FlightDataType.TYPE_ACCELERATION_Z, store.linearAcceleration.z); - } - - if (store.flightConditions != null) { - data.setValue(FlightDataType.TYPE_VELOCITY_TOTAL, status.getRocketVelocity().length()); - data.setValue(FlightDataType.TYPE_MACH_NUMBER, store.flightConditions.getMach()); - } - - if (store.massData != null) { - data.setValue(FlightDataType.TYPE_CG_LOCATION, store.massData.getCG().x); - } - if (status.isLaunchRodCleared()) { - // Don't include CP and stability with huge launch AOA - if (store.forces != null) { - data.setValue(FlightDataType.TYPE_CP_LOCATION, store.forces.getCP().x); - } - if (store.forces != null && store.flightConditions != null && store.massData != null) { - data.setValue(FlightDataType.TYPE_STABILITY, - (store.forces.getCP().x - store.massData.getCG().x) / store.flightConditions.getRefLength()); - } - } - if (store.massData != null) { - data.setValue(FlightDataType.TYPE_MASS, store.massData.getCG().weight); - data.setValue(FlightDataType.TYPE_PROPELLANT_MASS, store.massData.getPropellantMass()); - data.setValue(FlightDataType.TYPE_LONGITUDINAL_INERTIA, store.massData.getLongitudinalInertia()); - data.setValue(FlightDataType.TYPE_ROTATIONAL_INERTIA, store.massData.getRotationalInertia()); - } - - data.setValue(FlightDataType.TYPE_THRUST_FORCE, store.thrustForce); - data.setValue(FlightDataType.TYPE_DRAG_FORCE, store.dragForce); - data.setValue(FlightDataType.TYPE_GRAVITY, store.gravity); - - if (status.isLaunchRodCleared() && store.forces != null) { - if (store.massData != null && store.flightConditions != null) { - data.setValue(FlightDataType.TYPE_PITCH_MOMENT_COEFF, - store.forces.getCm() - store.forces.getCN() * store.massData.getCG().x / store.flightConditions.getRefLength()); - data.setValue(FlightDataType.TYPE_YAW_MOMENT_COEFF, - store.forces.getCyaw() - store.forces.getCside() * store.massData.getCG().x / store.flightConditions.getRefLength()); - } - data.setValue(FlightDataType.TYPE_NORMAL_FORCE_COEFF, store.forces.getCN()); - data.setValue(FlightDataType.TYPE_SIDE_FORCE_COEFF, store.forces.getCside()); - data.setValue(FlightDataType.TYPE_ROLL_MOMENT_COEFF, store.forces.getCroll()); - data.setValue(FlightDataType.TYPE_ROLL_FORCING_COEFF, store.forces.getCrollForce()); - data.setValue(FlightDataType.TYPE_ROLL_DAMPING_COEFF, store.forces.getCrollDamp()); - data.setValue(FlightDataType.TYPE_PITCH_DAMPING_MOMENT_COEFF, - store.forces.getPitchDampingMoment()); - } - - if (store.forces != null) { - data.setValue(FlightDataType.TYPE_DRAG_COEFF, store.forces.getCD()); - data.setValue(FlightDataType.TYPE_AXIAL_DRAG_COEFF, store.forces.getCaxial()); - data.setValue(FlightDataType.TYPE_FRICTION_DRAG_COEFF, store.forces.getFrictionCD()); - data.setValue(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, store.forces.getPressureCD()); - data.setValue(FlightDataType.TYPE_BASE_DRAG_COEFF, store.forces.getBaseCD()); - } - - if (store.flightConditions != null) { - data.setValue(FlightDataType.TYPE_REFERENCE_LENGTH, store.flightConditions.getRefLength()); - data.setValue(FlightDataType.TYPE_REFERENCE_AREA, store.flightConditions.getRefArea()); - - data.setValue(FlightDataType.TYPE_PITCH_RATE, store.flightConditions.getPitchRate()); - data.setValue(FlightDataType.TYPE_YAW_RATE, store.flightConditions.getYawRate()); - data.setValue(FlightDataType.TYPE_ROLL_RATE, store.flightConditions.getRollRate()); - - data.setValue(FlightDataType.TYPE_AOA, store.flightConditions.getAOA()); - } - - - if (extra) { - Coordinate c = status.getRocketOrientationQuaternion().rotateZ(); - double theta = Math.atan2(c.z, MathUtil.hypot(c.x, c.y)); - double phi = Math.atan2(c.y, c.x); - if (phi < -(Math.PI - 0.0001)) - phi = Math.PI; - data.setValue(FlightDataType.TYPE_ORIENTATION_THETA, theta); - data.setValue(FlightDataType.TYPE_ORIENTATION_PHI, phi); - } - - data.setValue(FlightDataType.TYPE_WIND_VELOCITY, store.windSpeed); - - if (store.flightConditions != null) { - data.setValue(FlightDataType.TYPE_AIR_TEMPERATURE, - store.flightConditions.getAtmosphericConditions().getTemperature()); - data.setValue(FlightDataType.TYPE_AIR_PRESSURE, - store.flightConditions.getAtmosphericConditions().getPressure()); - data.setValue(FlightDataType.TYPE_SPEED_OF_SOUND, - store.flightConditions.getAtmosphericConditions().getMachSpeed()); - } - - - data.setValue(FlightDataType.TYPE_TIME_STEP, store.timestep); - data.setValue(FlightDataType.TYPE_COMPUTATION_TIME, - (System.nanoTime() - status.getSimulationStartWallTime()) / 1000000000.0); - } - - - - - private static class RK4Parameters { - /** Linear acceleration */ - public Coordinate a; - /** Linear velocity */ - public Coordinate v; - /** Rotational acceleration */ - public Coordinate ra; - /** Rotational velocity */ - public Coordinate rv; - } - - private static class DataStore { - public double timestep = Double.NaN; - - public AccelerationData accelerationData; - - public AtmosphericConditions atmosphericConditions; - - public FlightConditions flightConditions; - - public double longitudinalAcceleration = Double.NaN; - - public MassData massData; - - public Coordinate coriolisAcceleration; - - public Coordinate linearAcceleration; - public Coordinate angularAcceleration; - - // set by calculateFlightConditions and calculateAcceleration: - public AerodynamicForces forces; - public double windSpeed = Double.NaN; - public double gravity = Double.NaN; - public double thrustForce = Double.NaN; - public double dragForce = Double.NaN; - public double lateralPitchRate = Double.NaN; - - public double rollAcceleration = Double.NaN; - public double lateralPitchAcceleration = Double.NaN; - - public Rotation2D thetaRotation; - - } - -} diff --git a/core/src/net/sf/openrocket/simulation/SimulationConditions.java b/core/src/net/sf/openrocket/simulation/SimulationConditions.java deleted file mode 100644 index ffd9e003..00000000 --- a/core/src/net/sf/openrocket/simulation/SimulationConditions.java +++ /dev/null @@ -1,300 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.models.atmosphere.AtmosphericModel; -import net.sf.openrocket.models.gravity.GravityModel; -import net.sf.openrocket.models.wind.WindModel; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.simulation.listeners.SimulationListener; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.GeodeticComputationStrategy; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.WorldCoordinate; - -/** - * A holder class for the simulation conditions. These include conditions that do not change - * during the flight of a rocket, for example launch rod parameters, atmospheric models, - * aerodynamic calculators etc. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationConditions implements Monitorable, Cloneable { - - private Rocket rocket; - private String motorID = null; - - private Simulation simulation; // The parent simulation - - private double launchRodLength = 1; - - /** Launch rod angle >= 0, radians from vertical */ - private double launchRodAngle = 0; - - /** Launch rod direction, 0 = upwind, PI = downwind. */ - private double launchRodDirection = 0; - - // TODO: Depreciate these and use worldCoordinate only. - //private double launchAltitude = 0; - //private double launchLatitude = 45; - //private double launchLongitude = 0; - private WorldCoordinate launchSite = new WorldCoordinate(0, 0, 0); - private GeodeticComputationStrategy geodeticComputation = GeodeticComputationStrategy.SPHERICAL; - - - private WindModel windModel; - private AtmosphericModel atmosphericModel; - private GravityModel gravityModel; - - private AerodynamicCalculator aerodynamicCalculator; - private MassCalculator massCalculator; - - - private double timeStep = RK4SimulationStepper.RECOMMENDED_TIME_STEP; - private double maximumAngleStep = RK4SimulationStepper.RECOMMENDED_ANGLE_STEP; - - /* Whether to calculate additional data or only primary simulation figures */ - private boolean calculateExtras = true; - - - private List<SimulationListener> simulationListeners = new ArrayList<SimulationListener>(); - - - private int randomSeed = 0; - - private int modID = 0; - private int modIDadd = 0; - - - - - public AerodynamicCalculator getAerodynamicCalculator() { - return aerodynamicCalculator; - } - - - public void setAerodynamicCalculator(AerodynamicCalculator aerodynamicCalculator) { - if (this.aerodynamicCalculator != null) - this.modIDadd += this.aerodynamicCalculator.getModID(); - this.modID++; - this.aerodynamicCalculator = aerodynamicCalculator; - } - - public MassCalculator getMassCalculator() { - return massCalculator; - } - - - public void setMassCalculator(MassCalculator massCalculator) { - if (this.massCalculator != null) - this.modIDadd += this.massCalculator.getModID(); - this.modID++; - this.massCalculator = massCalculator; - } - - - public Rocket getRocket() { - return rocket; - } - - - public void setRocket(Rocket rocket) { - if (this.rocket != null) - this.modIDadd += this.rocket.getModID(); - this.modID++; - this.rocket = rocket; - } - - - public String getMotorConfigurationID() { - return motorID; - } - - - public void setMotorConfigurationID(String motorID) { - this.motorID = motorID; - this.modID++; - } - - - public double getLaunchRodLength() { - return launchRodLength; - } - - - public void setLaunchRodLength(double launchRodLength) { - this.launchRodLength = launchRodLength; - this.modID++; - } - - - public double getLaunchRodAngle() { - return launchRodAngle; - } - - - public void setLaunchRodAngle(double launchRodAngle) { - this.launchRodAngle = launchRodAngle; - this.modID++; - } - - - public double getLaunchRodDirection() { - return launchRodDirection; - } - - - public void setLaunchRodDirection(double launchRodDirection) { - this.launchRodDirection = launchRodDirection; - this.modID++; - } - - - public WorldCoordinate getLaunchSite() { - return this.launchSite; - } - - public void setLaunchSite(WorldCoordinate site) { - if (this.launchSite.equals(site)) - return; - this.launchSite = site; - this.modID++; - } - - - public GeodeticComputationStrategy getGeodeticComputation() { - return geodeticComputation; - } - - public void setGeodeticComputation(GeodeticComputationStrategy geodeticComputation) { - if (this.geodeticComputation == geodeticComputation) - return; - if (geodeticComputation == null) { - throw new IllegalArgumentException("strategy cannot be null"); - } - this.geodeticComputation = geodeticComputation; - this.modID++; - } - - - public WindModel getWindModel() { - return windModel; - } - - - public void setWindModel(WindModel windModel) { - if (this.windModel != null) - this.modIDadd += this.windModel.getModID(); - this.modID++; - this.windModel = windModel; - } - - - public AtmosphericModel getAtmosphericModel() { - return atmosphericModel; - } - - - public void setAtmosphericModel(AtmosphericModel atmosphericModel) { - if (this.atmosphericModel != null) - this.modIDadd += this.atmosphericModel.getModID(); - this.modID++; - this.atmosphericModel = atmosphericModel; - } - - - public GravityModel getGravityModel() { - return gravityModel; - } - - - public void setGravityModel(GravityModel gravityModel) { - //if (this.gravityModel != null) - // this.modIDadd += this.gravityModel.getModID(); - this.modID++; - this.gravityModel = gravityModel; - } - - - public double getTimeStep() { - return timeStep; - } - - - public void setTimeStep(double timeStep) { - this.timeStep = timeStep; - this.modID++; - } - - - public double getMaximumAngleStep() { - return maximumAngleStep; - } - - - public void setMaximumAngleStep(double maximumAngle) { - this.maximumAngleStep = maximumAngle; - this.modID++; - } - - - public boolean isCalculateExtras() { - return calculateExtras; - } - - - public void setCalculateExtras(boolean calculateExtras) { - this.calculateExtras = calculateExtras; - this.modID++; - } - - - - public int getRandomSeed() { - return randomSeed; - } - - - public void setRandomSeed(int randomSeed) { - this.randomSeed = randomSeed; - this.modID++; - } - - public void setSimulation(Simulation sim) { - this.simulation = sim; - } - - public Simulation getSimulation(){ - return this.simulation; - } - - // TODO: HIGH: Make cleaner - public List<SimulationListener> getSimulationListenerList() { - return simulationListeners; - } - - - @Override - public int getModID() { - //return (modID + modIDadd + rocket.getModID() + windModel.getModID() + atmosphericModel.getModID() + - // gravityModel.getModID() + aerodynamicCalculator.getModID() + massCalculator.getModID()); - return (modID + modIDadd + rocket.getModID() + windModel.getModID() + atmosphericModel.getModID() + - aerodynamicCalculator.getModID() + massCalculator.getModID()); - } - - - @Override - public SimulationConditions clone() { - try { - // TODO: HIGH: Deep clone models - return (SimulationConditions) super.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException(e); - } - } - -} diff --git a/core/src/net/sf/openrocket/simulation/SimulationEngine.java b/core/src/net/sf/openrocket/simulation/SimulationEngine.java deleted file mode 100644 index b70e82bc..00000000 --- a/core/src/net/sf/openrocket/simulation/SimulationEngine.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.simulation.exception.SimulationException; - -/** - * A simulation engine that controls the flow of a simulation. This typically maintains - * flight events and related actions, while continuously calling a SimulationStepper to - * move the rocket forward step by step. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public interface SimulationEngine { - - /** - * Simulate the flight of a rocket. - * - * @param simulation the simulation conditions which to simulate. - * @return a FlightData object containing the simulated data. - * @throws SimulationException if an error occurs during simulation - */ - public FlightData simulate(SimulationConditions simulation) - throws SimulationException; - -} diff --git a/core/src/net/sf/openrocket/simulation/SimulationOptions.java b/core/src/net/sf/openrocket/simulation/SimulationOptions.java deleted file mode 100644 index a1b6bae9..00000000 --- a/core/src/net/sf/openrocket/simulation/SimulationOptions.java +++ /dev/null @@ -1,542 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.ArrayList; -import java.util.EventListener; -import java.util.EventObject; -import java.util.List; -import java.util.Random; -import java.util.Set; - -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.models.atmosphere.AtmosphericModel; -import net.sf.openrocket.models.atmosphere.ExtendedISAModel; -import net.sf.openrocket.models.gravity.GravityModel; -import net.sf.openrocket.models.gravity.WGSGravityModel; -import net.sf.openrocket.models.wind.PinkNoiseWindModel; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.ChangeSource; -import net.sf.openrocket.util.GeodeticComputationStrategy; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.StateChangeListener; -import net.sf.openrocket.util.Utils; -import net.sf.openrocket.util.WorldCoordinate; - -/** - * A class holding simulation options in basic parameter form and which functions - * as a ChangeSource. A SimulationConditions instance is generated from this class - * using {@link #toSimulationConditions()}. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationOptions implements ChangeSource, Cloneable { - - private static final LogHelper log = Application.getLogger(); - - public static final double MAX_LAUNCH_ROD_ANGLE = Math.PI / 3; - - /** - * The ISA standard atmosphere. - */ - private static final AtmosphericModel ISA_ATMOSPHERIC_MODEL = new ExtendedISAModel(); - - - private final Rocket rocket; - private String motorID = null; - - - /* - * NOTE: When adding/modifying parameters, they must also be added to the - * equals and copyFrom methods!! - */ - - // TODO: HIGH: Fetch default values from Prefs! - - private double launchRodLength = 1; - - /** Launch rod angle > 0, radians from vertical */ - private double launchRodAngle = 0; - - /** Launch rod direction, 0 = upwind, PI = downwind. */ - private double launchRodDirection = 0; - - - private double windAverage = 2.0; - private double windTurbulence = 0.1; - - - /* - * SimulationOptions maintains the launch site parameters as separate double values, - * and converts them into a WorldCoordinate when converting to SimulationConditions. - */ - private double launchAltitude = 0; - private double launchLatitude = 45; - private double launchLongitude = 0; - private GeodeticComputationStrategy geodeticComputation = GeodeticComputationStrategy.SPHERICAL; - - private boolean useISA = true; - private double launchTemperature = ExtendedISAModel.STANDARD_TEMPERATURE; - private double launchPressure = ExtendedISAModel.STANDARD_PRESSURE; - - - private double timeStep = RK4SimulationStepper.RECOMMENDED_TIME_STEP; - private double maximumAngle = RK4SimulationStepper.RECOMMENDED_ANGLE_STEP; - - private int randomSeed = new Random().nextInt(); - - private boolean calculateExtras = true; - - - private List<EventListener> listeners = new ArrayList<EventListener>(); - - - - public SimulationOptions(Rocket rocket) { - this.rocket = rocket; - } - - public Rocket getRocket() { - return rocket; - } - - - public String getMotorConfigurationID() { - return motorID; - } - - /** - * Set the motor configuration ID. This must be a valid motor configuration ID of - * the rocket, otherwise the configuration is set to <code>null</code>. - * - * @param id the configuration to set. - */ - public void setMotorConfigurationID(String id) { - if (id != null) - id = id.intern(); - if (!rocket.isMotorConfigurationID(id)) - id = null; - if (id == motorID) - return; - motorID = id; - fireChangeEvent(); - } - - - public double getLaunchRodLength() { - return launchRodLength; - } - - public void setLaunchRodLength(double launchRodLength) { - if (MathUtil.equals(this.launchRodLength, launchRodLength)) - return; - this.launchRodLength = launchRodLength; - fireChangeEvent(); - } - - - public double getLaunchRodAngle() { - return launchRodAngle; - } - - public void setLaunchRodAngle(double launchRodAngle) { - launchRodAngle = MathUtil.clamp(launchRodAngle, 0, MAX_LAUNCH_ROD_ANGLE); - if (MathUtil.equals(this.launchRodAngle, launchRodAngle)) - return; - this.launchRodAngle = launchRodAngle; - fireChangeEvent(); - } - - - public double getLaunchRodDirection() { - return launchRodDirection; - } - - public void setLaunchRodDirection(double launchRodDirection) { - launchRodDirection = MathUtil.reduce180(launchRodDirection); - if (MathUtil.equals(this.launchRodDirection, launchRodDirection)) - return; - this.launchRodDirection = launchRodDirection; - fireChangeEvent(); - } - - - - public double getWindSpeedAverage() { - return windAverage; - } - - public void setWindSpeedAverage(double windAverage) { - if (MathUtil.equals(this.windAverage, windAverage)) - return; - this.windAverage = MathUtil.max(windAverage, 0); - fireChangeEvent(); - } - - - public double getWindSpeedDeviation() { - return windAverage * windTurbulence; - } - - public void setWindSpeedDeviation(double windDeviation) { - if (windAverage < 0.1) { - windAverage = 0.1; - } - setWindTurbulenceIntensity(windDeviation / windAverage); - } - - - /** - * Return the wind turbulence intensity (standard deviation / average). - * - * @return the turbulence intensity - */ - public double getWindTurbulenceIntensity() { - return windTurbulence; - } - - /** - * Set the wind standard deviation to match the given turbulence intensity. - * - * @param intensity the turbulence intensity - */ - public void setWindTurbulenceIntensity(double intensity) { - // Does not check equality so that setWindSpeedDeviation can be sure of event firing - this.windTurbulence = intensity; - fireChangeEvent(); - } - - - - - - public double getLaunchAltitude() { - return launchAltitude; - } - - public void setLaunchAltitude(double altitude) { - if (MathUtil.equals(this.launchAltitude, altitude)) - return; - this.launchAltitude = altitude; - fireChangeEvent(); - } - - - public double getLaunchLatitude() { - return launchLatitude; - } - - public void setLaunchLatitude(double launchLatitude) { - launchLatitude = MathUtil.clamp(launchLatitude, -90, 90); - if (MathUtil.equals(this.launchLatitude, launchLatitude)) - return; - this.launchLatitude = launchLatitude; - fireChangeEvent(); - } - - public double getLaunchLongitude() { - return launchLongitude; - } - - public void setLaunchLongitude(double launchLongitude) { - launchLongitude = MathUtil.clamp(launchLongitude, -180, 180); - if (MathUtil.equals(this.launchLongitude, launchLongitude)) - return; - this.launchLongitude = launchLongitude; - fireChangeEvent(); - } - - - public GeodeticComputationStrategy getGeodeticComputation() { - return geodeticComputation; - } - - public void setGeodeticComputation(GeodeticComputationStrategy geodeticComputation) { - if (this.geodeticComputation == geodeticComputation) - return; - if (geodeticComputation == null) { - throw new IllegalArgumentException("strategy cannot be null"); - } - this.geodeticComputation = geodeticComputation; - fireChangeEvent(); - } - - - public boolean isISAAtmosphere() { - return useISA; - } - - public void setISAAtmosphere(boolean isa) { - if (isa == useISA) - return; - useISA = isa; - fireChangeEvent(); - } - - - public double getLaunchTemperature() { - return launchTemperature; - } - - - - public void setLaunchTemperature(double launchTemperature) { - if (MathUtil.equals(this.launchTemperature, launchTemperature)) - return; - this.launchTemperature = launchTemperature; - fireChangeEvent(); - } - - - - public double getLaunchPressure() { - return launchPressure; - } - - - - public void setLaunchPressure(double launchPressure) { - if (MathUtil.equals(this.launchPressure, launchPressure)) - return; - this.launchPressure = launchPressure; - fireChangeEvent(); - } - - - /** - * Returns an atmospheric model corresponding to the launch conditions. The - * atmospheric models may be shared between different calls. - * - * @return an AtmosphericModel object. - */ - private AtmosphericModel getAtmosphericModel() { - if (useISA) { - return ISA_ATMOSPHERIC_MODEL; - } - return new ExtendedISAModel(getLaunchAltitude(), launchTemperature, launchPressure); - } - - - public double getTimeStep() { - return timeStep; - } - - public void setTimeStep(double timeStep) { - if (MathUtil.equals(this.timeStep, timeStep)) - return; - this.timeStep = timeStep; - fireChangeEvent(); - } - - public double getMaximumStepAngle() { - return maximumAngle; - } - - public void setMaximumStepAngle(double maximumAngle) { - maximumAngle = MathUtil.clamp(maximumAngle, 1 * Math.PI / 180, 20 * Math.PI / 180); - if (MathUtil.equals(this.maximumAngle, maximumAngle)) - return; - this.maximumAngle = maximumAngle; - fireChangeEvent(); - } - - - - public boolean getCalculateExtras() { - return calculateExtras; - } - - - - public void setCalculateExtras(boolean calculateExtras) { - if (this.calculateExtras == calculateExtras) - return; - this.calculateExtras = calculateExtras; - fireChangeEvent(); - } - - - - public int getRandomSeed() { - return randomSeed; - } - - public void setRandomSeed(int randomSeed) { - if (this.randomSeed == randomSeed) { - return; - } - this.randomSeed = randomSeed; - /* - * This does not fire an event since we don't want to invalidate simulation results - * due to changing the seed value. This needs to be revisited if the user is ever - * allowed to select the seed value. - */ - // fireChangeEvent(); - } - - /** - * Randomize the random seed value. - */ - public void randomizeSeed() { - this.randomSeed = new Random().nextInt(); - // fireChangeEvent(); - } - - - - @Override - public SimulationOptions clone() { - try { - SimulationOptions copy = (SimulationOptions) super.clone(); - copy.listeners = new ArrayList<EventListener>(); - return copy; - } catch (CloneNotSupportedException e) { - throw new BugException(e); - } - } - - - public void copyFrom(SimulationOptions src) { - - if (this.rocket == src.rocket) { - - this.motorID = src.motorID; - - } else { - - if (src.rocket.hasMotors(src.motorID)) { - // Try to find a matching motor ID - String motorDesc = src.rocket.getMotorConfigurationDescription(src.motorID); - String matchID = null; - - for (String id : this.rocket.getMotorConfigurationIDs()) { - if (motorDesc.equals(this.rocket.getMotorConfigurationDescription(id))) { - matchID = id; - break; - } - } - - this.motorID = matchID; - } else { - this.motorID = null; - } - } - - this.launchAltitude = src.launchAltitude; - this.launchLatitude = src.launchLatitude; - this.launchLongitude = src.launchLongitude; - this.launchPressure = src.launchPressure; - this.launchRodAngle = src.launchRodAngle; - this.launchRodDirection = src.launchRodDirection; - this.launchRodLength = src.launchRodLength; - this.launchTemperature = src.launchTemperature; - this.maximumAngle = src.maximumAngle; - this.timeStep = src.timeStep; - this.windAverage = src.windAverage; - this.windTurbulence = src.windTurbulence; - this.calculateExtras = src.calculateExtras; - this.randomSeed = src.randomSeed; - - fireChangeEvent(); - } - - - - /** - * Compares whether the two simulation conditions are equal. The two are considered - * equal if the rocket, motor id and all variables are equal. - */ - @Override - public boolean equals(Object other) { - if (!(other instanceof SimulationOptions)) - return false; - SimulationOptions o = (SimulationOptions) other; - return ((this.rocket == o.rocket) && - Utils.equals(this.motorID, o.motorID) && - MathUtil.equals(this.launchAltitude, o.launchAltitude) && - MathUtil.equals(this.launchLatitude, o.launchLatitude) && - MathUtil.equals(this.launchLongitude, o.launchLongitude) && - MathUtil.equals(this.launchPressure, o.launchPressure) && - MathUtil.equals(this.launchRodAngle, o.launchRodAngle) && - MathUtil.equals(this.launchRodDirection, o.launchRodDirection) && - MathUtil.equals(this.launchRodLength, o.launchRodLength) && - MathUtil.equals(this.launchTemperature, o.launchTemperature) && - MathUtil.equals(this.maximumAngle, o.maximumAngle) && - MathUtil.equals(this.timeStep, o.timeStep) && - MathUtil.equals(this.windAverage, o.windAverage) && - MathUtil.equals(this.windTurbulence, o.windTurbulence) && - this.calculateExtras == o.calculateExtras && this.randomSeed == o.randomSeed); - } - - /** - * Hashcode method compatible with {@link #equals(Object)}. - */ - @Override - public int hashCode() { - if (motorID == null) - return rocket.hashCode(); - return rocket.hashCode() + motorID.hashCode(); - } - - @Override - public void addChangeListener(EventListener listener) { - listeners.add(listener); - } - - @Override - public void removeChangeListener(EventListener listener) { - listeners.remove(listener); - } - - private final EventObject event = new EventObject(this); - - private void fireChangeEvent() { - - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] list = listeners.toArray(new EventListener[0]); - for (EventListener l : list) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(event); - } - } - } - - - // TODO: HIGH: Clean up - public SimulationConditions toSimulationConditions() { - SimulationConditions conditions = new SimulationConditions(); - - conditions.setRocket((Rocket) getRocket().copy()); - conditions.setMotorConfigurationID(getMotorConfigurationID()); - conditions.setLaunchRodLength(getLaunchRodLength()); - conditions.setLaunchRodAngle(getLaunchRodAngle()); - conditions.setLaunchRodDirection(getLaunchRodDirection()); - conditions.setLaunchSite(new WorldCoordinate(getLaunchLatitude(), getLaunchLongitude(), getLaunchAltitude())); - conditions.setGeodeticComputation(getGeodeticComputation()); - conditions.setRandomSeed(randomSeed); - - PinkNoiseWindModel windModel = new PinkNoiseWindModel(randomSeed); - windModel.setAverage(getWindSpeedAverage()); - windModel.setStandardDeviation(getWindSpeedDeviation()); - conditions.setWindModel(windModel); - - conditions.setAtmosphericModel(getAtmosphericModel()); - - GravityModel gravityModel = new WGSGravityModel(); - - conditions.setGravityModel(gravityModel); - - conditions.setAerodynamicCalculator(new BarrowmanCalculator()); - conditions.setMassCalculator(new BasicMassCalculator()); - - conditions.setTimeStep(getTimeStep()); - conditions.setMaximumAngleStep(getMaximumStepAngle()); - - conditions.setCalculateExtras(getCalculateExtras()); - - return conditions; - } - -} diff --git a/core/src/net/sf/openrocket/simulation/SimulationStatus.java b/core/src/net/sf/openrocket/simulation/SimulationStatus.java deleted file mode 100644 index 9a39cffd..00000000 --- a/core/src/net/sf/openrocket/simulation/SimulationStatus.java +++ /dev/null @@ -1,389 +0,0 @@ -package net.sf.openrocket.simulation; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.motor.MotorInstanceConfiguration; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Monitorable; -import net.sf.openrocket.util.MonitorableSet; -import net.sf.openrocket.util.Quaternion; -import net.sf.openrocket.util.WorldCoordinate; - -/** - * A holder class for the dynamic status during the rocket's flight. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationStatus implements Cloneable, Monitorable { - - /* - * NOTE! All fields must be added to copyFrom() method!! - */ - - private SimulationConditions simulationConditions; - private Configuration configuration; - private MotorInstanceConfiguration motorConfiguration; - private FlightDataBranch flightData; - - private double time; - - private double previousTimeStep; - - private Coordinate position; - private WorldCoordinate worldPosition; - private Coordinate velocity; - - private Quaternion orientation; - private Coordinate rotationVelocity; - - private double effectiveLaunchRodLength; - - - /** Nanosecond time when the simulation was started. */ - private long simulationStartWallTime = Long.MIN_VALUE; - - - /** Set to true when a motor has ignited. */ - private boolean motorIgnited = false; - - /** Set to true when the rocket has risen from the ground. */ - private boolean liftoff = false; - - /** Set to true when the launch rod has been cleared. */ - private boolean launchRodCleared = false; - - /** Set to true when apogee has been detected. */ - private boolean apogeeReached = false; - - /** Contains a list of deployed recovery devices. */ - private MonitorableSet<RecoveryDevice> deployedRecoveryDevices = new MonitorableSet<RecoveryDevice>(); - - /** The flight event queue */ - private final EventQueue eventQueue = new EventQueue(); - - private WarningSet warnings; - - /** Available for special purposes by the listeners. */ - private final Map<String, Object> extraData = new HashMap<String, Object>(); - - - private int modID = 0; - private int modIDadd = 0; - - - public void setSimulationTime(double time) { - this.time = time; - this.modID++; - } - - - public double getSimulationTime() { - return time; - } - - - public void setConfiguration(Configuration configuration) { - if (this.configuration != null) - this.modIDadd += this.configuration.getModID(); - this.modID++; - this.configuration = configuration; - } - - - public Configuration getConfiguration() { - return configuration; - } - - - public void setMotorConfiguration(MotorInstanceConfiguration motorConfiguration) { - if (this.motorConfiguration != null) - this.modIDadd += this.motorConfiguration.getModID(); - this.modID++; - this.motorConfiguration = motorConfiguration; - } - - - public MotorInstanceConfiguration getMotorConfiguration() { - return motorConfiguration; - } - - - public void setFlightData(FlightDataBranch flightData) { - if (this.flightData != null) - this.modIDadd += this.flightData.getModID(); - this.modID++; - this.flightData = flightData; - } - - - public FlightDataBranch getFlightData() { - return flightData; - } - - - public double getPreviousTimeStep() { - return previousTimeStep; - } - - - public void setPreviousTimeStep(double previousTimeStep) { - this.previousTimeStep = previousTimeStep; - this.modID++; - } - - - public void setRocketPosition(Coordinate position) { - this.position = position; - this.modID++; - } - - - public Coordinate getRocketPosition() { - return position; - } - - public void setRocketWorldPosition(WorldCoordinate wc) { - this.worldPosition = wc; - this.modID++; - } - - public WorldCoordinate getRocketWorldPosition() { - return worldPosition; - } - - public void setRocketVelocity(Coordinate velocity) { - this.velocity = velocity; - this.modID++; - } - - - public Coordinate getRocketVelocity() { - return velocity; - } - - - - - - public Quaternion getRocketOrientationQuaternion() { - return orientation; - } - - - public void setRocketOrientationQuaternion(Quaternion orientation) { - this.orientation = orientation; - this.modID++; - } - - - public Coordinate getRocketRotationVelocity() { - return rotationVelocity; - } - - - public void setRocketRotationVelocity(Coordinate rotation) { - this.rotationVelocity = rotation; - } - - - public void setEffectiveLaunchRodLength(double effectiveLaunchRodLength) { - this.effectiveLaunchRodLength = effectiveLaunchRodLength; - this.modID++; - } - - - public double getEffectiveLaunchRodLength() { - return effectiveLaunchRodLength; - } - - - public void setSimulationStartWallTime(long simulationStartWallTime) { - this.simulationStartWallTime = simulationStartWallTime; - this.modID++; - } - - - public long getSimulationStartWallTime() { - return simulationStartWallTime; - } - - - public void setMotorIgnited(boolean motorIgnited) { - this.motorIgnited = motorIgnited; - this.modID++; - } - - - public boolean isMotorIgnited() { - return motorIgnited; - } - - - public void setLiftoff(boolean liftoff) { - this.liftoff = liftoff; - this.modID++; - } - - - public boolean isLiftoff() { - return liftoff; - } - - - public void setLaunchRodCleared(boolean launchRod) { - this.launchRodCleared = launchRod; - this.modID++; - } - - - public boolean isLaunchRodCleared() { - return launchRodCleared; - } - - - public void setApogeeReached(boolean apogeeReached) { - this.apogeeReached = apogeeReached; - this.modID++; - } - - - public boolean isApogeeReached() { - return apogeeReached; - } - - - public Set<RecoveryDevice> getDeployedRecoveryDevices() { - return deployedRecoveryDevices; - } - - - public void setWarnings(WarningSet warnings) { - if (this.warnings != null) - this.modIDadd += this.warnings.getModID(); - this.modID++; - this.warnings = warnings; - } - - - public WarningSet getWarnings() { - return warnings; - } - - - public EventQueue getEventQueue() { - return eventQueue; - } - - - public void setSimulationConditions(SimulationConditions simulationConditions) { - if (this.simulationConditions != null) - this.modIDadd += this.simulationConditions.getModID(); - this.modID++; - this.simulationConditions = simulationConditions; - } - - - public SimulationConditions getSimulationConditions() { - return simulationConditions; - } - - - /** - * Store extra data available for use by simulation listeners. The data can be retrieved - * using {@link #getExtraData(String)}. - * - * @param key the data key - * @param value the value to store - */ - public void putExtraData(String key, Object value) { - extraData.put(key, value); - } - - /** - * Retrieve extra data stored by simulation listeners. This data map is initially empty. - * Data can be stored using {@link #putExtraData(String, Object)}. - * - * @param key the data key to retrieve - * @return the data, or <code>null</code> if nothing has been set for the key - */ - public Object getExtraData(String key) { - return extraData.get(key); - } - - - /** - * Returns a copy of this object. The general purpose is that the conditions, - * rocket configuration, flight data etc. point to the same objects. However, - * subclasses are allowed to deep-clone specific objects, such as those pertaining - * to the current orientation of the rocket. The purpose is to allow creating intermediate - * copies of this object used during step computation. - * - * TODO: HIGH: Deep cloning required for branch saving. - */ - @Override - public SimulationStatus clone() { - try { - SimulationStatus clone = (SimulationStatus) super.clone(); - return clone; - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException?!?", e); - } - } - - - /** - * Copies the data from the provided object to this object. Most included object are - * deep-cloned, except for the flight data object. - * - * @param orig the object from which to copy - */ - public void copyFrom(SimulationStatus orig) { - this.simulationConditions = orig.simulationConditions.clone(); - this.configuration = orig.configuration.clone(); - this.motorConfiguration = orig.motorConfiguration.clone(); - this.flightData = orig.flightData; - this.time = orig.time; - this.previousTimeStep = orig.previousTimeStep; - this.position = orig.position; - this.worldPosition = orig.worldPosition; - this.velocity = orig.velocity; - this.orientation = orig.orientation; - this.rotationVelocity = orig.rotationVelocity; - this.effectiveLaunchRodLength = orig.effectiveLaunchRodLength; - this.simulationStartWallTime = orig.simulationStartWallTime; - this.motorIgnited = orig.motorIgnited; - this.liftoff = orig.liftoff; - this.launchRodCleared = orig.launchRodCleared; - this.apogeeReached = orig.apogeeReached; - - this.deployedRecoveryDevices.clear(); - this.deployedRecoveryDevices.addAll(orig.deployedRecoveryDevices); - - this.eventQueue.clear(); - this.eventQueue.addAll(orig.eventQueue); - - this.warnings = orig.warnings; - - this.extraData.clear(); - this.extraData.putAll(orig.extraData); - - this.modID = orig.modID; - this.modIDadd = orig.modIDadd; - } - - - @Override - public int getModID() { - return (modID + modIDadd + simulationConditions.getModID() + configuration.getModID() + - motorConfiguration.getModID() + flightData.getModID() + deployedRecoveryDevices.getModID() + - eventQueue.getModID() + warnings.getModID()); - } - - -} diff --git a/core/src/net/sf/openrocket/simulation/SimulationStepper.java b/core/src/net/sf/openrocket/simulation/SimulationStepper.java deleted file mode 100644 index 90855c3c..00000000 --- a/core/src/net/sf/openrocket/simulation/SimulationStepper.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.sf.openrocket.simulation; - -import net.sf.openrocket.simulation.exception.SimulationException; - -public interface SimulationStepper { - - /** - * Initialize a simulation using this simulation stepper based on the provided - * current simulation status and launch conditions. - * - * @param status the current simulation status. - * @return a SimulationStatus suitable for simulating with this simulation stepper. - */ - public SimulationStatus initialize(SimulationStatus status) throws SimulationException; - - /** - * Perform one simulation time step. - * - * @param status the current simulation status, of a type returned by {@link #initialize(SimulationStatus)}. - * @param maxTimeStep the maximum time step to take. This is an upper bound and can be used to limit a stepper - * from stepping over upcoming flight events (motor ignition etc). - */ - public void step(SimulationStatus status, double maxTimeStep) throws SimulationException; - -} diff --git a/core/src/net/sf/openrocket/simulation/customexpression/CustomExpression.java b/core/src/net/sf/openrocket/simulation/customexpression/CustomExpression.java deleted file mode 100644 index e233deff..00000000 --- a/core/src/net/sf/openrocket/simulation/customexpression/CustomExpression.java +++ /dev/null @@ -1,528 +0,0 @@ -package net.sf.openrocket.simulation.customexpression; - -import java.util.List; -import java.util.regex.*; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.unit.FixedUnitGroup; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.ArrayList; -import de.congrace.exp4j.Calculable; -import de.congrace.exp4j.ExpressionBuilder; -import de.congrace.exp4j.UnknownFunctionException; -import de.congrace.exp4j.UnparsableExpressionException; -import de.congrace.exp4j.Variable; - -/** - * Represents a single custom expression - * @author Richard Graham - * - */ -public class CustomExpression implements Cloneable{ - - private static final LogHelper log = Application.getLogger(); - - private OpenRocketDocument doc; - private String name, symbol, unit; - - protected String expression; - private ExpressionBuilder builder; - private List<CustomExpression> subExpressions = new ArrayList<CustomExpression>(); - - public CustomExpression(OpenRocketDocument doc){ - this.doc = doc; - - setName(""); - setSymbol(""); - setUnit(""); - setExpression(""); - } - - public CustomExpression(OpenRocketDocument doc, - String name, - String symbol, - String unit, - String expression) { - this.doc = doc; - - setName(name); - setSymbol(symbol); - setUnit(unit); - setExpression(expression); - } - - /* - * Sets the long name of this expression, e.g. 'Kinetic energy' - */ - public void setName(String name){ - this.name = name; - } - - /* - * Sets the string for the units of the result of this expression. - */ - public void setUnit(String unit){ - this.unit = unit; - } - - /* - * Sets the symbol string. This is the short, locale independent symbol for this whole expression - */ - public void setSymbol(String symbol){ - this.symbol = symbol; - } - - /* - * Sets the actual expression string for this expression - */ - public void setExpression(String expression){ - - // This is the expression as supplied - this.expression = expression; - - // Replace any indexed variables - expression = subTimeIndexes(expression); - expression = subTimeRanges(expression); - - builder = new ExpressionBuilder(expression); - for (String n : getAllSymbols()){ - builder.withVariable(new Variable(n)); - } - for (CustomExpression exp : this.subExpressions){ - builder.withVariable(new Variable(exp.hash())); - } - - builder.withCustomFunctions(Functions.getInstance().getAllFunction()); - log.info("Built expression "+expression); - } - - /* - * Replaces expressions of the form: - * a[x:y] with a hash and creates an associated RangeExpression from x to y - */ - private String subTimeRanges(String str){ - - Pattern p = Pattern.compile(variableRegex()+"\\[[^\\]]*:.*?\\]"); - Matcher m = p.matcher(str); - - // for each match, make a new custom expression (in subExpressions) with a hashed name - // and replace the expression and variable in the original expression string with [hash]. - while (m.find()){ - String match = m.group(); - - int start = match.indexOf("["); - int end = match.indexOf("]"); - int colon = match.indexOf(":"); - - String startTime = match.substring(start+1, colon); - String endTime = match.substring(colon+1, end); - String variableType = match.substring(0, start); - - RangeExpression exp = new RangeExpression(doc, startTime, endTime, variableType); - subExpressions.add( exp ); - str = str.replace(match, exp.hash()); - } - return str; - } - - /* - * Replaces expressions of the form - * a[x] with a hash and creates an associated IndexExpression with x - */ - private String subTimeIndexes(String str){ - - // find any matches of the time-indexed variable notation, e.g. m[1.2] for mass at 1.2 sec - Pattern p = Pattern.compile(variableRegex()+"\\[[^:]*?\\]"); - Matcher m = p.matcher(str); - - // for each match, make a new custom expression (in subExpressions) with a hashed name - // and replace the expression and variable in the original expression string with [hash]. - while (m.find()){ - String match = m.group(); - // just the index part (in the square brackets) : - String indexText = match.substring(match.indexOf("[")+1, match.length()-1); - // just the flight data type - String typeText = match.substring(0, match.indexOf("[")); - - // Do the replacement and add a corresponding new IndexExpression to the list - IndexExpression exp = new IndexExpression(doc, indexText, typeText); - subExpressions.add( exp ); - str = str.replace(match, exp.hash()); - } - return str; - } - - /* - * Returns a string of the form (t|a| ... ) with all variable symbols available - * This is useful for regex evaluation - */ - protected String variableRegex(){ - String regex = "("; - for (String s : getAllSymbols()){ - regex = regex + s + "|"; - } - regex = regex.substring(0, regex.length()-1) + ")"; - return regex; - } - - // get a list of all the names of all the available variables - protected ArrayList<String> getAllNames(){ - ArrayList<String> names = new ArrayList<String>(); - /* - for (FlightDataType type : FlightDataType.ALL_TYPES) - names.add(type.getName()); - - if (doc != null){ - List<CustomExpression> expressions = doc.getCustomExpressions(); - for (CustomExpression exp : expressions ){ - if (exp != this) - names.add(exp.getName()); - } - } - */ - for (FlightDataType type : doc.getFlightDataTypes()){ - String symb = type.getName(); - if (name == null) continue; - - if (!name.equals( this.getName() )){ - names.add(symb); - } - } - return names; - } - - // get a list of all the symbols of the available variables ignoring this one - protected ArrayList<String> getAllSymbols(){ - ArrayList<String> symbols = new ArrayList<String>(); - /* - for (FlightDataType type : FlightDataType.ALL_TYPES) - symbols.add(type.getSymbol()); - - if (doc != null){ - for (CustomExpression exp : doc.getCustomExpressions() ){ - if (exp != this) - symbols.add(exp.getSymbol()); - } - } - */ - for (FlightDataType type : doc.getFlightDataTypes()){ - String symb = type.getSymbol(); - if (!symb.equals( this.getSymbol() )){ - symbols.add(symb); - } - } - - return symbols; - } - - public boolean checkSymbol(){ - if ("".equals(symbol.trim())) - return false; - - // No bad characters - for (char c : "0123456789.,()[]{}<>:#@%^&*$ ".toCharArray()) - if (symbol.indexOf(c) != -1 ) - return false; - - // No operators (ignoring brackets) - for (String s : Functions.AVAILABLE_OPERATORS.keySet()){ - if (symbol.equals(s.trim().replaceAll("\\(|\\)|\\]|\\[|:", ""))) - return false; - } - - // No already defined symbols - ArrayList<String> symbols = getAllSymbols().clone(); - if (symbols.contains(symbol.trim())){ - int index = symbols.indexOf(symbol.trim()); - log.user("Symbol "+symbol+" already exists, found "+symbols.get(index)); - return false; - } - - return true; - } - - public boolean checkName(){ - if ("".equals(name.trim())) - return false; - - // No characters that could mess things up saving etc - for (char c : ",()[]{}<>#$".toCharArray()) - if (name.indexOf(c) != -1 ) - return false; - - ArrayList<String> names = getAllNames().clone(); - if (names.contains(name.trim())){ - int index = names.indexOf(name.trim()); - log.user("Name "+name+" already exists, found "+names.get(index)); - return false; - } - - return true; - } - - // Currently no restrictions on unit - public boolean checkUnit(){ - return true; - } - - public boolean checkAll(){ - return checkUnit() && checkSymbol() && checkName() && checkExpression(); - } - - public String getName(){ - return name; - } - - public String getSymbol(){ - return symbol; - } - - public String getUnit(){ - return unit; - } - - public String getExpressionString(){ - return expression; - } - - /** - * Performs a basic check to see if the current expression string is valid - * This includes checking for bad characters and balanced brackets and test - * building the expression. - */ - public boolean checkExpression(){ - if ("".equals(expression.trim())){ - return false; - } - - int round = 0, square = 0; // count of bracket openings - for (char c : expression.toCharArray()){ - switch (c) { - case '(' : round++; break; - case ')' : round--; break; - case '[' : square++; break; - case ']' : square--; break; - case ':' : - if (square <= 0){ - log.user(": found outside range expression"); - return false; - } - else break; - case '#' : return false; - case '$' : return false; - case '=' : return false; - } - } - if (round != 0 || square != 0) { - log.user("Expression has unballanced brackets"); - return false; - } - - - //// Define the available variables as empty - // The built in data types - /* - for (FlightDataType type : FlightDataType.ALL_TYPES){ - builder.withVariable(new Variable(type.getSymbol())); - } - - for (String symb : getAllSymbols()){ - builder.withVariable(new Variable(symb)); - } - */ - for (FlightDataType type : doc.getFlightDataTypes()){ - builder.withVariable(new Variable(type.getSymbol())); - } - - // Try to build - try { - builder.build(); - } catch (Exception e) { - log.user("Custom expression " + this.toString() + " invalid : " + e.toString()); - return false; - } - - - // Otherwise, all OK - return true; - } - - public Double evaluateDouble(SimulationStatus status){ - double result = evaluate(status).getDoubleValue(); - if (result == Double.NEGATIVE_INFINITY || result == Double.POSITIVE_INFINITY) result = Double.NaN; - return result; - } - - /* - * Builds the expression, done automatically during evaluation. Logs any errors. Returns null in case of error. - */ - protected Calculable buildExpression(){ - return buildExpression(builder); - } - - /* - * Builds a specified expression, log any errors and returns null in case of error. - */ - protected Calculable buildExpression(ExpressionBuilder b){ - Calculable calc = null; - try { - calc = b.build(); - } catch (UnknownFunctionException e1) { - log.user("Unknown function. Could not build custom expression "+this.toString()); - return null; - } catch (UnparsableExpressionException e1) { - log.user("Unparsable expression. Could not build custom expression "+this.toString()+". "+e1.getMessage()); - return null; - } - - return calc; - } - - /* - * Evaluate the expression using the last variable values from the simulation status. - * Returns NaN on any error. - */ - public Variable evaluate(SimulationStatus status){ - - Calculable calc = buildExpression(builder); - if (calc == null){ - return new Variable("Unknown"); - } - - // Evaluate any sub expressions and set associated variables in the calculable - for (CustomExpression expr : this.subExpressions){ - calc.setVariable( expr.evaluate(status) ); - } - - // Set all the built-in variables. Strictly we surely won't need all of them - // Going through and checking them to include only the ones used *might* give a speedup - for (FlightDataType type : status.getFlightData().getTypes()){ - double value = status.getFlightData().getLast(type); - calc.setVariable( new Variable(type.getSymbol(), value ) ); - } - - double result = Double.NaN; - try{ - result = calc.calculate().getDoubleValue(); - } - catch (java.util.EmptyStackException e){ - log.user("Unable to calculate expression "+this.expression+" due to empty stack exception"); - } - - return new Variable(name, result); - } - - /* - * Returns the new flight data type corresponding to this calculated data - * If the unit matches a SI unit string then the datatype will have the corresponding unitgroup. - * Otherwise, a fixed unit group will be created - */ - public FlightDataType getType(){ - - - UnitGroup ug = UnitGroup.SIUNITS.get(unit); - if ( ug == null ){ - log.debug("SI unit not found for "+unit+" in expression "+toString()+". Making a new fixed unit."); - ug = new FixedUnitGroup(unit); - } - //UnitGroup ug = new FixedUnitGroup(unit); - - FlightDataType type = FlightDataType.getType(name, symbol, ug); - - //log.debug(this.getClass().getSimpleName()+" returned type "+type.getName()+" (" + type.getSymbol() + ")" ); - - return type; - } - - /* - * Add this expression to the document if valid and not in document already - */ - public void addToDocument(){ - // Abort if exact expression already in - List<CustomExpression> expressions = doc.getCustomExpressions(); - if ( !expressions.isEmpty() ) { - // check if expression already exists - if ( expressions.contains(this) ){ - log.user("Expression already in document. This unit : "+this.getUnit()+", existing unit : "+expressions.get(0).getUnit()); - return; - } - } - - if (this.checkAll()){ - log.user("Custom expression added to rocket document"); - doc.addCustomExpression( this ); - } - } - - /* - * Removes this expression from the document, replacing it with a given new expression - */ - public void overwrite(CustomExpression newExpression){ - if (!doc.getCustomExpressions().contains(this)) - return; - else { - int index = doc.getCustomExpressions().indexOf(this); - doc.getCustomExpressions().set(index, newExpression); - } - } - - @Override - public String toString(){ - return "[Expression name="+this.name.toString()+ " expression=" + this.expression+" unit="+this.unit+"]"; - } - - @Override - /* - * Clone method makes a deep copy of everything except the reference to the document. - * If you want to apply this to another simulation, set simulation manually after cloning. - * @see java.lang.Object#clone() - */ - public Object clone() { - try { - return super.clone(); - } - catch( CloneNotSupportedException e ) - { - return new CustomExpression( doc , - new String(this.getName()), - new String(this.getSymbol()), - new String(this.getUnit()), - new String(this.getExpressionString())); - } - } - - /* - * Returns a simple all upper case string hash code with a proceeding $ mark. - * Used for temporary substitution when evaluating index and range expressions. - */ - public String hash(){ - Integer hashint = new Integer(this.getExpressionString().hashCode() + symbol.hashCode()); - String hash = "$"; - for (char c : hashint.toString().toCharArray()){ - if (c == '-') c = '0'; - char newc = (char) (c + 17); - hash = hash + newc; - } - return hash; - } - - @Override - public boolean equals(Object obj){ - CustomExpression other = (CustomExpression) obj; - - return ( this.getName().equals( other.getName() ) && - this.getSymbol().equals( other.getSymbol() ) && - this.getExpressionString().equals( other.getExpressionString() ) && - this.getUnit().equals( other.getUnit() ) - ); - } - - @Override - public int hashCode() { - return hash().hashCode(); - } -} diff --git a/core/src/net/sf/openrocket/simulation/customexpression/CustomExpressionSimulationListener.java b/core/src/net/sf/openrocket/simulation/customexpression/CustomExpressionSimulationListener.java deleted file mode 100644 index 243f7b15..00000000 --- a/core/src/net/sf/openrocket/simulation/customexpression/CustomExpressionSimulationListener.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.sf.openrocket.simulation.customexpression; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.startup.Application; - -public class CustomExpressionSimulationListener extends AbstractSimulationListener { - - private static final LogHelper log = Application.getLogger(); - private final List<CustomExpression> expressions; - - public CustomExpressionSimulationListener(List<CustomExpression> expressions) { - super(); - this.expressions = expressions; - } - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - if ( expressions == null || expressions.size() == 0 ) { - return; - } - // Calculate values for custom expressions - FlightDataBranch data = status.getFlightData(); - for (CustomExpression expression : expressions ) { - double value = expression.evaluateDouble(status); - //log.debug("Setting value of custom expression "+expression.toString()+" = "+value); - data.setValue(expression.getType(), value); - } - - - } - - @Override - public boolean isSystemListener(){ - return true; - } - -} diff --git a/core/src/net/sf/openrocket/simulation/customexpression/Functions.java b/core/src/net/sf/openrocket/simulation/customexpression/Functions.java deleted file mode 100644 index 6e638d91..00000000 --- a/core/src/net/sf/openrocket/simulation/customexpression/Functions.java +++ /dev/null @@ -1,269 +0,0 @@ -package net.sf.openrocket.simulation.customexpression; - -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayUtils; - -import de.congrace.exp4j.CustomFunction; -import de.congrace.exp4j.InvalidCustomFunctionException; -import de.congrace.exp4j.Variable; - -/* - * This is a singleton class which contains all the functions for custom expressions not provided by exp4j - */ -public class Functions { - private static Functions instance = null; - - private static final LogHelper log = Application.getLogger(); - private static final Translator trans = Application.getTranslator(); - - private List<CustomFunction> allFunctions = new ArrayList<CustomFunction>(); - - public static Functions getInstance() { - if(instance == null) { - try { - instance = new Functions(); - } catch (InvalidCustomFunctionException e) { - log.error("Invalid custom function."); - } - } - return instance; - } - - public List<CustomFunction> getAllFunction(){ - return allFunctions; - } - - // A map of available operator strings (keys) and description of function (value) - public static final SortedMap<String, String> AVAILABLE_OPERATORS = new TreeMap<String, String>() {{ - put("+" , trans.get("Operator.plus")); - put("-" , trans.get("Operator.minus")); - put("*" , trans.get("Operator.star")); - put("/" , trans.get("Operator.div")); - put("%" , trans.get("Operator.mod")); - put("^" , trans.get("Operator.pow")); - put("abs()" , trans.get("Operator.abs")); - put("ceil()" , trans.get("Operator.ceil")); - put("floor()" , trans.get("Operator.floor")); - put("sqrt()" , trans.get("Operator.sqrt")); - put("cbrt()" , trans.get("Operator.cbrt")); - put("exp()" , trans.get("Operator.exp")); - put("log()" , trans.get("Operator.ln")); - put("sin()" , trans.get("Operator.sin")); - put("cos()" , trans.get("Operator.cos")); - put("tan()" , trans.get("Operator.tan")); - put("asin()" , trans.get("Operator.asin")); - put("acos()" , trans.get("Operator.acos")); - put("atan()" , trans.get("Operator.atan")); - put("sinh()" , trans.get("Operator.hsin")); - put("cosh()" , trans.get("Operator.hcos")); - put("tanh()" , trans.get("Operator.htan")); - put("log10()" , trans.get("Operator.log10")); - put("round()" , trans.get("Operator.round")); - put("random()" , trans.get("Operator.random")); - put("expm1()" , trans.get("Operator.expm1")); - put("mean([:])" , trans.get("Operator.mean")); - put("min([:])" , trans.get("Operator.min")); - put("max([:])" , trans.get("Operator.max")); - put("var([:])" , trans.get("Operator.var")); - put("rms([:])" , trans.get("Operator.rms")); - put("stdev([:])", trans.get("Operator.stdev")); - put("lclip(,)" , trans.get("Operator.lclip")); - put("uclip(,)" , trans.get("Operator.uclip")); - put("binf([:],,)" , trans.get("Operator.binf")); - put("trapz([:])" , trans.get("Operator.trapz")); - put("tnear([:],)" , trans.get("Operator.tnear")); - }}; - - - protected Functions() throws InvalidCustomFunctionException { - - CustomFunction meanFn = new CustomFunction("mean") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] vals; - try{ - vals = vars.get(0).getArrayValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - return new Variable("double MEAN result, ", ArrayUtils.mean(vals)); - } - }; - allFunctions.add(meanFn); - - CustomFunction minFn = new CustomFunction("min") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] vals; - try{ - vals = vars.get(0).getArrayValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - return new Variable("double MIN result, ", ArrayUtils.min(vals)); - } - }; - allFunctions.add(minFn); - - CustomFunction maxFn = new CustomFunction("max") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] vals; - try{ - vals = vars.get(0).getArrayValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - return new Variable("double MAX result, ", ArrayUtils.max(vals)); - } - }; - allFunctions.add(maxFn); - - CustomFunction varFn = new CustomFunction("var") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] vals; - try{ - vals = vars.get(0).getArrayValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - return new Variable("double VAR result, ", ArrayUtils.variance(vals)); - } - }; - allFunctions.add(varFn); - - CustomFunction stdevFn = new CustomFunction("stdev") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] vals; - try{ - vals = vars.get(0).getArrayValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - return new Variable("double STDEV result, ", ArrayUtils.stdev(vals)); - } - }; - allFunctions.add(stdevFn); - - CustomFunction rmsFn = new CustomFunction("rms") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] vals; - try{ - vals = vars.get(0).getArrayValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - return new Variable("double RMS result, ", ArrayUtils.rms(vals)); - } - }; - allFunctions.add(rmsFn); - - CustomFunction lclipFn = new CustomFunction("lclip",2) { - @Override - public Variable applyFunction(List<Variable> vars) { - double val, clip; - try{ - val = vars.get(0).getDoubleValue(); - clip = vars.get(1).getDoubleValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - if (val < clip){ - val = clip; - } - return new Variable("double LCLIP result, ", val); - } - }; - allFunctions.add(lclipFn); - - CustomFunction uclipFn = new CustomFunction("uclip",2) { - @Override - public Variable applyFunction(List<Variable> vars) { - double val, clip; - try{ - val = vars.get(0).getDoubleValue(); - clip = vars.get(1).getDoubleValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - if (val > clip){ - val = clip; - } - return new Variable("double UCLIP result, ", val); - } - }; - allFunctions.add(uclipFn); - - CustomFunction binfFn = new CustomFunction("binf", 3) { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] range; - double min, max; - try{ - range = vars.get(0).getArrayValue(); - min = vars.get(1).getDoubleValue(); - max = vars.get(2).getDoubleValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - - int ins = 0; - for (double x: range){ - if (x < max && x > min){ - ins++; - } - } - return new Variable("double BINF result", (double) ins/ (double) range.length); - } - }; - allFunctions.add(binfFn); - - CustomFunction rombintFn = new CustomFunction("trapz") { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] range; - double dt = 0; - try{ - range = vars.get(0).getArrayValue(); - dt = vars.get(0).getStep(); - } catch (Exception e) { - return new Variable("Invalid"); - } - - return new Variable("double TRAPZ result", ArrayUtils.trapz(range, dt) ); - } - }; - allFunctions.add(rombintFn); - - CustomFunction tnearFn = new CustomFunction("tnear", 2) { - @Override - public Variable applyFunction(List<Variable> vars) { - double[] range; - double dt = 0; - double start = 0; - double near = 0; - try{ - range = vars.get(0).getArrayValue(); - dt = vars.get(0).getStep(); - start = vars.get(0).getStart(); - near = vars.get(1).getDoubleValue(); - } catch (Exception e) { - return new Variable("Invalid"); - } - - return new Variable("double TNEAR result", ArrayUtils.tnear(range, near, start, dt) ); - } - }; - allFunctions.add(tnearFn); - } -} diff --git a/core/src/net/sf/openrocket/simulation/customexpression/IndexExpression.java b/core/src/net/sf/openrocket/simulation/customexpression/IndexExpression.java deleted file mode 100644 index 6fb084de..00000000 --- a/core/src/net/sf/openrocket/simulation/customexpression/IndexExpression.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.simulation.customexpression; - -import java.util.List; - -import de.congrace.exp4j.Calculable; -import de.congrace.exp4j.Variable; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.LinearInterpolator; - -public class IndexExpression extends CustomExpression { - - FlightDataType type; - private static final LogHelper log = Application.getLogger(); - - public IndexExpression(OpenRocketDocument doc, String indexText, String typeText){ - super(doc); - - setExpression(indexText); - this.setName(""); - this.setSymbol(typeText); - } - - @Override - public Variable evaluate(SimulationStatus status){ - - Calculable calc = buildExpression(); - if (calc == null){ - return new Variable("Unknown"); - } - - // From the given datatype, get the time and function values and make an interpolator - - //Note: must get in a way that flight data system will figure out units. Otherwise there will be a type conflict when we get the new data. - FlightDataType type = FlightDataType.getType(null, getSymbol(), null); - - List<Double> data = status.getFlightData().get(type); - List<Double> time = status.getFlightData().get(FlightDataType.TYPE_TIME); - LinearInterpolator interp = new LinearInterpolator(time, data); - - // Evaluate this expression to get the t value - try{ - double tvalue = calc.calculate().getDoubleValue(); - return new Variable(hash(), interp.getValue( tvalue ) ); - } - catch (java.util.EmptyStackException e){ - log.user("Unable to calculate time index for indexed expression "+getExpressionString()+" due to empty stack exception"); - return new Variable("Unknown"); - } - - } -} diff --git a/core/src/net/sf/openrocket/simulation/customexpression/RangeExpression.java b/core/src/net/sf/openrocket/simulation/customexpression/RangeExpression.java deleted file mode 100644 index 1667b61e..00000000 --- a/core/src/net/sf/openrocket/simulation/customexpression/RangeExpression.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * A range expression contains two indexExpressions for the beginning and end time index of a range - */ - -package net.sf.openrocket.simulation.customexpression; - -import java.util.List; - -import de.congrace.exp4j.Calculable; -import de.congrace.exp4j.ExpressionBuilder; -import de.congrace.exp4j.Variable; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.simulation.customexpression.CustomExpression; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.ArrayUtils; -import net.sf.openrocket.util.LinearInterpolator; -import net.sf.openrocket.util.MathUtil; - -public class RangeExpression extends CustomExpression { - private static final LogHelper log = Application.getLogger(); - - private ExpressionBuilder startBuilder, endBuilder; - - public RangeExpression(OpenRocketDocument doc, String startTime, String endTime, String variableType) { - super(doc); - - if ("".equals(startTime.trim())){ - startTime = "0"; - } - if ("".equals(endTime.trim())){ - endTime = "t"; - } - - this.setName(""); - this.setSymbol(variableType); - this.setExpressions(startTime, endTime); - this.expression = variableType+startTime+endTime; // this is used just for generating the hash - - log.info("New range expression, "+startTime + " to "+endTime); - } - - /* - * Sets the actual expression string for this expression - */ - private void setExpressions(String start, String end){ - - startBuilder = new ExpressionBuilder(start); - endBuilder = new ExpressionBuilder(end); - for (String n : getAllSymbols()){ - startBuilder.withVariable(new Variable(n)); - endBuilder.withVariable(new Variable(n)); - } - } - - @Override - public Variable evaluate(SimulationStatus status){ - - Calculable startCalc = buildExpression(startBuilder); - Calculable endCalc = buildExpression(endBuilder); - if (startCalc == null || endCalc == null){ - return new Variable("Unknown"); - } - - // Set the variables in the start and end calculators - for (FlightDataType type : status.getFlightData().getTypes()){ - double value = status.getFlightData().getLast(type); - startCalc.setVariable( new Variable(type.getSymbol(), value ) ); - endCalc.setVariable( new Variable(type.getSymbol(), value ) ); - } - - // From the given datatype, get the time and function values and make an interpolator - - //Note: must get in a way that flight data system will figure out units. Otherwise there will be a type conflict when we get the new data. - FlightDataType type = FlightDataType.getType(null, getSymbol(), null); - - List<Double> data = status.getFlightData().get(type); - List<Double> time = status.getFlightData().get(FlightDataType.TYPE_TIME); - LinearInterpolator interp = new LinearInterpolator(time, data); - - // Evaluate the expression to get the start and end of the range - double startTime, endTime; - try{ - startTime = startCalc.calculate().getDoubleValue(); - startTime = MathUtil.clamp(startTime, 0, Double.MAX_VALUE); - - endTime = endCalc.calculate().getDoubleValue(); - endTime = MathUtil.clamp(endTime, 0, time.get(time.size()-1)); - } - catch (java.util.EmptyStackException e){ - log.user("Unable to calculate time index for range expression "+getSymbol()+" due to empty stack exception"); - return new Variable("Unknown"); - } - - // generate an array representing the range - double step = status.getSimulationConditions().getSimulation().getOptions().getTimeStep(); - double[] t = ArrayUtils.range(startTime, endTime, step); - double[] y = new double[t.length]; - int i = 0; - for (double tval : t){ - y[i] = interp.getValue( tval ); - i++; - } - - Variable result; - if (y.length == 0){ - result = new Variable("Unknown"); - } - else { - result = new Variable(hash(), y, startTime, step); - } - - return result; - } -} diff --git a/core/src/net/sf/openrocket/simulation/exception/MotorIgnitionException.java b/core/src/net/sf/openrocket/simulation/exception/MotorIgnitionException.java deleted file mode 100644 index fd9e60ac..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/MotorIgnitionException.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.sf.openrocket.simulation.exception; - -/** - * An exception signifying that the simulation failed because no motors were - * defined or ignited in the rocket. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class MotorIgnitionException extends SimulationLaunchException { - - public MotorIgnitionException(String message) { - super(message); - } - - public MotorIgnitionException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/exception/SimulationCalculationException.java b/core/src/net/sf/openrocket/simulation/exception/SimulationCalculationException.java deleted file mode 100644 index 40f86321..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/SimulationCalculationException.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.sf.openrocket.simulation.exception; - -/** - * An exception that indicates that a computation problem has occurred during - * the simulation, for example that some values have exceed reasonable bounds. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationCalculationException extends SimulationException { - - public SimulationCalculationException() { - } - - public SimulationCalculationException(String message) { - super(message); - } - - public SimulationCalculationException(Throwable cause) { - super(cause); - } - - public SimulationCalculationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/exception/SimulationCancelledException.java b/core/src/net/sf/openrocket/simulation/exception/SimulationCancelledException.java deleted file mode 100644 index e2293432..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/SimulationCancelledException.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.simulation.exception; - - -/** - * An exception signifying that a simulation was cancelled. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationCancelledException extends SimulationException { - - public SimulationCancelledException() { - - } - - public SimulationCancelledException(String message) { - super(message); - } - - public SimulationCancelledException(Throwable cause) { - super(cause); - } - - public SimulationCancelledException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/exception/SimulationException.java b/core/src/net/sf/openrocket/simulation/exception/SimulationException.java deleted file mode 100644 index f180f892..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/SimulationException.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.simulation.exception; - -public class SimulationException extends Exception { - - public SimulationException() { - - } - - public SimulationException(String message) { - super(message); - } - - public SimulationException(Throwable cause) { - super(cause); - } - - public SimulationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/exception/SimulationLaunchException.java b/core/src/net/sf/openrocket/simulation/exception/SimulationLaunchException.java deleted file mode 100644 index df9f3862..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/SimulationLaunchException.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.sf.openrocket.simulation.exception; - -/** - * An exception signifying that a problem occurred at launch, for example - * that no motors were defined or no motors ignited. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationLaunchException extends SimulationException { - - public SimulationLaunchException(String message) { - super(message); - } - - public SimulationLaunchException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/exception/SimulationListenerException.java b/core/src/net/sf/openrocket/simulation/exception/SimulationListenerException.java deleted file mode 100644 index d6bd737a..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/SimulationListenerException.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.sf.openrocket.simulation.exception; - - -public class SimulationListenerException extends SimulationException { - - public SimulationListenerException() { - } - - public SimulationListenerException(String message) { - super(message); - } - - public SimulationListenerException(Throwable cause) { - super(cause); - } - - public SimulationListenerException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/exception/SimulationNotSupportedException.java b/core/src/net/sf/openrocket/simulation/exception/SimulationNotSupportedException.java deleted file mode 100644 index 66618258..00000000 --- a/core/src/net/sf/openrocket/simulation/exception/SimulationNotSupportedException.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.simulation.exception; - - -/** - * A exception that signifies that the attempted simulation is not supported. - * The reason for not being supported may be due to unsupported combination of - * simulator/calculator, unsupported rocket structure or other reasons. - * <p> - * This exception signifies a fatal problem in the simulation; for non-fatal conditions - * add a warning to the simulation results. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationNotSupportedException extends SimulationException { - - public SimulationNotSupportedException() { - } - - public SimulationNotSupportedException(String message) { - super(message); - } - - public SimulationNotSupportedException(Throwable cause) { - super(cause); - } - - public SimulationNotSupportedException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java b/core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java deleted file mode 100644 index 3f156f38..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java +++ /dev/null @@ -1,188 +0,0 @@ -package net.sf.openrocket.simulation.listeners; - -import java.util.List; - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.simulation.AccelerationData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.MassData; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.util.Coordinate; - - -/** - * An abstract base class for implementing simulation listeners. This class implements all - * of the simulation listener interfaces using methods that have no effect on the simulation. - * The recommended way of implementing simulation listeners is to extend this class. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class AbstractSimulationListener implements SimulationListener, SimulationComputationListener, - SimulationEventListener { - - //// SimulationListener //// - - @Override - public String getName() { - return this.getClass().getSimpleName(); - } - - @Override - public String[] getMenuPosition() { - return new String[0]; - } - - @Override - public void startSimulation(SimulationStatus status) throws SimulationException { - // No-op - } - - @Override - public void endSimulation(SimulationStatus status, SimulationException exception) { - // No-op - } - - @Override - public boolean preStep(SimulationStatus status) throws SimulationException { - return true; - } - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - // No-op - } - - /** - * {@inheritDoc} - * <p> - * <em>This implementation of the method always returns <code>false</code>.</em> - */ - @Override - public boolean isSystemListener() { - return false; - } - - /** - * Return an array of any flight data types this listener creates. - */ - @Override - public FlightDataType[] getFlightDataTypes(){ - return new FlightDataType[] {}; - } - - - //// SimulationEventListener //// - - @Override - public boolean addFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException { - return true; - } - - @Override - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException { - return true; - } - - @Override - public boolean motorIgnition(SimulationStatus status, MotorId motorId, MotorMount mount, MotorInstance instance) throws SimulationException { - return true; - } - - @Override - public boolean recoveryDeviceDeployment(SimulationStatus status, RecoveryDevice recoveryDevice) throws SimulationException { - return true; - } - - - - //// SimulationComputationListener //// - - @Override - public AccelerationData preAccelerationCalculation(SimulationStatus status) throws SimulationException { - return null; - } - - @Override - public AerodynamicForces preAerodynamicCalculation(SimulationStatus status) throws SimulationException { - return null; - } - - @Override - public AtmosphericConditions preAtmosphericModel(SimulationStatus status) throws SimulationException { - return null; - } - - @Override - public FlightConditions preFlightConditions(SimulationStatus status) throws SimulationException { - return null; - } - - @Override - public double preGravityModel(SimulationStatus status) throws SimulationException { - return Double.NaN; - } - - @Override - public MassData preMassCalculation(SimulationStatus status) throws SimulationException { - return null; - } - - @Override - public double preSimpleThrustCalculation(SimulationStatus status) throws SimulationException { - return Double.NaN; - } - - @Override - public Coordinate preWindModel(SimulationStatus status) throws SimulationException { - return null; - } - - @Override - public AccelerationData postAccelerationCalculation(SimulationStatus status, AccelerationData acceleration) throws SimulationException { - return null; - } - - @Override - public AerodynamicForces postAerodynamicCalculation(SimulationStatus status, AerodynamicForces forces) throws SimulationException { - return null; - } - - @Override - public AtmosphericConditions postAtmosphericModel(SimulationStatus status, AtmosphericConditions atmosphericConditions) throws SimulationException { - return null; - } - - @Override - public FlightConditions postFlightConditions(SimulationStatus status, FlightConditions flightConditions) throws SimulationException { - return null; - } - - @Override - public double postGravityModel(SimulationStatus status, double gravity) throws SimulationException { - return Double.NaN; - } - - @Override - public MassData postMassCalculation(SimulationStatus status, MassData massData) throws SimulationException { - return null; - } - - @Override - public double postSimpleThrustCalculation(SimulationStatus status, double thrust) throws SimulationException { - return Double.NaN; - } - - @Override - public Coordinate postWindModel(SimulationStatus status, Coordinate wind) throws SimulationException { - return null; - } - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java b/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java deleted file mode 100644 index 3089d053..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.sf.openrocket.simulation.listeners; - -import java.util.List; - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.simulation.AccelerationData; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.MassData; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.util.Coordinate; - -/** - * An interface containing listener callbacks relating to different computational aspects performed - * during flight. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public interface SimulationComputationListener extends SimulationListener { - - - //////// Computation/modeling related callbacks //////// - - public AccelerationData preAccelerationCalculation(SimulationStatus status) throws SimulationException; - - public AccelerationData postAccelerationCalculation(SimulationStatus status, AccelerationData acceleration) - throws SimulationException; - - public AtmosphericConditions preAtmosphericModel(SimulationStatus status) - throws SimulationException; - - public AtmosphericConditions postAtmosphericModel(SimulationStatus status, AtmosphericConditions atmosphericConditions) - throws SimulationException; - - - public Coordinate preWindModel(SimulationStatus status) throws SimulationException; - - public Coordinate postWindModel(SimulationStatus status, Coordinate wind) throws SimulationException; - - - public double preGravityModel(SimulationStatus status) throws SimulationException; - - public double postGravityModel(SimulationStatus status, double gravity) throws SimulationException; - - - public FlightConditions preFlightConditions(SimulationStatus status) - throws SimulationException; - - public FlightConditions postFlightConditions(SimulationStatus status, FlightConditions flightConditions) - throws SimulationException; - - - public AerodynamicForces preAerodynamicCalculation(SimulationStatus status) - throws SimulationException; - - public AerodynamicForces postAerodynamicCalculation(SimulationStatus status, AerodynamicForces forces) - throws SimulationException; - - public MassData preMassCalculation(SimulationStatus status) throws SimulationException; - - public MassData postMassCalculation(SimulationStatus status, MassData massData) throws SimulationException; - - - public double preSimpleThrustCalculation(SimulationStatus status) throws SimulationException; - - public double postSimpleThrustCalculation(SimulationStatus status, double thrust) throws SimulationException; - - public FlightDataType[] getFlightDataTypes(); -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/SimulationEventListener.java b/core/src/net/sf/openrocket/simulation/listeners/SimulationEventListener.java deleted file mode 100644 index 8ac0e11a..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationEventListener.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.sf.openrocket.simulation.listeners; - -import java.util.List; - -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; - -public interface SimulationEventListener { - - - /** - * Called before adding a flight event to the event queue. - * - * @param status the simulation status - * @param event the event that is being added - * @return <code>true</code> to add the event, - * <code>false</code> to abort adding event to event queue - */ - public boolean addFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException; - - - - /** - * Called before handling a flight event. - * - * @param status the simulation status - * @param event the event that is taking place - * @return <code>true</code> to continue handling the event, - * <code>false</code> to abort handling - */ - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException; - - - /** - * Motor ignition event. - * - * @param status the simulation status - * @param motorId the motor id in the MotorInstanceConfiguration - * @param mount the motor mount containing the motor - * @param instance the motor instance being ignited - * @return <code>true</code> to ignite the motor, <code>false</code> to abort ignition - */ - public boolean motorIgnition(SimulationStatus status, MotorId motorId, MotorMount mount, - MotorInstance instance) throws SimulationException; - - - /** - * Recovery device deployment. - * - * @param status the simulation status - * @param recoveryDevice the recovery device that is being deployed. - * @return <code>true</code> to deploy the recovery device, <code>false</code> to abort deployment - */ - public boolean recoveryDeviceDeployment(SimulationStatus status, RecoveryDevice recoveryDevice) - throws SimulationException; - - - - public FlightDataType[] getFlightDataTypes(); - - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/SimulationListener.java b/core/src/net/sf/openrocket/simulation/listeners/SimulationListener.java deleted file mode 100644 index 322db8e7..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationListener.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.simulation.listeners; - -import java.util.List; - -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; - - - -public interface SimulationListener { - - /** - * Get the name of this simulation listener. Ideally this should be localized, as - * it can be displayed in the UI. - * - * @return the name of this simulation listener. - */ - public String getName(); - - - /** - * Get the menu position of this simulation listener. This should be an array - * of localized submenu names in descending order, or an empty array for positioning - * in the base menu. - * - * @return the menu position of this simulation listener. - */ - public String[] getMenuPosition(); - - - /** - * Called when starting a simulation. - * - * @param status the simulation status. - */ - public void startSimulation(SimulationStatus status) throws SimulationException; - - - /** - * Called when ending a simulation. This is called either when the simulation ends normally - * (due to an end simulation event) or when a SimulationException is thrown. - * <p> - * This method cannot throw a SimulationException, since the simulation is already being ended. - * - * @param status the simulation status. - * @param exception the exception that caused ending the simulation, or <code>null</code> if ending normally. - */ - public void endSimulation(SimulationStatus status, SimulationException exception); - - - /** - * Called before a simulation step is taken. This method may also prevent the normal - * stepping method from being called. - * - * @param status the simulation status. - * @return <code>true</code> to continue normally, <code>false</code> to skip taking the step - */ - public boolean preStep(SimulationStatus status) throws SimulationException; - - - /** - * Called immediately after a simulation step has been taken. This method is called whether the - * {@link #preStep(SimulationStatus)} aborted the step or not. - * - * @param status the simulation status. - */ - public void postStep(SimulationStatus status) throws SimulationException; - - - /** - * Return whether this is a system listener. System listeners are used internally for various - * purposes by OpenRocket. User-written listeners should always return <code>false</code>. - * <p> - * System listeners do not cause warnings to be added to the simulation results when they affect - * the simulation. - * - * @return whether this is a system listener - */ - public boolean isSystemListener(); - - - /** - * Return a list of any flight data types this listener creates. - */ - public FlightDataType[] getFlightDataTypes(); - - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/SimulationListenerHelper.java b/core/src/net/sf/openrocket/simulation/listeners/SimulationListenerHelper.java deleted file mode 100644 index be658f15..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationListenerHelper.java +++ /dev/null @@ -1,668 +0,0 @@ -package net.sf.openrocket.simulation.listeners; - - -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.aerodynamics.Warning; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.simulation.AccelerationData; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.MassData; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.MathUtil; - -/** - * Helper methods for firing events to simulation listeners. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class SimulationListenerHelper { - - private static final LogHelper log = Application.getLogger(); - - //////// SimulationListener methods //////// - - - /** - * Fire startSimulation event. - */ - public static void fireStartSimulation(SimulationStatus status) - throws SimulationException { - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - l.startSimulation(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - } - } - - - /** - * Fire endSimulation event. - */ - public static void fireEndSimulation(SimulationStatus status, SimulationException exception) { - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - l.endSimulation(status, exception); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - } - } - - - - - /** - * Fire preStep event. - * - * @return <code>true</code> to handle step normally, <code>false</code> to skip the step. - */ - public static boolean firePreStep(SimulationStatus status) - throws SimulationException { - boolean b; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - b = l.preStep(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (b == false) { - warn(status, l); - return false; - } - } - return true; - } - - - /** - * Fire postStep event. - */ - public static void firePostStep(SimulationStatus status) - throws SimulationException { - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - l.postStep(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - } - } - - - - //////// SimulationEventListener methods //////// - - /** - * Fire an add flight event event. - * - * @return <code>true</code> to add the event normally, <code>false</code> to skip adding the event. - */ - public static boolean fireAddFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException { - boolean b; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationEventListener) { - b = ((SimulationEventListener) l).addFlightEvent(status, event); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (b == false) { - warn(status, l); - return false; - } - } - } - return true; - } - - /** - * Fire a handle flight event event. - * - * @return <code>true</code> to handle the event normally, <code>false</code> to skip event. - */ - public static boolean fireHandleFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException { - boolean b; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationEventListener) { - b = ((SimulationEventListener) l).handleFlightEvent(status, event); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (b == false) { - warn(status, l); - return false; - } - } - } - return true; - } - - /** - * Fire motor ignition event. - * - * @return <code>true</code> to handle the event normally, <code>false</code> to skip event. - */ - public static boolean fireMotorIgnition(SimulationStatus status, MotorId motorId, MotorMount mount, - MotorInstance instance) throws SimulationException { - boolean b; - int modID = status.getModID(); // Contains also motor instance - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationEventListener) { - b = ((SimulationEventListener) l).motorIgnition(status, motorId, mount, instance); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (b == false) { - warn(status, l); - return false; - } - } - } - return true; - } - - - /** - * Fire recovery device deployment event. - * - * @return <code>true</code> to handle the event normally, <code>false</code> to skip event. - */ - public static boolean fireRecoveryDeviceDeployment(SimulationStatus status, RecoveryDevice device) - throws SimulationException { - boolean b; - int modID = status.getModID(); // Contains also motor instance - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationEventListener) { - b = ((SimulationEventListener) l).recoveryDeviceDeployment(status, device); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (b == false) { - warn(status, l); - return false; - } - } - } - return true; - } - - - //////// SimulationComputationalListener methods //////// - - /** - * Fire preAtmosphericModel event. - * - * @return <code>null</code> normally, or overriding atmospheric conditions. - */ - public static AtmosphericConditions firePreAtmosphericModel(SimulationStatus status) - throws SimulationException { - AtmosphericConditions conditions; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - conditions = ((SimulationComputationListener) l).preAtmosphericModel(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (conditions != null) { - warn(status, l); - return conditions; - } - } - } - return null; - } - - /** - * Fire postAtmosphericModel event. - * - * @return the atmospheric conditions to use. - */ - public static AtmosphericConditions firePostAtmosphericModel(SimulationStatus status, AtmosphericConditions conditions) - throws SimulationException { - AtmosphericConditions c; - AtmosphericConditions clone = conditions.clone(); - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - c = ((SimulationComputationListener) l).postAtmosphericModel(status, clone); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (c != null && !c.equals(conditions)) { - warn(status, l); - conditions = c; - clone = conditions.clone(); - } - } - } - return conditions; - } - - - - /** - * Fire preWindModel event. - * - * @return <code>null</code> normally, or overriding wind. - */ - public static Coordinate firePreWindModel(SimulationStatus status) - throws SimulationException { - Coordinate wind; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - wind = ((SimulationComputationListener) l).preWindModel(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (wind != null) { - warn(status, l); - return wind; - } - } - } - return null; - } - - /** - * Fire postWindModel event. - * - * @return the wind to use. - */ - public static Coordinate firePostWindModel(SimulationStatus status, Coordinate wind) throws SimulationException { - Coordinate w; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - w = ((SimulationComputationListener) l).postWindModel(status, wind); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (w != null && !w.equals(wind)) { - warn(status, l); - wind = w; - } - } - } - return wind; - } - - - - /** - * Fire preGravityModel event. - * - * @return <code>NaN</code> normally, or overriding gravity. - */ - public static double firePreGravityModel(SimulationStatus status) - throws SimulationException { - double gravity; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - gravity = ((SimulationComputationListener) l).preGravityModel(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (!Double.isNaN(gravity)) { - warn(status, l); - return gravity; - } - } - } - return Double.NaN; - } - - /** - * Fire postGravityModel event. - * - * @return the gravity to use. - */ - public static double firePostGravityModel(SimulationStatus status, double gravity) throws SimulationException { - double g; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - g = ((SimulationComputationListener) l).postGravityModel(status, gravity); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (!Double.isNaN(g) && !MathUtil.equals(g, gravity)) { - warn(status, l); - gravity = g; - } - } - } - return gravity; - } - - - - - /** - * Fire preFlightConditions event. - * - * @return <code>null</code> normally, or overriding flight conditions. - */ - public static FlightConditions firePreFlightConditions(SimulationStatus status) - throws SimulationException { - FlightConditions conditions; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - conditions = ((SimulationComputationListener) l).preFlightConditions(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (conditions != null) { - warn(status, l); - return conditions; - } - } - } - return null; - } - - /** - * Fire postFlightConditions event. - * - * @return the flight conditions to use: either <code>conditions</code> or a new object - * containing the modified conditions. - */ - public static FlightConditions firePostFlightConditions(SimulationStatus status, FlightConditions conditions) - throws SimulationException { - FlightConditions c; - FlightConditions clone = conditions.clone(); - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - c = ((SimulationComputationListener) l).postFlightConditions(status, clone); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (c != null && !c.equals(conditions)) { - warn(status, l); - conditions = c; - clone = conditions.clone(); - } - } - } - return conditions; - } - - - - - /** - * Fire preAerodynamicCalculation event. - * - * @return <code>null</code> normally, or overriding aerodynamic forces. - */ - public static AerodynamicForces firePreAerodynamicCalculation(SimulationStatus status) - throws SimulationException { - AerodynamicForces forces; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - forces = ((SimulationComputationListener) l).preAerodynamicCalculation(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (forces != null) { - warn(status, l); - return forces; - } - } - } - return null; - } - - /** - * Fire postAerodynamicCalculation event. - * - * @return the aerodynamic forces to use. - */ - public static AerodynamicForces firePostAerodynamicCalculation(SimulationStatus status, AerodynamicForces forces) - throws SimulationException { - AerodynamicForces f; - AerodynamicForces clone = forces.clone(); - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - f = ((SimulationComputationListener) l).postAerodynamicCalculation(status, clone); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (f != null && !f.equals(forces)) { - warn(status, l); - forces = f; - clone = forces.clone(); - } - } - } - return forces; - } - - - - - - /** - * Fire preMassCalculation event. - * - * @return <code>null</code> normally, or overriding mass data. - */ - public static MassData firePreMassCalculation(SimulationStatus status) - throws SimulationException { - MassData mass; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - mass = ((SimulationComputationListener) l).preMassCalculation(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (mass != null) { - warn(status, l); - return mass; - } - } - } - return null; - } - - /** - * Fire postMassCalculation event. - * - * @return the aerodynamic forces to use. - */ - public static MassData firePostMassCalculation(SimulationStatus status, MassData mass) throws SimulationException { - MassData m; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - m = ((SimulationComputationListener) l).postMassCalculation(status, mass); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (m != null && !m.equals(mass)) { - warn(status, l); - mass = m; - } - } - } - return mass; - } - - - - - /** - * Fire preThrustComputation event. - * - * @return <code>NaN</code> normally, or overriding thrust. - */ - public static double firePreThrustCalculation(SimulationStatus status) - throws SimulationException { - double thrust; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - thrust = ((SimulationComputationListener) l).preSimpleThrustCalculation(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (!Double.isNaN(thrust)) { - warn(status, l); - return thrust; - } - } - } - return Double.NaN; - } - - /** - * Fire postThrustComputation event. - * - * @return the thrust value to use. - */ - public static double firePostThrustCalculation(SimulationStatus status, double thrust) throws SimulationException { - double t; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - t = ((SimulationComputationListener) l).postSimpleThrustCalculation(status, thrust); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (!Double.isNaN(t) && !MathUtil.equals(t, thrust)) { - warn(status, l); - thrust = t; - } - } - } - return thrust; - } - - - - - - /** - * Fire preMassCalculation event. - * - * @return <code>null</code> normally, or overriding mass data. - */ - public static AccelerationData firePreAccelerationCalculation(SimulationStatus status) throws SimulationException { - AccelerationData acceleration; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - acceleration = ((SimulationComputationListener) l).preAccelerationCalculation(status); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (acceleration != null) { - warn(status, l); - return acceleration; - } - } - } - return null; - } - - /** - * Fire postMassCalculation event. - * - * @return the aerodynamic forces to use. - */ - public static AccelerationData firePostAccelerationCalculation(SimulationStatus status, - AccelerationData acceleration) throws SimulationException { - AccelerationData a; - int modID = status.getModID(); - - for (SimulationListener l : status.getSimulationConditions().getSimulationListenerList()) { - if (l instanceof SimulationComputationListener) { - a = ((SimulationComputationListener) l).postAccelerationCalculation(status, acceleration); - if (modID != status.getModID()) { - warn(status, l); - modID = status.getModID(); - } - if (a != null && !a.equals(acceleration)) { - warn(status, l); - acceleration = a; - } - } - } - return acceleration; - } - - - - - private static void warn(SimulationStatus status, SimulationListener listener) { - if (!listener.isSystemListener()) { - log.info("Non-system listener " + listener + " affected the simulation"); - status.getWarnings().add(Warning.LISTENERS_AFFECTED); - } - } -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/example/AirStart.java b/core/src/net/sf/openrocket/simulation/listeners/example/AirStart.java deleted file mode 100644 index 97ce93a2..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/example/AirStart.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.sf.openrocket.simulation.listeners.example; - -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.util.Coordinate; - -/** - * Simulation listener that launches a rocket from a specific altitude. - * <p> - * The altitude is read from the system property "openrocket.airstart.altitude" - * if defined, otherwise a default altitude of 1000 meters is used. - */ -public class AirStart extends AbstractSimulationListener { - - /** Default launch altitude */ - private static final double DEFAULT_ALTITUDE = 1000.0; - - @Override - public void startSimulation(SimulationStatus status) throws SimulationException { - - // Get the launch altitude - double altitude; - String arg = System.getProperty("openrocket.airstart.altitude"); - try { - altitude = Double.parseDouble(arg); - } catch (RuntimeException e) { - altitude = DEFAULT_ALTITUDE; - } - - // Modify launch position - Coordinate position = status.getRocketPosition(); - position = position.add(0, 0, altitude); - status.setRocketPosition(position); - - } - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/example/CSVSaveListener.java b/core/src/net/sf/openrocket/simulation/listeners/example/CSVSaveListener.java deleted file mode 100644 index 05a55fa2..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/example/CSVSaveListener.java +++ /dev/null @@ -1,295 +0,0 @@ -package net.sf.openrocket.simulation.listeners.example; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.util.Iterator; - -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; - - -public class CSVSaveListener extends AbstractSimulationListener { - - private static enum Types { - TIME { - @Override - public double getValue(SimulationStatus status) { - return status.getSimulationTime(); - } - }, - POSITION_X { - @Override - public double getValue(SimulationStatus status) { - return status.getRocketPosition().x; - } - }, - POSITION_Y { - @Override - public double getValue(SimulationStatus status) { - return status.getRocketPosition().y; - } - }, - ALTITUDE { - @Override - public double getValue(SimulationStatus status) { - return status.getRocketPosition().z; - } - }, - VELOCITY_X { - @Override - public double getValue(SimulationStatus status) { - return status.getRocketVelocity().x; - } - }, - VELOCITY_Y { - @Override - public double getValue(SimulationStatus status) { - return status.getRocketVelocity().y; - } - }, - VELOCITY_Z { - @Override - public double getValue(SimulationStatus status) { - return status.getRocketVelocity().z; - } - }, - THETA { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_ORIENTATION_THETA); - } - }, - PHI { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_ORIENTATION_PHI); - } - }, - AOA { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_AOA); - } - }, - ROLLRATE { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_ROLL_RATE); - } - }, - PITCHRATE { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_PITCH_RATE); - } - }, - - PITCHMOMENT { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_PITCH_MOMENT_COEFF); - } - }, - YAWMOMENT { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_YAW_MOMENT_COEFF); - } - }, - ROLLMOMENT { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_ROLL_MOMENT_COEFF); - } - }, - NORMALFORCE { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_NORMAL_FORCE_COEFF); - } - }, - SIDEFORCE { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_SIDE_FORCE_COEFF); - } - }, - AXIALFORCE { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_DRAG_FORCE); - } - }, - WINDSPEED { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_WIND_VELOCITY); - } - }, - PITCHDAMPING { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_PITCH_DAMPING_MOMENT_COEFF); - } - }, - CA { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_AXIAL_DRAG_COEFF); - } - }, - CD { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_DRAG_COEFF); - } - }, - CDpressure { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_PRESSURE_DRAG_COEFF); - } - }, - CDfriction { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_FRICTION_DRAG_COEFF); - } - }, - CDbase { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_BASE_DRAG_COEFF); - } - }, - MACH { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_MACH_NUMBER); - } - }, - RE { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_REYNOLDS_NUMBER); - } - }, - - CONTROL_ANGLE { - @Override - public double getValue(SimulationStatus status) { - Iterator<RocketComponent> iterator = - status.getConfiguration().getRocket().iterator(); - FinSet fin = null; - - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - if (c instanceof FinSet && c.getName().equals("CONTROL")) { - fin = (FinSet) c; - break; - } - } - if (fin == null) - return 0; - return fin.getCantAngle(); - } - }, - - MASS { - @Override - public double getValue(SimulationStatus status) { - return status.getFlightData().getLast(FlightDataType.TYPE_MASS); - } - } - - ; - - public abstract double getValue(SimulationStatus status); - } - - - public static final String FILENAME_FORMAT = "simulation-%03d.csv"; - - private File file; - private PrintStream output = null; - - - @Override - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException { - - if (event.getType() == FlightEvent.Type.LAUNCH) { - int n = 1; - - if (output != null) { - System.err.println("WARNING: Ending simulation logging to CSV file " + - "(SIMULATION_END not encountered)."); - output.close(); - output = null; - } - - do { - file = new File(String.format(FILENAME_FORMAT, n)); - n++; - } while (file.exists()); - - System.err.println("Opening file " + file + " for CSV output."); - try { - output = new PrintStream(file); - } catch (FileNotFoundException e) { - System.err.println("ERROR OPENING FILE: " + e); - } - - final Types[] types = Types.values(); - StringBuilder s = new StringBuilder("# " + types[0].toString()); - for (int i = 1; i < types.length; i++) { - s.append("," + types[i].toString()); - } - output.println(s); - - } else if (event.getType() == FlightEvent.Type.SIMULATION_END && output != null) { - - System.err.println("Ending simulation logging to CSV file: " + file); - output.close(); - output = null; - - } else if (event.getType() != FlightEvent.Type.ALTITUDE) { - - if (output != null) { - output.println("# Event " + event); - } else { - System.err.println("WARNING: Event " + event + " encountered without open file"); - } - - } - - return true; - } - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - - final Types[] types = Types.values(); - StringBuilder s; - - if (output != null) { - - s = new StringBuilder("" + types[0].getValue(status)); - for (int i = 1; i < types.length; i++) { - s.append("," + types[i].getValue(status)); - } - output.println(s); - - } else { - - System.err.println("WARNING: stepTaken called with no open file " + - "(t=" + status.getSimulationTime() + ")"); - } - - } -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/example/DampingMoment.java b/core/src/net/sf/openrocket/simulation/listeners/example/DampingMoment.java deleted file mode 100644 index b9d2e463..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/example/DampingMoment.java +++ /dev/null @@ -1,129 +0,0 @@ -package net.sf.openrocket.simulation.listeners.example; - -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.AerodynamicForces; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.motor.MotorId; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.motor.MotorInstanceConfiguration; -import net.sf.openrocket.rocketcomponent.MotorMount; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.ArrayList; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.PolyInterpolator; - -public class DampingMoment extends AbstractSimulationListener { - - private static final FlightDataType type = FlightDataType.getType("Damping moment coefficient", "Cdm", UnitGroup.UNITS_COEFFICIENT); - private static final FlightDataType[] typeList = {type}; - - public String getName(){ - return "Damping moment listener"; - } - - /** - * Return a list of any flight data types this listener creates. - */ - public FlightDataType[] getFlightDataTypes(){ - return typeList; - } - - @Override - public FlightConditions postFlightConditions(SimulationStatus status, FlightConditions flightConditions) throws SimulationException { - - // Save it as a flightdatatype - - //status.getFlightData().setValue(type, aerodynamicPart + propulsivePart); - status.getFlightData().setValue(type, calculate(status, flightConditions)); - - return flightConditions; - } - - private double calculate(SimulationStatus status, FlightConditions flightConditions){ - - // Work out the propulsive/jet damping part of the moment. - - // dm/dt = (thrust - ma)/v - FlightDataBranch data = status.getFlightData(); - - List<Double> mpAll = data.get(FlightDataType.TYPE_PROPELLANT_MASS); - List<Double> time = data.get(FlightDataType.TYPE_TIME); - if (mpAll == null || time == null){ - return Double.NaN; - } - - int len = mpAll.size(); - - // This isn't as accurate as I would like - double mdot=Double.NaN; - if (len > 2){ - // Using polynomial interpolator for derivative. Doesn't help much - //double[] x = { time.get(len-5), time.get(len-4), time.get(len-3), time.get(len-2), time.get(len-1) }; - //double[] y = { mpAll.get(len-5), mpAll.get(len-4), mpAll.get(len-3), mpAll.get(len-2), mpAll.get(len-1) }; - //PolyInterpolator interp = new PolyInterpolator(x); - //double[] coeff = interp.interpolator(y); - //double dt = .01; - //mdot = (interp.eval(x[4], coeff) - interp.eval(x[4]-dt, coeff))/dt; - - mdot = (mpAll.get(len-1) - mpAll.get(len-2)) / (time.get(len-1) - time.get(len-2)); - } - - double cg = data.getLast(FlightDataType.TYPE_CG_LOCATION); - - // find the maximum distance from nose to nozzle. - double nozzleDistance = 0; - for (MotorId id: status.getMotorConfiguration().getMotorIDs()){ - MotorInstanceConfiguration config = status.getMotorConfiguration(); - Coordinate position = config.getMotorPosition(id); - - double x = position.x + config.getMotorInstance(id).getParentMotor().getLength(); - if (x > nozzleDistance){ - nozzleDistance = x; - } - } - - // now can get the propulsive part - double propulsivePart = mdot * Math.pow(nozzleDistance - cg, 2); - - // Work out the aerodynamic part of the moment. - double aerodynamicPart = 0; - - AerodynamicCalculator aerocalc = status.getSimulationConditions().getAerodynamicCalculator(); - - // Must go through each component ... - Map<RocketComponent, AerodynamicForces> forces = aerocalc.getForceAnalysis(status.getConfiguration(), flightConditions, null); - for (Map.Entry<RocketComponent, AerodynamicForces> entry : forces.entrySet()){ - - RocketComponent comp = entry.getKey(); - - if (!comp.isAerodynamic()) continue; - - //System.out.println(comp.toString()); - - double CNa = entry.getValue().getCNa(); //? - double Cp = entry.getValue().getCP().length(); - double z = comp.getPositionValue(); //? - - aerodynamicPart += CNa*Math.pow(z-Cp, 2); - } - - double v = flightConditions.getVelocity(); - double rho = flightConditions.getAtmosphericConditions().getDensity(); - double ar = flightConditions.getRefArea(); - - aerodynamicPart = aerodynamicPart * .5 * rho * v * ar; - - return aerodynamicPart + propulsivePart; - - } - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/example/PrintSimulationListener.java b/core/src/net/sf/openrocket/simulation/listeners/example/PrintSimulationListener.java deleted file mode 100644 index ac070d2b..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/example/PrintSimulationListener.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.sf.openrocket.simulation.listeners.example; - -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; - - -public class PrintSimulationListener extends AbstractSimulationListener { - - @Override - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) throws SimulationException { - System.out.println("*** handleEvent *** " + event.toString() + - " position=" + status.getRocketPosition() + " velocity=" + status.getRocketVelocity()); - return true; - } - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - FlightDataBranch data = status.getFlightData(); - System.out.printf("*** stepTaken *** time=%.3f position=" + status.getRocketPosition() + - " velocity=" + status.getRocketVelocity() + "=%.3f\n", status.getSimulationTime(), status.getRocketVelocity().length()); - System.out.printf(" thrust=%.3fN drag==%.3fN mass=%.3fkg " + - "accZ=%.3fm/s2 acc=%.3fm/s2\n", - data.getLast(FlightDataType.TYPE_THRUST_FORCE), - data.getLast(FlightDataType.TYPE_DRAG_FORCE), - data.getLast(FlightDataType.TYPE_MASS), - data.getLast(FlightDataType.TYPE_ACCELERATION_Z), - data.getLast(FlightDataType.TYPE_ACCELERATION_TOTAL)); - } - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/example/RollControlListener.java b/core/src/net/sf/openrocket/simulation/listeners/example/RollControlListener.java deleted file mode 100644 index 68063cb4..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/example/RollControlListener.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.sf.openrocket.simulation.listeners.example; - -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.MathUtil; - -/** - * An example listener that applies a PI-controller to adjust the cant of fins - * named "CONTROL" to stop the rocket from rolling. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class RollControlListener extends AbstractSimulationListener { - - // Name of control fin set - private static final String CONTROL_FIN_NAME = "CONTROL"; - - // Define custom flight data type - private static final FlightDataType FIN_CANT_TYPE = FlightDataType.getType("Control fin cant", "\u03B1fc", UnitGroup.UNITS_ANGLE); - - // Simulation time at which PID controller is activated - private static final double START_TIME = 0.5; - - // Desired roll rate (rad/sec) - private static final double SETPOINT = 0.0; - - // Maximum control fin turn rate (rad/sec) - private static final double TURNRATE = 10 * Math.PI / 180; - - // Maximum control fin angle (rad) - private static final double MAX_ANGLE = 15 * Math.PI / 180; - - - /* - * PID parameters - * - * At M=0.3 KP oscillation threshold between 0.35 and 0.4. Good KI=3 - * At M=0.6 KP oscillation threshold between 0.07 and 0.08 Good KI=2 - * At M=0.9 KP oscillation threshold between 0.013 and 0.014 Good KI=0.5 - */ - private static final double KP = 0.007; - private static final double KI = 0.2; - - - - - private double rollrate; - - private double prevTime = 0; - private double intState = 0; - - private double finPosition = 0; - - - - @Override - public FlightConditions postFlightConditions(SimulationStatus status, FlightConditions flightConditions) { - // Store the current roll rate for later use - rollrate = flightConditions.getRollRate(); - return null; - } - - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - - // Activate PID controller only after a specific time - if (status.getSimulationTime() < START_TIME) { - prevTime = status.getSimulationTime(); - return; - } - - // Find the fin set named CONTROL - FinSet finset = null; - for (RocketComponent c : status.getConfiguration()) { - if ((c instanceof FinSet) && (c.getName().equals(CONTROL_FIN_NAME))) { - finset = (FinSet) c; - break; - } - } - if (finset == null) { - throw new SimulationException("A fin set with name '" + CONTROL_FIN_NAME + "' was not found"); - } - - - // Determine time step - double deltaT = status.getSimulationTime() - prevTime; - prevTime = status.getSimulationTime(); - - - // PID controller - double error = SETPOINT - rollrate; - - double p = KP * error; - intState += error * deltaT; - double i = KI * intState; - - double value = p + i; - - - // Clamp the fin angle between -MAX_ANGLE and MAX_ANGLE - if (Math.abs(value) > MAX_ANGLE) { - System.err.printf("Attempting to set angle %.1f at t=%.3f, clamping.\n", - value * 180 / Math.PI, status.getSimulationTime()); - value = MathUtil.clamp(value, -MAX_ANGLE, MAX_ANGLE); - } - - - // Limit the fin turn rate - if (finPosition < value) { - finPosition = Math.min(finPosition + TURNRATE * deltaT, value); - } else { - finPosition = Math.max(finPosition - TURNRATE * deltaT, value); - } - - // Set the control fin cant and store the data - finset.setCantAngle(finPosition); - status.getFlightData().setValue(FIN_CANT_TYPE, finPosition); - - } -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/example/StopSimulationListener.java b/core/src/net/sf/openrocket/simulation/listeners/example/StopSimulationListener.java deleted file mode 100644 index 1dd74436..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/example/StopSimulationListener.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.sf.openrocket.simulation.listeners.example; - -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; - -/** - * A simulation listener that stops the simulation after a specified number of steps or - * after a specified abount of simulation time. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class StopSimulationListener extends AbstractSimulationListener { - - private final int REPORT = 500; - - private final double stopTime; - private final int stopStep; - - private int step = 0; - - private long startTime = -1; - private long time = -1; - - public StopSimulationListener(double t, int n) { - stopTime = t; - stopStep = n; - } - - @Override - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) { - - if (event.getType() == FlightEvent.Type.LAUNCH) { - System.out.println("Simulation starting."); - time = System.nanoTime(); - startTime = System.nanoTime(); - } - - return true; - } - - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - step++; - if ((step % REPORT) == 0) { - long t = System.nanoTime(); - - System.out.printf("Step %4d, time=%.3f, took %d us/step (avg. %d us/step)\n", - step, status.getSimulationTime(), (t - time) / 1000 / REPORT, (t - startTime) / 1000 / step); - time = t; - } - if (status.getSimulationTime() >= stopTime || step >= stopStep) { - System.out.printf("Stopping simulation, step=%d time=%.3f\n", step, status.getSimulationTime()); - status.getEventQueue().add(new FlightEvent(FlightEvent.Type.SIMULATION_END, - status.getSimulationTime(), null)); - } - } - -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/system/ApogeeEndListener.java b/core/src/net/sf/openrocket/simulation/listeners/system/ApogeeEndListener.java deleted file mode 100644 index 60081224..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/system/ApogeeEndListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.simulation.listeners.system; - -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; - - -/** - * A simulation listeners that ends the simulation when apogee is reached. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class ApogeeEndListener extends AbstractSimulationListener { - - public static final ApogeeEndListener INSTANCE = new ApogeeEndListener(); - - @Override - public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) { - if (event.getType() == FlightEvent.Type.APOGEE) { - status.getEventQueue().add(new FlightEvent(FlightEvent.Type.SIMULATION_END, status.getSimulationTime())); - } - return true; - } - - @Override - public boolean isSystemListener() { - return true; - } -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/system/InterruptListener.java b/core/src/net/sf/openrocket/simulation/listeners/system/InterruptListener.java deleted file mode 100644 index e2460098..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/system/InterruptListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.simulation.listeners.system; - -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationCancelledException; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; - - -/** - * A simulation listener that throws a {@link SimulationCancelledException} if - * this thread has been interrupted. The conditions is checked every time a step - * is taken. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class InterruptListener extends AbstractSimulationListener { - - public static final InterruptListener INSTANCE = new InterruptListener(); - - @Override - public void postStep(SimulationStatus status) throws SimulationException { - if (Thread.interrupted()) { - throw new SimulationCancelledException("The simulation was interrupted."); - } - } - - @Override - public boolean isSystemListener() { - return true; - } -} diff --git a/core/src/net/sf/openrocket/simulation/listeners/system/RecoveryDeviceDeploymentEndListener.java b/core/src/net/sf/openrocket/simulation/listeners/system/RecoveryDeviceDeploymentEndListener.java deleted file mode 100644 index b6bac333..00000000 --- a/core/src/net/sf/openrocket/simulation/listeners/system/RecoveryDeviceDeploymentEndListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.simulation.listeners.system; - -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.simulation.FlightEvent; -import net.sf.openrocket.simulation.SimulationStatus; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.simulation.listeners.AbstractSimulationListener; - - -/** - * A simulation listeners that ends the simulation when apogee is reached. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class RecoveryDeviceDeploymentEndListener extends AbstractSimulationListener { - - public static final RecoveryDeviceDeploymentEndListener INSTANCE = new RecoveryDeviceDeploymentEndListener(); - - @Override - public boolean recoveryDeviceDeployment(SimulationStatus status, RecoveryDevice recoveryDevice) throws SimulationException { - status.getEventQueue().add(new FlightEvent(FlightEvent.Type.SIMULATION_END, status.getSimulationTime())); - return true; - } - - @Override - public boolean isSystemListener() { - return true; - } -} diff --git a/core/src/net/sf/openrocket/startup/Application.java b/core/src/net/sf/openrocket/startup/Application.java deleted file mode 100644 index 18d1af77..00000000 --- a/core/src/net/sf/openrocket/startup/Application.java +++ /dev/null @@ -1,176 +0,0 @@ -package net.sf.openrocket.startup; - -import net.sf.openrocket.database.ComponentPresetDao; -import net.sf.openrocket.database.MotorDatabase; -import net.sf.openrocket.l10n.ClassBasedTranslator; -import net.sf.openrocket.l10n.DebugTranslator; -import net.sf.openrocket.l10n.ExceptionSuppressingTranslator; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.LogLevel; -import net.sf.openrocket.logging.LogLevelBufferLogger; -import net.sf.openrocket.logging.PrintStreamLogger; - -/** - * A class that provides singleton instances / beans for other classes to utilize. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public final class Application { - - private static LogHelper logger; - private static LogLevelBufferLogger logBuffer; - - private static Translator baseTranslator = new DebugTranslator(null); - - private static MotorDatabase motorSetDatabase; - - private static ComponentPresetDao componentPresetDao; - - private static Preferences preferences; - - private static ExceptionHandler exceptionHandler; - - // Initialize the logger to something sane for testing without executing Startup - static { - setLogOutputLevel(LogLevel.DEBUG); - } - - /** - * Return whether to use additional safety code checks. - */ - public static boolean useSafetyChecks() { - // Currently default to false unless openrocket.debug.safetycheck is defined - String s = System.getProperty("openrocket.debug.safetycheck"); - if (s != null && !(s.equalsIgnoreCase("false") || s.equalsIgnoreCase("off"))) { - return true; - } - return false; - } - - /** - * Retrieve the logger to be used in logging. By default this returns - * a logger that outputs to stdout/stderr even if not separately initialized, - * useful for development and debugging. - */ - public static LogHelper getLogger() { - return logger; - } - - /** - * Set the logger to be used in logging. Note that calling this will only have effect - * on not-yet loaded classes, as the instance is stored in a static variable. - */ - public static void setLogger(LogHelper logger) { - Application.logger = logger; - } - - - - /** - * Return the log buffer. - * - * @return the logBuffer or null if not initialized - */ - public static LogLevelBufferLogger getLogBuffer() { - return logBuffer; - } - - /** - * Set the log buffer logger. The logger must be separately configured - * to receive the logging. - */ - public static void setLogBuffer(LogLevelBufferLogger logBuffer) { - Application.logBuffer = logBuffer; - } - - - /** - * Set the logging to output the specified log level and upwards to standard output. - * - * @param level the minimum logging level to output. - */ - public static void setLogOutputLevel(LogLevel level) { - logger = new PrintStreamLogger(); - for (LogLevel l : LogLevel.values()) { - if (l.atLeast(level)) { - ((PrintStreamLogger) logger).setOutput(l, System.out); - } - } - - } - - - /** - * Return the translator to use for obtaining translated strings. - * @return a translator. - */ - public static Translator getTranslator() { - Translator t = baseTranslator; - t = new ClassBasedTranslator(t, 1); - t = new ExceptionSuppressingTranslator(t); - return t; - } - - /** - * Set the translator used in obtaining translated strings. - * @param translator the translator to set. - */ - public static void setBaseTranslator(Translator translator) { - Application.baseTranslator = translator; - } - - - /** - * @return the preferences - */ - public static Preferences getPreferences() { - return preferences; - } - - /** - * @param preferences the preferences to set - */ - public static void setPreferences(Preferences preferences) { - Application.preferences = preferences; - } - - /** - * @return the exceptionHandler - */ - public static ExceptionHandler getExceptionHandler() { - return exceptionHandler; - } - - /** - * @param exceptionHandler the exceptionHandler to set - */ - public static void setExceptionHandler(ExceptionHandler exceptionHandler) { - Application.exceptionHandler = exceptionHandler; - } - - /** - * Return the database of all thrust curves loaded into the system. - */ - public static MotorDatabase getMotorSetDatabase() { - return motorSetDatabase; - } - - /** - * Set the database of thrust curves loaded into the system. - */ - public static void setMotorSetDatabase(MotorDatabase motorSetDatabase) { - Application.motorSetDatabase = motorSetDatabase; - } - - public static ComponentPresetDao getComponentPresetDao() { - return componentPresetDao; - - } - - public static void setComponentPresetDao(ComponentPresetDao componentPresetDao) { - Application.componentPresetDao = componentPresetDao; - } - - -} diff --git a/core/src/net/sf/openrocket/startup/ConcurrentComponentPresetDatabaseLoader.java b/core/src/net/sf/openrocket/startup/ConcurrentComponentPresetDatabaseLoader.java deleted file mode 100644 index 79838ece..00000000 --- a/core/src/net/sf/openrocket/startup/ConcurrentComponentPresetDatabaseLoader.java +++ /dev/null @@ -1,140 +0,0 @@ -package net.sf.openrocket.startup; - -import java.io.InputStream; -import java.util.Collection; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import net.sf.openrocket.database.ComponentPresetDatabase; -import net.sf.openrocket.file.iterator.DirectoryIterator; -import net.sf.openrocket.file.iterator.FileIterator; -import net.sf.openrocket.gui.util.SimpleFileFilter; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.xml.OpenRocketComponentLoader; -import net.sf.openrocket.util.Pair; - -public class ConcurrentComponentPresetDatabaseLoader { - - private static final LogHelper log = Application.getLogger(); - private static final String SYSTEM_PRESET_DIR = "datafiles/presets"; - - private final CountDownLatch latch = new CountDownLatch(1); - - private final ComponentPresetDatabase componentPresetDao; - - private final ExecutorService writerPool; - - private final ExecutorService loaderPool; - - private final Thread workGenerator; - - private FileIterator iterator; - - private long startTime; - private long fileCount = 0; - private long presetCount = 0; - - ConcurrentComponentPresetDatabaseLoader( ComponentPresetDatabase componentPresetDao ) { - this.componentPresetDao = componentPresetDao; - - writerPool = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r,"PresetWriterThread"); - return t; - } - }); - - loaderPool = Executors.newFixedThreadPool(3, new ThreadFactory() { - int threadCount = 0; - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r,"PresetLoaderPool-" + threadCount++); - t.setPriority(Thread.MIN_PRIORITY); - return t; - } - - }); - - workGenerator = new Thread( new WorkGenerator(),"PresetGeneratorThread"); - } - - public void load() { - startTime = System.currentTimeMillis(); - workGenerator.start(); - } - - public void await() throws InterruptedException { - latch.await(); - loaderPool.shutdown(); - loaderPool.awaitTermination(90, TimeUnit.SECONDS); - writerPool.shutdown(); - writerPool.awaitTermination(90, TimeUnit.SECONDS); - if ( iterator != null ) { - iterator.close(); - } - long end = System.currentTimeMillis(); - log.debug("Time to load presets: " + (end-startTime) + "ms " + presetCount + " loaded from " + fileCount + " files"); - } - - - private class WorkGenerator implements Runnable { - @Override - public void run() { - // Start loading - log.info("Loading component presets from " + SYSTEM_PRESET_DIR); - - iterator = DirectoryIterator.findDirectory(SYSTEM_PRESET_DIR, - new SimpleFileFilter("", false, "orc")); - - if (iterator != null) { - while( iterator.hasNext() ) { - Pair<String,InputStream> f = iterator.next(); - FileLoader loader = new FileLoader( f.getV(), f.getU() ); - loaderPool.execute(loader); - fileCount ++; - } - } - latch.countDown(); - } - } - - private class FileLoader implements Runnable { - private final InputStream is; - private final String fileName; - - public FileLoader(InputStream is, String fileName) { - super(); - this.is = is; - this.fileName = fileName; - } - - @Override - public void run() { - OpenRocketComponentLoader loader = new OpenRocketComponentLoader(); - Collection<ComponentPreset> presets = loader.load(is, fileName); - PresetWriter writer = new PresetWriter(presets); - writerPool.execute(writer); - } - } - - private class PresetWriter implements Runnable { - private final Collection<ComponentPreset> presets; - - public PresetWriter(Collection<ComponentPreset> presets) { - super(); - this.presets = presets; - } - - @Override - public void run() { - presetCount += presets.size(); - componentPresetDao.addAll(presets); - } - - } -} diff --git a/core/src/net/sf/openrocket/startup/ConcurrentLoadingThrustCurveMotorSetDatabase.java b/core/src/net/sf/openrocket/startup/ConcurrentLoadingThrustCurveMotorSetDatabase.java deleted file mode 100644 index 2eba9b42..00000000 --- a/core/src/net/sf/openrocket/startup/ConcurrentLoadingThrustCurveMotorSetDatabase.java +++ /dev/null @@ -1,302 +0,0 @@ -package net.sf.openrocket.startup; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import net.sf.openrocket.database.ThrustCurveMotorSet; -import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; -import net.sf.openrocket.file.iterator.DirectoryIterator; -import net.sf.openrocket.file.iterator.FileIterator; -import net.sf.openrocket.file.motor.MotorLoaderHelper; -import net.sf.openrocket.gui.util.SimpleFileFilter; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.Pair; - -/** - * Load motors in parallel using a three stage pipeline. - * - * Stage 1: single thread managed by the ThrustCurveMotorSetDatabase. This thread generates - * one object for each thrust curve motor file and puts it in the second stage. - * - * Stage 2: multiple threads which process individual files. Each process takes - * a single motor file and parses out the list of motors it contains. - * The list of motors is queued up for the third stage to process. - * - * Stage 3: single thread which processes the list of motors generated in stage 2. - * This thread puts all the motors from the list in the motor set database. - * - * It is important that stage 3 be done with a single thread because ThrustCurveMotorSetDatabase - * is not thread safe. Even if synchronization were to be done, it is unlikely that parallelizing - * this process would improve anything. - * - * - */ -public class ConcurrentLoadingThrustCurveMotorSetDatabase extends ThrustCurveMotorSetDatabase { - - private static final LogHelper log = Application.getLogger(); - private final String thrustCurveDirectory; - - /** Block motor loading for this many milliseconds */ - // Block motor loading for 1.5 seconds to allow window painting to be faster - private static AtomicInteger blockLoading = new AtomicInteger(1500); - - public ConcurrentLoadingThrustCurveMotorSetDatabase(String thrustCurveDirectory) { - // configure ThrustCurveMotorSetDatabase as true so we get our own thread in - // loadMotors. - super(true); - this.thrustCurveDirectory = thrustCurveDirectory; - } - - @Override - protected void loadMotors() { - - // Block loading until timeout occurs or database is taken into use - log.info("Blocking motor loading while starting up"); - /* - while (!inUse && blockLoading.addAndGet(-100) > 0) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } - */ - log.info("Blocking ended, inUse=" + inUse + " blockLoading=" + blockLoading.get()); - - BookKeeping keeper = new BookKeeping(); - keeper.start(); - - try { - keeper.waitForFinish(); - } - catch ( InterruptedException iex ) { - throw new BugException(iex); - } - - keeper = null; - - } - - private void addAll( List<Motor> motors ) { - for (Motor m : motors) { - addMotor( (ThrustCurveMotor) m); - } - } - - /** - * A class which holds all the threading data. - * Implemented as an inner class so we can easily jettison the references when - * the processing is terminated. - * - */ - private class BookKeeping { - - /* - * Executor for Stage 3. - */ - private final ExecutorService writerThread; - - /* - * Executor for Stage 2. - */ - private final ExecutorService loaderPool; - - /* - * Runnable used for Stage 1. - */ - private final WorkGenerator workGenerator; - - private long startTime; - - /* - * Number of thrust curves loaded - */ - private int thrustCurveCount = 0; - - /* - * Number of files processed. - */ - private int fileCount = 0; - - /* - * We have to hold on to the zip file iterator which is used to load - * the system motor files until all processing is done. This is because - * closing the iterator prematurely causes all the InputStreams opened - * with it to close. - */ - private FileIterator iterator; - - private BookKeeping() { - - writerThread = new ThreadPoolExecutor(1,1,200, TimeUnit.SECONDS, - new LinkedBlockingQueue<Runnable>(), - new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r,"MotorWriterThread"); - return t; - } - }); - - loaderPool = new ThreadPoolExecutor(10,10, 2, TimeUnit.SECONDS, - new LinkedBlockingQueue<Runnable>(), - new ThreadFactory() { - int threadCount = 0; - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r,"MotorLoaderPool-" + threadCount++); - return t; - } - }); - - workGenerator = new WorkGenerator(); - - } - - private void start() { - - startTime = System.currentTimeMillis(); - - log.info("Starting motor loading from " + thrustCurveDirectory + " in background thread."); - - // Run the work generator - in this thread. - workGenerator.run(); - - } - - private void waitForFinish() throws InterruptedException { - try { - loaderPool.shutdown(); - loaderPool.awaitTermination(90, TimeUnit.SECONDS); - writerThread.shutdown(); - writerThread.awaitTermination(90, TimeUnit.SECONDS); - } - finally { - iterator.close(); - } - - long endTime = System.currentTimeMillis(); - - int distinctMotorCount = 0; - int distinctThrustCurveCount = 0; - distinctMotorCount = motorSets.size(); - for (ThrustCurveMotorSet set : motorSets) { - distinctThrustCurveCount += set.getMotorCount(); - } - - log.info("Motor loading done, took " + (endTime - startTime) + " ms to load " - + fileCount + " files/directories containing " - + thrustCurveCount + " thrust curves which contained " - + distinctMotorCount + " distinct motors with " - + distinctThrustCurveCount + " distinct thrust curves."); - - } - - - private class WorkGenerator implements Runnable { - - @Override - public void run() { - // Start loading - log.info("Loading motors from " + thrustCurveDirectory); - - iterator = DirectoryIterator.findDirectory(thrustCurveDirectory, - new SimpleFileFilter("", false, "eng", "rse")); - - // Load the packaged thrust curves - if (iterator == null) { - throw new IllegalStateException("Thrust curve directory " + thrustCurveDirectory + - "not found, distribution built wrong"); - } - - while( iterator.hasNext() ) { - Pair<String,InputStream> f = iterator.next(); - MotorLoader loader = new MotorLoader( f.getV(), f.getU() ); - loaderPool.execute(loader); - fileCount ++; - } - - // Load the user-defined thrust curves - for (File file : ((SwingPreferences) Application.getPreferences()).getUserThrustCurveFiles()) { - log.info("Loading motors from " + file); - MotorLoader loader = new MotorLoader( file ); - loaderPool.execute(loader); - fileCount++; - } - } - } - - private class MotorLoader implements Runnable { - - private final InputStream is; - private final String fileName; - - private final File file; - - public MotorLoader( File file ) { - super(); - this.file = file; - this.is = null; - this.fileName = null; - } - - public MotorLoader(InputStream is, String fileName) { - super(); - this.file = null; - this.is = is; - this.fileName = fileName; - } - - @Override - public void run() { - log.debug("Loading motor from " + fileName); - - try { - List<Motor> motors; - if ( file == null ) { - motors = MotorLoaderHelper.load(is, fileName); - } else { - motors = MotorLoaderHelper.load(file); - } - writerThread.submit( new MotorInserter(motors)); - } - finally { - if ( is != null ) { - try { - is.close(); - } catch ( IOException iex ) { - } - } - } - } - } - - private class MotorInserter implements Runnable { - - private final List<Motor> motors; - - MotorInserter( List<Motor> motors ) { - this.motors = motors; - } - - @Override - public void run() { - thrustCurveCount += motors.size(); - ConcurrentLoadingThrustCurveMotorSetDatabase.this.addAll(motors); - } - - } - } - -} diff --git a/core/src/net/sf/openrocket/startup/ExceptionHandler.java b/core/src/net/sf/openrocket/startup/ExceptionHandler.java deleted file mode 100644 index fa115322..00000000 --- a/core/src/net/sf/openrocket/startup/ExceptionHandler.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.sf.openrocket.startup; - -public interface ExceptionHandler { - - public void handleErrorCondition(String message); - public void handleErrorCondition(String message, Throwable exception); - public void handleErrorCondition(final Throwable exception); - - - public void uncaughtException(final Thread thread, final Throwable throwable); - -} diff --git a/core/src/net/sf/openrocket/startup/OSXStartup.java b/core/src/net/sf/openrocket/startup/OSXStartup.java deleted file mode 100644 index ad14186b..00000000 --- a/core/src/net/sf/openrocket/startup/OSXStartup.java +++ /dev/null @@ -1,115 +0,0 @@ -package net.sf.openrocket.startup; - -import java.awt.Image; -import java.awt.Toolkit; - -import net.sf.openrocket.arch.SystemInfo; -import net.sf.openrocket.arch.SystemInfo.Platform; -import net.sf.openrocket.gui.dialogs.AboutDialog; -import net.sf.openrocket.gui.dialogs.preferences.PreferencesDialog; -import net.sf.openrocket.gui.main.BasicFrame; -import net.sf.openrocket.logging.LogHelper; - -import com.apple.eawt.AboutHandler; -import com.apple.eawt.PreferencesHandler; -import com.apple.eawt.QuitHandler; -import com.apple.eawt.QuitResponse; -import com.apple.eawt.AppEvent.AboutEvent; -import com.apple.eawt.AppEvent.PreferencesEvent; -import com.apple.eawt.AppEvent.QuitEvent; - -/** - * Static code for initialization of OSX UI Elements: Menu, Icon, Name and - * Application menu handlers. - * - * @author Bill Kuker <bkuker@billkuker.com> - * - */ -final class OSXStartup { - private static final LogHelper log = Application.getLogger(); - - // The name in the app menu - private static final String APP_NAME = "OpenRocket"; - - // The image resource to use for the Dock Icon - private static final String ICON_RSRC = "/pix/icon/icon-256.png"; - - /** - * The handler for the Quit item in the OSX app menu - */ - private static final QuitHandler qh = new QuitHandler() { - @Override - public void handleQuitRequestWith(final QuitEvent e, final QuitResponse r) { - BasicFrame.quitAction(); - // if we get here the user canceled - r.cancelQuit(); - } - }; - - /** - * The handler for the About item in the OSX app menu - */ - private static final AboutHandler ah = new AboutHandler() { - @Override - public void handleAbout(final AboutEvent a) { - new AboutDialog(null).setVisible(true); - } - }; - - /** - * The handler for the Preferences item in the OSX app menu - */ - private static final PreferencesHandler ph = new PreferencesHandler() { - @Override - public void handlePreferences(final PreferencesEvent p) { - PreferencesDialog.showPreferences(null); - } - }; - - /** - * Sets up the Application's Icon, Name, Menu and some menu item handlers - * for Apple OSX. This method needs to be called before other AWT or Swing - * things happen, or parts will fail to work. - * - * This function should fail gracefully if the OS is wrong. - */ - static void setupOSX() { - if (SystemInfo.getPlatform() != Platform.MAC_OS) { - log.warn("Attempting to set up OSX UI on non-MAC_OS"); - } - log.debug("Setting up OSX UI Elements"); - try { - // Put the menu bar at the top of the screen - System.setProperty("apple.laf.useScreenMenuBar", "true"); - // Set the name in the menu - System.setProperty("com.apple.mrj.application.apple.menu.about.name", APP_NAME); - - // This line must come AFTER the above properties are set, otherwise - // the name will not appear - final com.apple.eawt.Application osxApp = com.apple.eawt.Application.getApplication(); - - if (osxApp == null) { - // Application is null: Something is wrong, give up on OSX - // setup. - throw new NullPointerException("com.apple.eawt.Application.getApplication() returned NULL. " - + "Aborting OSX UI Setup."); - } - - // Set handlers - osxApp.setQuitHandler(qh); - osxApp.setAboutHandler(ah); - osxApp.setPreferencesHandler(ph); - - // Set the dock icon to the largest icon - final Image dockIcon = Toolkit.getDefaultToolkit().getImage( - Startup2.class.getResource(ICON_RSRC)); - osxApp.setDockIconImage(dockIcon); - - } catch (final Throwable t) { - // None of the preceding is critical to the app, - // so at worst case log an error and continue - log.warn("Error setting up OSX UI:", t); - } - } - -} diff --git a/core/src/net/sf/openrocket/startup/Preferences.java b/core/src/net/sf/openrocket/startup/Preferences.java deleted file mode 100644 index 73a29cc2..00000000 --- a/core/src/net/sf/openrocket/startup/Preferences.java +++ /dev/null @@ -1,408 +0,0 @@ -package net.sf.openrocket.startup; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.rocketcomponent.BodyComponent; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.InternalComponent; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassObject; -import net.sf.openrocket.rocketcomponent.RecoveryDevice; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.Color; -import net.sf.openrocket.util.LineStyle; -import net.sf.openrocket.util.MathUtil; -import net.sf.openrocket.util.UniqueID; - -public abstract class Preferences { - - /* - * Well known string keys to preferences. - * There are other strings out there in the source as well. - */ - public static final String BODY_COMPONENT_INSERT_POSITION_KEY = "BodyComponentInsertPosition"; - public static final String USER_THRUST_CURVES_KEY = "UserThrustCurves"; - public static final String CONFIRM_DELETE_SIMULATION = "ConfirmDeleteSimulation"; - // Preferences related to data export - public static final String EXPORT_FIELD_SEPARATOR = "ExportFieldSeparator"; - public static final String EXPORT_SIMULATION_COMMENT = "ExportSimulationComment"; - public static final String EXPORT_FIELD_NAME_COMMENT = "ExportFieldDescriptionComment"; - public static final String EXPORT_EVENT_COMMENTS = "ExportEventComments"; - public static final String EXPORT_COMMENT_CHARACTER = "ExportCommentCharacter"; - public static final String USER_LOCAL = "locale"; - - public static final String PLOT_SHOW_POINTS = "ShowPlotPoints"; - - private static final String CHECK_UPDATES = "CheckUpdates"; - public static final String LAST_UPDATE = "LastUpdateVersion"; - - public static final String MOTOR_DIAMETER_FILTER = "MotorDiameterMatch"; - public static final String MOTOR_HIDE_SIMILAR = "MotorHideSimilar"; - - // Node names - public static final String PREFERRED_THRUST_CURVE_MOTOR_NODE = "preferredThrustCurveMotors"; - - /* - * ****************************************************************************************** - * - * Abstract methods which must be implemented by any derived class. - */ - public abstract boolean getBoolean(String key, boolean defaultValue); - - public abstract void putBoolean(String key, boolean value); - - public abstract int getInt(String key, int defaultValue); - - public abstract void putInt(String key, int value); - - public abstract double getDouble(String key, double defaultValue); - - public abstract void putDouble(String key, double value); - - public abstract String getString(String key, String defaultValue); - - public abstract void putString(String key, String value); - - /** - * Directory represents a way to collect multiple keys together. Implementors may - * choose to concatenate the directory with the key using some special character. - * @param directory - * @param key - * @param defaultValue - * @return - */ - public abstract String getString(String directory, String key, String defaultValue); - - public abstract void putString(String directory, String key, String value); - - /* - * ****************************************************************************************** - */ - public final boolean getCheckUpdates() { - return this.getBoolean(CHECK_UPDATES, BuildProperties.getDefaultCheckUpdates()); - } - - public final void setCheckUpdates(boolean check) { - this.putBoolean(CHECK_UPDATES, check); - } - - public final double getDefaultMach() { - // TODO: HIGH: implement custom default mach number - return 0.3; - } - - /** - * Return the OpenRocket unique ID. - * - * @return a random ID string that stays constant between OpenRocket executions - */ - public final String getUniqueID() { - String id = this.getString("id", null); - if (id == null) { - id = UniqueID.uuid(); - this.putString("id", id); - } - return id; - } - - /** - * Returns a limited-range integer value from the preferences. If the value - * in the preferences is negative or greater than max, then the default value - * is returned. - * - * @param key The preference to retrieve. - * @param max Maximum allowed value for the choice. - * @param def Default value. - * @return The preference value. - */ - public final int getChoice(String key, int max, int def) { - int v = this.getInt(key, def); - if ((v < 0) || (v > max)) - return def; - return v; - } - - /** - * Helper method that puts an integer choice value into the preferences. - * - * @param key the preference key. - * @param value the value to store. - */ - public final void putChoice(String key, int value) { - this.putInt(key, value); - } - - /** - * Retrieve an enum value from the user preferences. - * - * @param <T> the enum type - * @param key the key - * @param def the default value, cannot be null - * @return the value in the preferences, or the default value - */ - public final <T extends Enum<T>> T getEnum(String key, T def) { - if (def == null) { - throw new BugException("Default value cannot be null"); - } - - String value = getString(key, null); - if (value == null) { - return def; - } - - try { - return Enum.valueOf(def.getDeclaringClass(), value); - } catch (IllegalArgumentException e) { - return def; - } - } - - /** - * Store an enum value to the user preferences. - * - * @param key the key - * @param value the value to store, or null to remove the value - */ - public final void putEnum(String key, Enum<?> value) { - if (value == null) { - putString(key, null); - } else { - putString(key, value.name()); - } - } - - public Color getDefaultColor(Class<? extends RocketComponent> c) { - String color = get("componentColors", c, DEFAULT_COLORS); - if (color == null) - return Color.BLACK; - - Color clr = parseColor(color); - if (clr != null) { - return clr; - } else { - return Color.BLACK; - } - } - - public final void setDefaultColor(Class<? extends RocketComponent> c, Color color) { - if (color == null) - return; - putString("componentColors", c.getSimpleName(), stringifyColor(color)); - } - - - /** - * Retrieve a Line style for the given component. - * @param c - * @return - */ - public final LineStyle getDefaultLineStyle(Class<? extends RocketComponent> c) { - String value = get("componentStyle", c, DEFAULT_LINE_STYLES); - try { - return LineStyle.valueOf(value); - } catch (Exception e) { - return LineStyle.SOLID; - } - } - - /** - * Set a default line style for the given component. - * @param c - * @param style - */ - public final void setDefaultLineStyle(Class<? extends RocketComponent> c, - LineStyle style) { - if (style == null) - return; - putString("componentStyle", c.getSimpleName(), style.name()); - } - - /** - * Get the default material type for the given component. - * @param componentClass - * @param type the Material.Type to return. - * @return - */ - public Material getDefaultComponentMaterial( - Class<? extends RocketComponent> componentClass, - Material.Type type) { - - String material = get("componentMaterials", componentClass, null); - if (material != null) { - try { - Material m = Material.fromStorableString(material, false); - if (m.getType() == type) - return m; - } catch (IllegalArgumentException ignore) { - } - } - - switch (type) { - case LINE: - return DefaultMaterialHolder.DEFAULT_LINE_MATERIAL; - case SURFACE: - return DefaultMaterialHolder.DEFAULT_SURFACE_MATERIAL; - case BULK: - return DefaultMaterialHolder.DEFAULT_BULK_MATERIAL; - } - throw new IllegalArgumentException("Unknown material type: " + type); - } - - /** - * Set the default material for a component type. - * @param componentClass - * @param material - */ - public void setDefaultComponentMaterial( - Class<? extends RocketComponent> componentClass, Material material) { - - putString("componentMaterials", componentClass.getSimpleName(), - material == null ? null : material.toStorableString()); - } - - /** - * get a net.sf.openrocket.util.Color object for the given key. - * @param key - * @param defaultValue - * @return - */ - public final Color getColor(String key, Color defaultValue) { - Color c = parseColor(getString(key, null)); - if (c == null) { - return defaultValue; - } - return c; - } - - /** - * set a net.sf.openrocket.util.Color preference value for the given key. - * @param key - * @param value - */ - public final void putColor(String key, Color value) { - putString(key, stringifyColor(value)); - } - - /** - * Helper function to convert a string representation into a net.sf.openrocket.util.Color object. - * @param color - * @return - */ - protected static Color parseColor(String color) { - if (color == null) { - return null; - } - - String[] rgb = color.split(","); - if (rgb.length == 3) { - try { - int red = MathUtil.clamp(Integer.parseInt(rgb[0]), 0, 255); - int green = MathUtil.clamp(Integer.parseInt(rgb[1]), 0, 255); - int blue = MathUtil.clamp(Integer.parseInt(rgb[2]), 0, 255); - return new Color(red, green, blue); - } catch (NumberFormatException ignore) { - } - } - return null; - } - - /** - * Helper function to convert a net.sf.openrocket.util.Color object into a - * String before storing in a preference. - * @param color - * @return - */ - protected static String stringifyColor(Color color) { - String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue(); - return string; - } - - /** - * Special helper function which allows for a map of default values. - * - * First getString(directory,componentClass.getSimpleName(), null) is invoked, - * if the returned value is null, the defaultMap is consulted for a value. - * - * @param directory - * @param componentClass - * @param defaultMap - * @return - */ - protected String get(String directory, - Class<? extends RocketComponent> componentClass, - Map<Class<?>, String> defaultMap) { - - // Search preferences - Class<?> c = componentClass; - while (c != null && RocketComponent.class.isAssignableFrom(c)) { - String value = this.getString(directory, c.getSimpleName(), null); - if (value != null) - return value; - c = c.getSuperclass(); - } - - if (defaultMap == null) - return null; - - // Search defaults - c = componentClass; - while (RocketComponent.class.isAssignableFrom(c)) { - String value = defaultMap.get(c); - if (value != null) - return value; - c = c.getSuperclass(); - } - - return null; - } - - public abstract void addUserMaterial(Material m); - - public abstract Set<Material> getUserMaterials(); - - public abstract void removeUserMaterial(Material m); - - public abstract void setComponentFavorite(ComponentPreset preset, ComponentPreset.Type type, boolean favorite); - - public abstract Set<String> getComponentFavorites(ComponentPreset.Type type); - - /* - * Map of default line styles - */ - private static final HashMap<Class<?>, String> DEFAULT_LINE_STYLES = - new HashMap<Class<?>, String>(); - static { - DEFAULT_LINE_STYLES.put(RocketComponent.class, LineStyle.SOLID.name()); - DEFAULT_LINE_STYLES.put(MassObject.class, LineStyle.DASHED.name()); - } - - /* - * Within a holder class so they will load only when needed. - */ - private static class DefaultMaterialHolder { - private static final Material DEFAULT_LINE_MATERIAL = Databases.findMaterial(Material.Type.LINE, "Elastic cord (round 2 mm, 1/16 in)"); - private static final Material DEFAULT_SURFACE_MATERIAL = Databases.findMaterial(Material.Type.SURFACE, "Ripstop nylon"); - private static final Material DEFAULT_BULK_MATERIAL = Databases.findMaterial(Material.Type.BULK, "Cardboard"); - } - - private static final HashMap<Class<?>, String> DEFAULT_COLORS = - new HashMap<Class<?>, String>(); - static { - DEFAULT_COLORS.put(BodyComponent.class, "0,0,240"); - DEFAULT_COLORS.put(FinSet.class, "0,0,200"); - DEFAULT_COLORS.put(LaunchLug.class, "0,0,180"); - DEFAULT_COLORS.put(InternalComponent.class, "170,0,100"); - DEFAULT_COLORS.put(MassObject.class, "0,0,0"); - DEFAULT_COLORS.put(RecoveryDevice.class, "255,0,0"); - } - - - -} diff --git a/core/src/net/sf/openrocket/startup/Startup.java b/core/src/net/sf/openrocket/startup/Startup.java deleted file mode 100644 index 31f83184..00000000 --- a/core/src/net/sf/openrocket/startup/Startup.java +++ /dev/null @@ -1,201 +0,0 @@ -package net.sf.openrocket.startup; - -import java.io.PrintStream; -import java.util.Locale; -import java.util.prefs.Preferences; - -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.DebugTranslator; -import net.sf.openrocket.l10n.L10N; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.logging.DelegatorLogger; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.LogLevel; -import net.sf.openrocket.logging.LogLevelBufferLogger; -import net.sf.openrocket.logging.PrintStreamLogger; - - -/** - * The first class in the OpenRocket startup sequence. This class is responsible - * for setting up the Application class with the statically used subsystems - * (logging and translation) and then delegating to Startup2 class. - * <p> - * This class must be very cautious about what classes it calls. This is because - * the loggers/translators for classes are initialized as static final members during - * class initialization. For example, this class MUST NOT use the Prefs class, because - * using it will cause LineStyle to be initialized, which then receives an invalid - * (not-yet-initialized) translator. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Startup { - - static LogHelper log; - - private static final String LOG_STDERR_PROPERTY = "openrocket.log.stderr"; - private static final String LOG_STDOUT_PROPERTY = "openrocket.log.stdout"; - - private static final int LOG_BUFFER_LENGTH = 50; - - /** - * OpenRocket startup main method. - */ - public static void main(final String[] args) throws Exception { - - // Check for "openrocket.debug" property before anything else - checkDebugStatus(); - - // Initialize logging first so we can use it - initializeLogging(); - - Application.setPreferences( new SwingPreferences() ); - - // Setup the translations - initializeL10n(); - - // Continue startup in Startup2 class (where Application is already set up) - Startup2.runMain(args); - - } - - - /** - * Set proper system properties if openrocket.debug is defined. - */ - private static void checkDebugStatus() { - if (System.getProperty("openrocket.debug") != null) { - setPropertyIfNotSet("openrocket.log.stdout", "VBOSE"); - setPropertyIfNotSet("openrocket.log.tracelevel", "VBOSE"); - setPropertyIfNotSet("openrocket.debug.menu", "true"); - setPropertyIfNotSet("openrocket.debug.mutexlocation", "true"); - setPropertyIfNotSet("openrocket.debug.motordigest", "true"); - } - } - - private static void setPropertyIfNotSet(String key, String value) { - if (System.getProperty(key) == null) { - System.setProperty(key, value); - } - } - - - - /** - * Initializes the loggins system. - */ - public static void initializeLogging() { - DelegatorLogger delegator = new DelegatorLogger(); - - // Log buffer - LogLevelBufferLogger buffer = new LogLevelBufferLogger(LOG_BUFFER_LENGTH); - delegator.addLogger(buffer); - - // Check whether to log to stdout/stderr - PrintStreamLogger printer = new PrintStreamLogger(); - boolean logout = setLogOutput(printer, System.out, System.getProperty(LOG_STDOUT_PROPERTY), null); - boolean logerr = setLogOutput(printer, System.err, System.getProperty(LOG_STDERR_PROPERTY), LogLevel.ERROR); - if (logout || logerr) { - delegator.addLogger(printer); - } - - // Set the loggers - Application.setLogger(delegator); - Application.setLogBuffer(buffer); - - // Initialize the log for this class - log = Application.getLogger(); - log.info("Logging subsystem initialized"); - String str = "Console logging output:"; - for (LogLevel l : LogLevel.values()) { - PrintStream ps = printer.getOutput(l); - str += " " + l.name() + ":"; - if (ps == System.err) { - str += "stderr"; - } else if (ps == System.out) { - str += "stdout"; - } else { - str += "none"; - } - } - str += " (" + LOG_STDOUT_PROPERTY + "=" + System.getProperty(LOG_STDOUT_PROPERTY) + - " " + LOG_STDERR_PROPERTY + "=" + System.getProperty(LOG_STDERR_PROPERTY) + ")"; - log.info(str); - } - - private static boolean setLogOutput(PrintStreamLogger logger, PrintStream stream, String level, LogLevel defaultLevel) { - LogLevel minLevel = LogLevel.fromString(level, defaultLevel); - if (minLevel == null) { - return false; - } - - for (LogLevel l : LogLevel.values()) { - if (l.atLeast(minLevel)) { - logger.setOutput(l, stream); - } - } - return true; - } - - - - - /** - * Initializes the localization system. - */ - private static void initializeL10n() { - - // Check for locale propery - String langcode = System.getProperty("openrocket.locale"); - - if (langcode != null) { - - Locale l = L10N.toLocale(langcode); - log.info("Setting custom locale " + l); - Locale.setDefault(l); - - } else { - - // Check user-configured locale - Locale l = getUserLocale(); - if (l != null) { - log.info("Setting user-selected locale " + l); - Locale.setDefault(l); - } else { - log.info("Using default locale " + Locale.getDefault()); - } - - } - - // Setup the translator - Translator t; - t = new ResourceBundleTranslator("l10n.messages"); - if (Locale.getDefault().getLanguage().equals("xx")) { - t = new DebugTranslator(t); - } - - log.info("Set up translation for locale " + Locale.getDefault() + - ", debug.currentFile=" + t.get("debug.currentFile")); - - Application.setBaseTranslator(t); - } - - - - - private static Locale getUserLocale() { - /* - * This method MUST NOT use the Prefs class, since is causes a multitude - * of classes to be initialized. Therefore this duplicates the functionality - * of the Prefs class locally. - */ - - if (System.getProperty("openrocket.debug.prefs") != null) { - return null; - } - - return L10N.toLocale(Preferences.userRoot().node("OpenRocket").get("locale", null)); - } - - -} diff --git a/core/src/net/sf/openrocket/startup/Startup2.java b/core/src/net/sf/openrocket/startup/Startup2.java deleted file mode 100644 index 6b7b49cd..00000000 --- a/core/src/net/sf/openrocket/startup/Startup2.java +++ /dev/null @@ -1,243 +0,0 @@ -package net.sf.openrocket.startup; - -import java.awt.GraphicsEnvironment; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.ToolTipManager; - -import net.sf.openrocket.arch.SystemInfo; -import net.sf.openrocket.arch.SystemInfo.Platform; -import net.sf.openrocket.communication.UpdateInfo; -import net.sf.openrocket.communication.UpdateInfoRetriever; -import net.sf.openrocket.database.ComponentPresetDatabase; -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.gui.dialogs.UpdateInfoDialog; -import net.sf.openrocket.gui.main.BasicFrame; -import net.sf.openrocket.gui.main.Splash; -import net.sf.openrocket.gui.main.SwingExceptionHandler; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.util.BuildProperties; - -/** - * The second class in the OpenRocket startup sequence. This class can assume the - * Application class to be properly set up, and can use any classes safely. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Startup2 { - private static final LogHelper log = Application.getLogger(); - - - private static final String THRUSTCURVE_DIRECTORY = "datafiles/thrustcurves/"; - - /** - * Run when starting up OpenRocket after Application has been set up. - * - * @param args command line arguments - */ - static void runMain(final String[] args) throws Exception { - - log.info("Starting up OpenRocket version " + BuildProperties.getVersion()); - - // Check that we're not running headless - log.info("Checking for graphics head"); - checkHead(); - - // Check that we're running a good version of a JRE - log.info("Checking JRE compatibility"); - VersionHelper.checkVersion(); - VersionHelper.checkOpenJDK(); - - // If running on a MAC set up OSX UI Elements. - if ( SystemInfo.getPlatform() == Platform.MAC_OS ){ - OSXStartup.setupOSX(); - } - - // Run the actual startup method in the EDT since it can use progress dialogs etc. - log.info("Moving startup to EDT"); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - runInEDT(args); - } - }); - - log.info("Startup complete"); - } - - - /** - * Run in the EDT when starting up OpenRocket. - * - * @param args command line arguments - */ - private static void runInEDT(String[] args) { - - // Initialize the splash screen with version info - log.info("Initializing the splash screen"); - Splash.init(); - - // Must be done after localization is initialized - ComponentPresetDatabase componentPresetDao = new ComponentPresetDatabase(true) { - - @Override - protected void load() { - ConcurrentComponentPresetDatabaseLoader presetLoader = new ConcurrentComponentPresetDatabaseLoader( this ); - presetLoader.load(); - try { - presetLoader.await(); - } catch ( InterruptedException iex) { - - } - } - - }; - Application.setComponentPresetDao( componentPresetDao ); - - componentPresetDao.startLoading(); - - // Setup the uncaught exception handler - log.info("Registering exception handler"); - SwingExceptionHandler exceptionHandler = new SwingExceptionHandler(); - Application.setExceptionHandler(exceptionHandler); - exceptionHandler.registerExceptionHandler(); - - // Start update info fetching - final UpdateInfoRetriever updateInfo; - if ( Application.getPreferences().getCheckUpdates()) { - log.info("Starting update check"); - updateInfo = new UpdateInfoRetriever(); - updateInfo.start(); - } else { - log.info("Update check disabled"); - updateInfo = null; - } - - // Set the best available look-and-feel - log.info("Setting best LAF"); - GUIUtil.setBestLAF(); - - // Set tooltip delay time. Tooltips are used in MotorChooserDialog extensively. - ToolTipManager.sharedInstance().setDismissDelay(30000); - - // Load defaults - ((SwingPreferences) Application.getPreferences()).loadDefaultUnits(); - - // Load motors etc. - log.info("Loading databases"); - - loadMotor(); - - Databases.fakeMethod(); - - - // Starting action (load files or open new document) - log.info("Opening main application window"); - if (!handleCommandLine(args)) { - BasicFrame.newAction(); - } - - // Check whether update info has been fetched or whether it needs more time - log.info("Checking update status"); - checkUpdateStatus(updateInfo); - - } - - /** - * this method is useful for the python bindings. - */ - public static void loadMotor() { - ConcurrentLoadingThrustCurveMotorSetDatabase motorLoader = new ConcurrentLoadingThrustCurveMotorSetDatabase(THRUSTCURVE_DIRECTORY); - motorLoader.startLoading(); - Application.setMotorSetDatabase(motorLoader); - } - - /** - * Check that the JRE is not running headless. - */ - private static void checkHead() { - - if (GraphicsEnvironment.isHeadless()) { - log.error("Application is headless."); - System.err.println(); - System.err.println("OpenRocket cannot currently be run without the graphical " + - "user interface."); - System.err.println(); - System.exit(1); - } - - } - - - private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) { - if (updateInfo == null) - return; - - int delay = 1000; - if (!updateInfo.isRunning()) - delay = 100; - - final Timer timer = new Timer(delay, null); - - ActionListener listener = new ActionListener() { - private int count = 5; - - @Override - public void actionPerformed(ActionEvent e) { - if (!updateInfo.isRunning()) { - timer.stop(); - - String current = BuildProperties.getVersion(); - String last = Application.getPreferences().getString(Preferences.LAST_UPDATE, ""); - - UpdateInfo info = updateInfo.getUpdateInfo(); - if (info != null && info.getLatestVersion() != null && - !current.equals(info.getLatestVersion()) && - !last.equals(info.getLatestVersion())) { - - UpdateInfoDialog infoDialog = new UpdateInfoDialog(info); - infoDialog.setVisible(true); - if (infoDialog.isReminderSelected()) { - Application.getPreferences().putString(Preferences.LAST_UPDATE, ""); - } else { - Application.getPreferences().putString(Preferences.LAST_UPDATE, info.getLatestVersion()); - } - } - } - count--; - if (count <= 0) - timer.stop(); - } - }; - timer.addActionListener(listener); - timer.start(); - } - - /** - * Handles arguments passed from the command line. This may be used either - * when starting the first instance of OpenRocket or later when OpenRocket is - * executed again while running. - * - * @param args the command-line arguments. - * @return whether a new frame was opened or similar user desired action was - * performed as a result. - */ - private static boolean handleCommandLine(String[] args) { - - // Check command-line for files - boolean opened = false; - for (String file : args) { - if (BasicFrame.open(new File(file), null)) { - opened = true; - } - } - return opened; - } - -} diff --git a/core/src/net/sf/openrocket/startup/VersionHelper.java b/core/src/net/sf/openrocket/startup/VersionHelper.java deleted file mode 100644 index 0b3d9182..00000000 --- a/core/src/net/sf/openrocket/startup/VersionHelper.java +++ /dev/null @@ -1,129 +0,0 @@ -package net.sf.openrocket.startup; - -import java.awt.GraphicsEnvironment; -import java.util.Locale; - -import javax.swing.JOptionPane; - -import net.sf.openrocket.logging.LogHelper; - -public class VersionHelper { - - private static final LogHelper log = Application.getLogger(); - - private static final int REQUIRED_MAJOR_VERSION = 1; - private static final int REQUIRED_MINOR_VERSION = 6; - - // OpenJDK 1.6.0_0-b16 is known to work, 1.6.0_0-b12 does not - private static final String BAD_OPENJDK_VERSION = "^1.6.0_0-b([0-9]|1[1-5])$"; - - - /** - * Check that the JRE version is high enough. - */ - static void checkVersion() { - - String[] version = System.getProperty("java.specification.version", "").split("\\."); - - String jreName = System.getProperty("java.vm.name", "(unknown)"); - String jreVersion = System.getProperty("java.runtime.version", "(unknown)"); - String jreVendor = System.getProperty("java.vendor", "(unknown)"); - - log.info("Running JRE " + jreName + " version " + jreVersion + " by " + jreVendor); - - int major, minor; - - try { - major = Integer.parseInt(version[0]); - minor = Integer.parseInt(version[1]); - - if (major < REQUIRED_MAJOR_VERSION || - (major == REQUIRED_MAJOR_VERSION && minor < REQUIRED_MINOR_VERSION)) { - error(new String[] { "Java SE version 6 is required to run OpenRocket.", - "You are currently running " + jreName + " version " + - jreVersion + " by " + jreVendor }); - } - - } catch (RuntimeException e) { - - confirm(new String[] { "The Java version in use could not be detected.", - "OpenRocket requires at least Java SE 6.", - "Continue anyway?" }); - - } - - } - - /** - * Check whether OpenJDK is being used, and if it is warn the user about - * problems and confirm whether to continue. - */ - static void checkOpenJDK() { - - if (System.getProperty("java.runtime.name", "").toLowerCase(Locale.ENGLISH).indexOf("icedtea") >= 0 || - System.getProperty("java.vm.name", "").toLowerCase(Locale.ENGLISH).indexOf("openjdk") >= 0) { - - String jreName = System.getProperty("java.vm.name", "(unknown)"); - String jreVersion = System.getProperty("java.runtime.version", "(unknown)"); - String jreVendor = System.getProperty("java.vendor", "(unknown)"); - - if (jreVersion.matches(BAD_OPENJDK_VERSION)) { - - confirm(new String[] { "Old versions of OpenJDK are known to have problems " + - "running OpenRocket.", - " ", - "You are currently running " + jreName + " version " + - jreVersion + " by " + jreVendor, - "Do you want to continue?" }); - } - } - } - - - - /////////// Helper methods ////////// - - /** - * Presents an error message to the user and exits the application. - * - * @param message an array of messages to present. - */ - private static void error(String[] message) { - - System.err.println(); - System.err.println("Error starting OpenRocket:"); - System.err.println(); - for (int i = 0; i < message.length; i++) { - System.err.println(message[i]); - } - System.err.println(); - - - if (!GraphicsEnvironment.isHeadless()) { - - JOptionPane.showMessageDialog(null, message, "Error starting OpenRocket", - JOptionPane.ERROR_MESSAGE); - - } - - System.exit(1); - } - - - /** - * Presents the user with a message dialog and asks whether to continue. - * If the user does not select "Yes" the the application exits. - * - * @param message the message Strings to show. - */ - private static void confirm(String[] message) { - - if (!GraphicsEnvironment.isHeadless()) { - - if (JOptionPane.showConfirmDialog(null, message, "Error starting OpenRocket", - JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { - System.exit(1); - } - } - } -} diff --git a/core/src/net/sf/openrocket/unit/CaliberUnit.java b/core/src/net/sf/openrocket/unit/CaliberUnit.java deleted file mode 100644 index cc93cb51..00000000 --- a/core/src/net/sf/openrocket/unit/CaliberUnit.java +++ /dev/null @@ -1,133 +0,0 @@ -package net.sf.openrocket.unit; - -import java.util.Iterator; - -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.SymmetricComponent; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; - - -public class CaliberUnit extends GeneralUnit { - - public static final double DEFAULT_CALIBER = 0.01; - - private final Configuration configuration; - private final Rocket rocket; - - private int rocketModId = -1; - private int configurationModId = -1; - - private double caliber = -1; - - - - - public CaliberUnit(Configuration configuration) { - super(1.0, "cal"); - this.configuration = configuration; - - if (configuration == null) { - this.rocket = null; - } else { - this.rocket = configuration.getRocket(); - } - } - - public CaliberUnit(Rocket rocket) { - super(1.0, "cal"); - this.configuration = null; - this.rocket = rocket; - } - - public CaliberUnit(double reference) { - super(1.0, "cal"); - this.configuration = null; - this.rocket = null; - this.caliber = reference; - - if (reference <= 0) { - throw new IllegalArgumentException("Illegal reference = " + reference); - } - } - - - @Override - public double fromUnit(double value) { - checkCaliber(); - - return value * caliber; - } - - @Override - public double toUnit(double value) { - checkCaliber(); - - return value / caliber; - } - - - - private void checkCaliber() { - if (configuration != null && configuration.getModID() != configurationModId) { - caliber = -1; - configurationModId = configuration.getModID(); - } - if (rocket != null && rocket.getModID() != rocketModId) { - caliber = -1; - rocketModId = rocket.getModID(); - } - if (caliber < 0) { - if (configuration != null) { - caliber = calculateCaliber(configuration); - } else if (rocket != null) { - caliber = calculateCaliber(rocket); - } else { - throw new BugException("Both rocket and configuration are null"); - } - } - } - - - /** - * Calculate the caliber of a rocket configuration. - * - * @param config the rocket configuration - * @return the caliber of the rocket, or the default caliber. - */ - public static double calculateCaliber(Configuration config) { - return calculateCaliber(config.iterator()); - } - - /** - * Calculate the caliber of a rocket. - * - * @param rocket the rocket - * @return the caliber of the rocket, or the default caliber. - */ - public static double calculateCaliber(Rocket rocket) { - return calculateCaliber(rocket.iterator()); - } - - - - private static double calculateCaliber(Iterator<RocketComponent> iterator) { - double cal = 0; - - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - if (c instanceof SymmetricComponent) { - double r1 = ((SymmetricComponent) c).getForeRadius() * 2; - double r2 = ((SymmetricComponent) c).getAftRadius() * 2; - cal = MathUtil.max(cal, r1, r2); - } - } - - if (cal < 0.0001) - cal = DEFAULT_CALIBER; - - return cal; - } -} diff --git a/core/src/net/sf/openrocket/unit/DegreeUnit.java b/core/src/net/sf/openrocket/unit/DegreeUnit.java deleted file mode 100644 index 240e0b84..00000000 --- a/core/src/net/sf/openrocket/unit/DegreeUnit.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.unit; - -import java.text.DecimalFormat; - -import net.sf.openrocket.util.Chars; - -public class DegreeUnit extends GeneralUnit { - - public DegreeUnit() { - super(Math.PI/180.0, ""+Chars.DEGREE); - } - - @Override - public boolean hasSpace() { - return false; - } - - @Override - public double round(double v) { - return Math.rint(v); - } - - private final DecimalFormat decFormat = new DecimalFormat("0.#"); - @Override - public String toString(double value) { - double val = toUnit(value); - return decFormat.format(val); - } -} diff --git a/core/src/net/sf/openrocket/unit/FixedPrecisionUnit.java b/core/src/net/sf/openrocket/unit/FixedPrecisionUnit.java deleted file mode 100644 index c175d4ef..00000000 --- a/core/src/net/sf/openrocket/unit/FixedPrecisionUnit.java +++ /dev/null @@ -1,137 +0,0 @@ -package net.sf.openrocket.unit; - -import java.util.ArrayList; - -public class FixedPrecisionUnit extends Unit { - - private final double precision; - private final String formatString; - - public FixedPrecisionUnit(String unit, double precision) { - this(unit, precision, 1.0); - } - - public FixedPrecisionUnit(String unit, double precision, double multiplier) { - super(multiplier, unit); - - this.precision = precision; - - int decimals = 0; - double p = precision; - while ((p - Math.floor(p)) > 0.0000001) { - p *= 10; - decimals++; - } - formatString = "%." + decimals + "f"; - } - - - @Override - public double getNextValue(double value) { - return round(value + precision); - } - - @Override - public double getPreviousValue(double value) { - return round(value - precision); - } - - - @Override - public double round(double value) { - return Math.rint(value/precision)*precision; - } - - - - - @Override - public String toString(double value) { - return String.format(formatString, this.toUnit(value)); - } - - - - // TODO: LOW: This is copied from GeneralUnit, perhaps combine - @Override - public Tick[] getTicks(double start, double end, double minor, double major) { - // Convert values - start = toUnit(start); - end = toUnit(end); - minor = toUnit(minor); - major = toUnit(major); - - if (minor <= 0 || major <= 0 || major < minor) { - throw new IllegalArgumentException("getTicks called with minor="+minor+" major="+major); - } - - ArrayList<Tick> ticks = new ArrayList<Tick>(); - - int mod2,mod3,mod4; // Moduli for minor-notable, major-nonnotable, major-notable - double minstep; - - // Find the smallest possible step size - double one=1; - while (one > minor) - one /= 10; - while (one < minor) - one *= 10; - // one is the smallest round-ten that is larger than minor - if (one/2 >= minor) { - // smallest step is round-five - minstep = one/2; - mod2 = 2; // Changed later if clashes with major ticks - } else { - minstep = one; - mod2 = 10; // Changed later if clashes with major ticks - } - - // Find step size for major ticks - one = 1; - while (one > major) - one /= 10; - while (one < major) - one *= 10; - if (one/2 >= major) { - // major step is round-five, major-notable is next round-ten - double majorstep = one/2; - mod3 = (int)Math.round(majorstep/minstep); - mod4 = mod3*2; - } else { - // major step is round-ten, major-notable is next round-ten - mod3 = (int)Math.round(one/minstep); - mod4 = mod3*10; - } - // Check for clashes between minor-notable and major-nonnotable - if (mod3 == mod2) { - if (mod2==2) - mod2 = 1; // Every minor tick is notable - else - mod2 = 5; // Every fifth minor tick is notable - } - - - // Calculate starting position - int pos = (int)Math.ceil(start/minstep); -// System.out.println("mod2="+mod2+" mod3="+mod3+" mod4="+mod4); - while (pos*minstep <= end) { - double unitValue = pos*minstep; - double value = fromUnit(unitValue); - - if (pos%mod4 == 0) - ticks.add(new Tick(value,unitValue,true,true)); - else if (pos%mod3 == 0) - ticks.add(new Tick(value,unitValue,true,false)); - else if (pos%mod2 == 0) - ticks.add(new Tick(value,unitValue,false,true)); - else - ticks.add(new Tick(value,unitValue,false,false)); - - pos++; - } - - return ticks.toArray(new Tick[0]); - } - - -} diff --git a/core/src/net/sf/openrocket/unit/FixedUnitGroup.java b/core/src/net/sf/openrocket/unit/FixedUnitGroup.java deleted file mode 100644 index 8cb6fde4..00000000 --- a/core/src/net/sf/openrocket/unit/FixedUnitGroup.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.unit; - -/* - * This class provides a 'dumb' version of UnitGroup - * It allows any arbitrary unit to be created. It doesn't store any value and can't be converted into anything else. - * This is useful for custom expression units. - * - * @author Richard Graham - */ - -public class FixedUnitGroup extends UnitGroup { - - String unitString; - - public FixedUnitGroup( String unitString ){ - this.unitString = unitString; - } - - public int getUnitCount(){ - return 1; - } - - public Unit getDefaultUnit(){ - return new GeneralUnit(1, unitString); - } - - public Unit getSIUnit(){ - return new GeneralUnit(1, unitString); - } - - public boolean contains(Unit u){ - return true; - } - -} diff --git a/core/src/net/sf/openrocket/unit/FractionalUnit.java b/core/src/net/sf/openrocket/unit/FractionalUnit.java deleted file mode 100644 index 740e4776..00000000 --- a/core/src/net/sf/openrocket/unit/FractionalUnit.java +++ /dev/null @@ -1,245 +0,0 @@ -package net.sf.openrocket.unit; - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.ArrayList; - -import net.sf.openrocket.util.Chars; - -public class FractionalUnit extends Unit { - - private final static char FRACTION = Chars.FRACTION; - - private final static String[] NUMERATOR = { - "\u2070", // 0 - "\u00B9", // 1 - "\u00B2", // 2 - "\u00B3", // 3 - "\u2074", // 4 - "\u2075", // 5 - "\u2076", // 6 - "\u2077", // 7 - "\u2078", // 8 - "\u2079" // 9 - }; - - private final static String[] DENOMINATOR = { - "\u2080", // 0 - "\u2081", // 1 - "\u2082", // 2 - "\u2083", // 3 - "\u2084", // 4 - "\u2085", // 5 - "\u2086", // 6 - "\u2087", // 7 - "\u2088", // 8 - "\u2089" // 9 - }; - - // This is the base of the fractions. ie, 16d for 1/16ths. - private final int fractionBase; - // This is 1d/fractionBase; - private final double fractionValue; - - // This is the value used when incrementing/decrementing. - private final double incrementValue; - - // If the actual value differs from the decimal representation by more than this, - // we display as decimals. - private final double epsilon; - - private final String unitLabel; - - public FractionalUnit(double multiplier, String unit, String unitLabel, int fractionBase, double incrementValue) { - this(multiplier, unit, unitLabel, fractionBase, incrementValue, 0.1d / fractionBase); - } - - public FractionalUnit(double multiplier, String unit, String unitLabel, int fractionBase, double incrementValue, double epsilon) { - super(multiplier, unit); - this.unitLabel = unitLabel; - this.fractionBase = fractionBase; - this.fractionValue = 1.0d / fractionBase; - this.incrementValue = incrementValue; - this.epsilon = epsilon; - } - - @Override - public double round(double value) { - return roundTo(value, fractionValue); - } - - private double roundTo(double value, double fraction) { - double remainder = Math.IEEEremainder(value, fraction); - return value - remainder; - } - - @Override - public double getNextValue(double value) { - double rounded = roundTo(value, incrementValue); - if (rounded <= value + epsilon) { - rounded += incrementValue; - } - return rounded; - } - - @Override - public double getPreviousValue(double value) { - double rounded = roundTo(value, incrementValue); - if (rounded >= value - epsilon) { - rounded -= incrementValue; - } - return rounded; - } - - @Override - public Tick[] getTicks(double start, double end, double minor, double major) { - // Convert values - start = toUnit(start); - end = toUnit(end); - minor = toUnit(minor); - major = toUnit(major); - - if (minor <= 0 || major <= 0 || major < minor) { - throw new IllegalArgumentException("getTicks called with minor=" + minor + " major=" + major); - } - - ArrayList<Tick> ticks = new ArrayList<Tick>(); - - int mod2, mod3, mod4; // Moduli for minor-notable, major-nonnotable, major-notable - double minstep; - - // Find the smallest possible step size - double one = 1; - while (one > minor) - one /= 2; - while (one < minor) - one *= 2; - minstep = one; - mod2 = 16; - - // Find step size for major ticks - one = 1; - while (one > major) - one /= 10; - while (one < major) - one *= 10; - if (one / 2 >= major) { - // major step is round-five, major-notable is next round-ten - double majorstep = one / 2; - mod3 = (int) Math.round(majorstep / minstep); - mod4 = mod3 * 2; - } else { - // major step is round-ten, major-notable is next round-ten - mod3 = (int) Math.round(one / minstep); - mod4 = mod3 * 10; - } - // Check for clashes between minor-notable and major-nonnotable - if (mod3 == mod2) { - if (mod2 == 2) - mod2 = 1; // Every minor tick is notable - else - mod2 = 5; // Every fifth minor tick is notable - } - - - // Calculate starting position - int pos = (int) Math.ceil(start / minstep); - // System.out.println("mod2="+mod2+" mod3="+mod3+" mod4="+mod4); - while (pos * minstep <= end) { - double unitValue = pos * minstep; - double value = fromUnit(unitValue); - - if (pos % mod4 == 0) - ticks.add(new Tick(value, unitValue, true, true)); - else if (pos % mod3 == 0) - ticks.add(new Tick(value, unitValue, true, false)); - else if (pos % mod2 == 0) - ticks.add(new Tick(value, unitValue, false, true)); - else - ticks.add(new Tick(value, unitValue, false, false)); - - pos++; - } - - return ticks.toArray(new Tick[0]); - } - - - @Override - public String toString(double value) { - - double correctVal = toUnit(value); - double val = round(correctVal); - - - if (Math.abs(val - correctVal) > epsilon) { - NumberFormat decFormat = new DecimalFormat("#.###"); - return decFormat.format(correctVal); - } - - NumberFormat intFormat = new DecimalFormat("#"); - double sign = Math.signum(val); - - double posValue = sign * val; - - double intPart = Math.floor(posValue); - - double frac = Math.rint((posValue - intPart) / fractionValue); - double fracBase = fractionBase; - - // Reduce fraction. - while (frac > 0 && fracBase > 2 && frac % 2 == 0) { - frac /= 2.0; - fracBase /= 2.0; - } - - posValue *= sign; - - if (frac == 0.0) { - return intFormat.format(posValue); - } else if (intPart == 0.0) { - return (sign < 0 ? "-" : "") + numeratorString(Double.valueOf(frac).intValue()) - + FRACTION + denominatorString(Double.valueOf(fracBase).intValue()); - } else { - return intFormat.format(sign * intPart) + " " + numeratorString(Double.valueOf(frac).intValue()) - + FRACTION + denominatorString(Double.valueOf(fracBase).intValue()); - } - - } - - private String numeratorString(int value) { - - String rep = ""; - if (value == 0) { - return "0"; - } - while (value > 0) { - rep = NUMERATOR[value % 10] + rep; - value = value / 10; - } - return rep; - } - - private String denominatorString(int value) { - String rep = ""; - if (value == 0) { - return "0"; - } - while (value > 0) { - rep = DENOMINATOR[value % 10] + rep; - value = value / 10; - } - return rep; - } - - @Override - public String toStringUnit(double value) { - if (Double.isNaN(value)) - return "N/A"; - - String s = toString(value); - s += " " + unitLabel; - return s; - } - -} diff --git a/core/src/net/sf/openrocket/unit/FrequencyUnit.java b/core/src/net/sf/openrocket/unit/FrequencyUnit.java deleted file mode 100644 index 7b5d15cf..00000000 --- a/core/src/net/sf/openrocket/unit/FrequencyUnit.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.sf.openrocket.unit; - -public class FrequencyUnit extends GeneralUnit { - - - public FrequencyUnit(double multiplier, String unit) { - super(multiplier, unit); - } - - - - @Override - public double toUnit(double value) { - double hz = 1/value; - return hz / multiplier; - } - - - @Override - public double fromUnit(double value) { - double hz = value * multiplier; - return 1/hz; - } - -} diff --git a/core/src/net/sf/openrocket/unit/GeneralUnit.java b/core/src/net/sf/openrocket/unit/GeneralUnit.java deleted file mode 100644 index d604fe6e..00000000 --- a/core/src/net/sf/openrocket/unit/GeneralUnit.java +++ /dev/null @@ -1,228 +0,0 @@ -package net.sf.openrocket.unit; - -import java.util.ArrayList; - -public class GeneralUnit extends Unit { - - private final int significantNumbers; - private final int decimalRounding; - - // Values smaller that this are rounded using decimal rounding - // [pre-calculated as 10^(significantNumbers-1)] - private final double decimalLimit; - - // Pre-calculated as 10^significantNumbers - private final double significantNumbersLimit; - - - public GeneralUnit(double multiplier, String unit) { - this(multiplier, unit, 2, 10); - } - - public GeneralUnit(double multiplier, String unit, int significantNumbers) { - this(multiplier, unit, significantNumbers, 10); - } - - public GeneralUnit(double multiplier, String unit, int significantNumbers, int decimalRounding) { - super(multiplier, unit); - assert(significantNumbers>0); - assert(decimalRounding>0); - - this.significantNumbers = significantNumbers; - this.decimalRounding = decimalRounding; - - double d=1; - double e=10; - for (int i=1; i<significantNumbers; i++) { - d *= 10.0; - e *= 10.0; - } - decimalLimit = d; - significantNumbersLimit = e; - } - - @Override - public double round(double value) { - if (value < decimalLimit) { - // Round to closest 1/decimalRounding - return Math.rint(value*decimalRounding)/decimalRounding; - } else { - // Round to given amount of significant numbers - double m = 1; - while (value >= significantNumbersLimit) { - m *= 10.0; - value /= 10.0; - } - return Math.rint(value)*m; - } - } - - - - - // TODO: LOW: untested - // start, end and scale in this units -// @Override - public ArrayList<Tick> getTicks(double start, double end, double scale) { - ArrayList<Tick> ticks = new ArrayList<Tick>(); - double delta; - int normal, major; - - // TODO: LOW: more fine-grained (e.g. 0||||5||||10||||15||||20) - if (scale <= 1.0/decimalRounding) { - delta = 1.0/decimalRounding; - normal = 1; - major = decimalRounding; - } else if (scale <= 1.0) { - delta = 1.0/decimalRounding; - normal = decimalRounding; - major = decimalRounding*10; - } else { - double r = scale; - delta = 1; - while (r > 10) { - r /= 10; - delta *= 10; - } - normal = 10; - major = 100; // TODO: LOW: More fine-grained with 5 - } - - double v = Math.ceil(start/delta)*delta; - int n = (int)Math.round(v/delta); - -// while (v <= end) { -// if (n%major == 0) -// ticks.add(new Tick(v,Tick.MAJOR)); -// else if (n%normal == 0) -// ticks.add(new Tick(v,Tick.NORMAL)); -// else -// ticks.add(new Tick(v,Tick.MINOR)); -// v += delta; -// n++; -// } - - return ticks; - } - - @Override - public Tick[] getTicks(double start, double end, double minor, double major) { - // Convert values - start = toUnit(start); - end = toUnit(end); - minor = toUnit(minor); - major = toUnit(major); - - if (minor <= 0 || major <= 0 || major < minor) { - throw new IllegalArgumentException("getTicks called with minor="+minor+" major="+major); - } - - ArrayList<Tick> ticks = new ArrayList<Tick>(); - - int mod2,mod3,mod4; // Moduli for minor-notable, major-nonnotable, major-notable - double minstep; - - // Find the smallest possible step size - double one=1; - while (one > minor) - one /= 10; - while (one < minor) - one *= 10; - // one is the smallest round-ten that is larger than minor - if (one/2 >= minor) { - // smallest step is round-five - minstep = one/2; - mod2 = 2; // Changed later if clashes with major ticks - } else { - minstep = one; - mod2 = 10; // Changed later if clashes with major ticks - } - - // Find step size for major ticks - one = 1; - while (one > major) - one /= 10; - while (one < major) - one *= 10; - if (one/2 >= major) { - // major step is round-five, major-notable is next round-ten - double majorstep = one/2; - mod3 = (int)Math.round(majorstep/minstep); - mod4 = mod3*2; - } else { - // major step is round-ten, major-notable is next round-ten - mod3 = (int)Math.round(one/minstep); - mod4 = mod3*10; - } - // Check for clashes between minor-notable and major-nonnotable - if (mod3 == mod2) { - if (mod2==2) - mod2 = 1; // Every minor tick is notable - else - mod2 = 5; // Every fifth minor tick is notable - } - - - // Calculate starting position - int pos = (int)Math.ceil(start/minstep); -// System.out.println("mod2="+mod2+" mod3="+mod3+" mod4="+mod4); - while (pos*minstep <= end) { - double unitValue = pos*minstep; - double value = fromUnit(unitValue); - - if (pos%mod4 == 0) - ticks.add(new Tick(value,unitValue,true,true)); - else if (pos%mod3 == 0) - ticks.add(new Tick(value,unitValue,true,false)); - else if (pos%mod2 == 0) - ticks.add(new Tick(value,unitValue,false,true)); - else - ticks.add(new Tick(value,unitValue,false,false)); - - pos++; - } - - return ticks.toArray(new Tick[0]); - } - - - @Override - public double getNextValue(double value) { - // TODO: HIGH: Auto-generated method stub - return value+1; - } - - @Override - public double getPreviousValue(double value) { - // TODO: HIGH: Auto-generated method stub - return value-1; - } - - - ///// TESTING: - - private static void printTicks(double start, double end, double minor, double major) { - Tick[] ticks = Unit.NOUNIT2.getTicks(start, end, minor, major); - String str = "Ticks for ("+start+","+end+","+minor+","+major+"):"; - for (int i=0; i<ticks.length; i++) { - str += " "+ticks[i].value; - if (ticks[i].major) { - if (ticks[i].notable) - str += "*"; - else - str += "o"; - } else { - if (ticks[i].notable) - str += "_"; - else - str += " "; - } - } - System.out.println(str); - } - public static void main(String[] arg) { - printTicks(0,100,1,10); - printTicks(4.7,11.0,0.15,0.7); - } - -} diff --git a/core/src/net/sf/openrocket/unit/RadianUnit.java b/core/src/net/sf/openrocket/unit/RadianUnit.java deleted file mode 100644 index 18f1aff6..00000000 --- a/core/src/net/sf/openrocket/unit/RadianUnit.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.unit; - -import java.text.DecimalFormat; - -public class RadianUnit extends GeneralUnit { - - public RadianUnit() { - super(1,"rad"); - } - - @Override - public double round(double v) { - return Math.rint(v*10.0)/10.0; - } - - private final DecimalFormat decFormat = new DecimalFormat("0.0"); - @Override - public String toString(double value) { - double val = toUnit(value); - return decFormat.format(val); - } -} diff --git a/core/src/net/sf/openrocket/unit/TemperatureUnit.java b/core/src/net/sf/openrocket/unit/TemperatureUnit.java deleted file mode 100644 index 23645ceb..00000000 --- a/core/src/net/sf/openrocket/unit/TemperatureUnit.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.sf.openrocket.unit; - -public class TemperatureUnit extends FixedPrecisionUnit { - - protected final double addition; - - public TemperatureUnit(double multiplier, double addition, String unit) { - super(unit, 1, multiplier); - - this.addition = addition; - } - - @Override - public boolean hasSpace() { - return false; - } - - @Override - public double toUnit(double value) { - return value/multiplier - addition; - } - - @Override - public double fromUnit(double value) { - return (value + addition)*multiplier; - } -} diff --git a/core/src/net/sf/openrocket/unit/Tick.java b/core/src/net/sf/openrocket/unit/Tick.java deleted file mode 100644 index 4448aac1..00000000 --- a/core/src/net/sf/openrocket/unit/Tick.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.unit; - -public final class Tick { - public final double value; - public final double unitValue; - public final boolean major; - public final boolean notable; - - public Tick(double value, double unitValue, boolean major, boolean notable) { - this.value = value; - this.unitValue = unitValue; - this.major = major; - this.notable = notable; - } - - @Override - public String toString() { - String s = "Tick[value="+value; - if (major) - s += ",major"; - else - s += ",minor"; - if (notable) - s += ",notable"; - s+= "]"; - return s; - } -} diff --git a/core/src/net/sf/openrocket/unit/Unit.java b/core/src/net/sf/openrocket/unit/Unit.java deleted file mode 100644 index dda76944..00000000 --- a/core/src/net/sf/openrocket/unit/Unit.java +++ /dev/null @@ -1,204 +0,0 @@ -package net.sf.openrocket.unit; - -import java.text.DecimalFormat; - -import net.sf.openrocket.util.Chars; - -public abstract class Unit { - - /** No unit with 2 digit precision */ - public static final Unit NOUNIT2 = new GeneralUnit(1, "" + Chars.ZWSP, 2); - - protected final double multiplier; // meters = units * multiplier - protected final String unit; - - /** - * Creates a new Unit with a given multiplier and unit name. - * - * Multiplier e.g. 1 in = 0.0254 meter - * - * @param multiplier The multiplier to use on the value, 1 this unit == multiplier SI units - * @param unit The unit's short form. - */ - public Unit(double multiplier, String unit) { - if (multiplier == 0) - throw new IllegalArgumentException("Unit has multiplier=0"); - this.multiplier = multiplier; - this.unit = unit; - } - - /** - * Converts from SI units to this unit. The default implementation simply divides by the - * multiplier. - * - * @param value Value in SI unit - * @return Value in these units - */ - public double toUnit(double value) { - return value / multiplier; - } - - /** - * Convert from this type of units to SI units. The default implementation simply - * multiplies by the multiplier. - * - * @param value Value in these units - * @return Value in SI units - */ - public double fromUnit(double value) { - return value * multiplier; - } - - - /** - * Return the unit name. - * - * @return the unit. - */ - public String getUnit() { - return unit; - } - - /** - * Whether the value and unit should be separated by a whitespace. This method - * returns true as most units have a space between the value and unit, but may be - * overridden. - * - * @return true if the value and unit should be separated - */ - public boolean hasSpace() { - return true; - } - - @Override - public String toString() { - return unit; - } - - // TODO: Should this use grouping separator ("#,##0.##")? - - private static final DecimalFormat intFormat = new DecimalFormat("#"); - private static final DecimalFormat decFormat = new DecimalFormat("0.##"); - private static final DecimalFormat smallFormat = new DecimalFormat("0.###"); - private static final DecimalFormat expFormat = new DecimalFormat("0.00E0"); - - /** - * Format the given value (in SI units) to a string representation of the value in this - * units. An suitable amount of decimals for the unit are used in the representation. - * The unit is not appended to the numerical value. - * - * @param value Value in SI units. - * @return A string representation of the number in these units. - */ - public String toString(double value) { - double val = toUnit(value); - - if (Math.abs(val) > 1E6) { - return expFormat.format(val); - } - if (Math.abs(val) >= 100) { - return intFormat.format(val); - } - if (Math.abs(val) <= 0.0005) { - return "0"; - } - if ( Math.abs(val) < 0.095) { - return smallFormat.format(val); - } - - double sign = Math.signum(val); - val = Math.abs(val); - double mul = 1.0; - while (val < 100) { - mul *= 10; - val *= 10; - } - val = Math.rint(val) / mul * sign; - return decFormat.format(val); - } - - - /** - * Return a string with the specified value and unit. The value is converted into - * this unit. If <code>value</code> is NaN, returns "N/A" (not applicable). - * - * @param value the value to print in SI units. - * @return the value and unit, or "N/A". - */ - public String toStringUnit(double value) { - if (Double.isNaN(value)) - return "N/A"; - - String s = toString(value); - if (hasSpace()) - s += " "; - s += unit; - return s; - } - - - - /** - * Creates a new Value object with the specified value and this unit. - * - * @param value the value to set. - * @return a new Value object. - */ - public Value toValue(double value) { - return new Value(value, this); - } - - - - /** - * Round the value (in the current units) to a precision suitable for rough valuing - * (approximately 2 significant numbers). - * - * @param value Value in current units - * @return Rounded value. - */ - public abstract double round(double value); - - /** - * Return the next rounded value after the given value. - * @param value Value in these units. - * @return The next suitable rounded value. - */ - public abstract double getNextValue(double value); - - /** - * Return the previous rounded value before the given value. - * @param value Value in these units. - * @return The previous suitable rounded value. - */ - public abstract double getPreviousValue(double value); - - //public abstract ArrayList<Tick> getTicks(double start, double end, double scale); - - /** - * Return ticks in the range start - end (in current units). minor is the minimum - * distance between minor, non-notable ticks and major the minimum distance between - * major non-notable ticks. The values are in current units, i.e. no conversion is - * performed. - */ - public abstract Tick[] getTicks(double start, double end, double minor, double major); - - /** - * Compares whether the two units are equal. Equality requires the unit classes, - * multiplier values and units to be equal. - */ - @Override - public boolean equals(Object other) { - if (other == null) - return false; - if (this.getClass() != other.getClass()) - return false; - return ((this.multiplier == ((Unit) other).multiplier) && this.unit.equals(((Unit) other).unit)); - } - - @Override - public int hashCode() { - return this.getClass().hashCode() + this.unit.hashCode(); - } - -} diff --git a/core/src/net/sf/openrocket/unit/UnitGroup.java b/core/src/net/sf/openrocket/unit/UnitGroup.java deleted file mode 100644 index 48ae67a9..00000000 --- a/core/src/net/sf/openrocket/unit/UnitGroup.java +++ /dev/null @@ -1,719 +0,0 @@ -package net.sf.openrocket.unit; - -import static net.sf.openrocket.util.Chars.*; -import static net.sf.openrocket.util.MathUtil.pow2; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.Rocket; - - -/** - * A group of units (eg. length, mass etc.). Contains a list of different units of a same - * quantity. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - -public class UnitGroup { - - public static final UnitGroup UNITS_NONE; - - public static final UnitGroup UNITS_MOTOR_DIMENSIONS; - public static final UnitGroup UNITS_LENGTH; - public static final UnitGroup UNITS_ALL_LENGTHS; - public static final UnitGroup UNITS_DISTANCE; - - public static final UnitGroup UNITS_AREA; - public static final UnitGroup UNITS_STABILITY; - /** - * This unit group contains only the caliber unit that never scales the originating "SI" value. - * It can be used in cases where the originating value is already in calibers to obtains the correct unit. - */ - public static final UnitGroup UNITS_STABILITY_CALIBERS; - public static final UnitGroup UNITS_VELOCITY; - public static final UnitGroup UNITS_WINDSPEED; - public static final UnitGroup UNITS_ACCELERATION; - public static final UnitGroup UNITS_MASS; - public static final UnitGroup UNITS_INERTIA; - public static final UnitGroup UNITS_ANGLE; - public static final UnitGroup UNITS_DENSITY_BULK; - public static final UnitGroup UNITS_DENSITY_SURFACE; - public static final UnitGroup UNITS_DENSITY_LINE; - public static final UnitGroup UNITS_FORCE; - public static final UnitGroup UNITS_IMPULSE; - - /** Time in the order of less than a second (time step etc). */ - public static final UnitGroup UNITS_TIME_STEP; - - /** Time in the order of seconds (motor delay etc). */ - public static final UnitGroup UNITS_SHORT_TIME; - - /** Time in the order of the flight time of a rocket. */ - public static final UnitGroup UNITS_FLIGHT_TIME; - public static final UnitGroup UNITS_ROLL; - public static final UnitGroup UNITS_TEMPERATURE; - public static final UnitGroup UNITS_PRESSURE; - public static final UnitGroup UNITS_RELATIVE; - public static final UnitGroup UNITS_ROUGHNESS; - - public static final UnitGroup UNITS_COEFFICIENT; - public static final UnitGroup UNITS_FREQUENCY; - - public static final UnitGroup UNITS_ENERGY; - public static final UnitGroup UNITS_POWER; - public static final UnitGroup UNITS_MOMENTUM; - public static final UnitGroup UNITS_VOLTAGE; - public static final UnitGroup UNITS_CURRENT; - - - public static final Map<String, UnitGroup> UNITS; // keys such as "LENGTH", "VELOCITY" - public static final Map<String, UnitGroup> SIUNITS; // keys such a "m", "m/s" - - - /* - * Note: Units may not use HTML tags. - * - * The scaling value "X" is obtained by "one of this unit is X of SI units" - * Type into Google for example: "1 in^2 in m^2" - */ - static { - UNITS_NONE = new UnitGroup(); - UNITS_NONE.addUnit(Unit.NOUNIT2); - - UNITS_ENERGY = new UnitGroup(); - UNITS_ENERGY.addUnit(new GeneralUnit(1, "J")); - UNITS_ENERGY.addUnit(new GeneralUnit(1e-7, "erg")); - UNITS_ENERGY.addUnit(new GeneralUnit(1.055, "BTU")); - UNITS_ENERGY.addUnit(new GeneralUnit(4.184, "cal")); - UNITS_ENERGY.addUnit(new GeneralUnit(1.3558179483314, "ft"+DOT+"lbf")); - UNITS_ENERGY.setDefaultUnit(0); - - UNITS_POWER = new UnitGroup(); - UNITS_POWER.addUnit(new GeneralUnit(1e-3, "mW")); - UNITS_POWER.addUnit(new GeneralUnit(1, "W")); - UNITS_POWER.addUnit(new GeneralUnit(1e3, "kW")); - UNITS_POWER.addUnit(new GeneralUnit(1e-7, "ergs")); - UNITS_POWER.addUnit(new GeneralUnit(745.699872, "hp")); - UNITS_POWER.setDefaultUnit(1); - - UNITS_MOMENTUM = new UnitGroup(); - UNITS_MOMENTUM.addUnit(new GeneralUnit(1, "kg"+DOT+"m/s")); - UNITS_MOMENTUM.setDefaultUnit(0); - - UNITS_VOLTAGE = new UnitGroup(); - UNITS_VOLTAGE.addUnit(new GeneralUnit(1e-3, "mV")); - UNITS_VOLTAGE.addUnit(new GeneralUnit(1, "V")); - UNITS_VOLTAGE.setDefaultUnit(1); - - UNITS_CURRENT = new UnitGroup(); - UNITS_CURRENT.addUnit(new GeneralUnit(1e-3, "mA")); - UNITS_CURRENT.addUnit(new GeneralUnit(1, "A")); - UNITS_CURRENT.setDefaultUnit(1); - - UNITS_LENGTH = new UnitGroup(); - UNITS_LENGTH.addUnit(new GeneralUnit(0.001, "mm")); - UNITS_LENGTH.addUnit(new GeneralUnit(0.01, "cm")); - UNITS_LENGTH.addUnit(new GeneralUnit(1, "m")); - UNITS_LENGTH.addUnit(new GeneralUnit(0.0254, "in")); - UNITS_LENGTH.addUnit(new FractionalUnit(0.0254, "in/64", "in", 64, 1d / 16d, 0.5d / 64d)); - UNITS_LENGTH.addUnit(new GeneralUnit(0.3048, "ft")); - UNITS_LENGTH.setDefaultUnit(1); - - UNITS_MOTOR_DIMENSIONS = new UnitGroup(); - UNITS_MOTOR_DIMENSIONS.addUnit(new GeneralUnit(1, "m")); // just added - UNITS_MOTOR_DIMENSIONS.addUnit(new GeneralUnit(0.001, "mm")); - UNITS_MOTOR_DIMENSIONS.addUnit(new GeneralUnit(0.01, "cm")); - UNITS_MOTOR_DIMENSIONS.addUnit(new GeneralUnit(0.0254, "in")); - UNITS_MOTOR_DIMENSIONS.setDefaultUnit(0); - - UNITS_DISTANCE = new UnitGroup(); - UNITS_DISTANCE.addUnit(new GeneralUnit(1, "m")); - UNITS_DISTANCE.addUnit(new GeneralUnit(1000, "km")); - UNITS_DISTANCE.addUnit(new GeneralUnit(0.3048, "ft")); - UNITS_DISTANCE.addUnit(new GeneralUnit(0.9144, "yd")); - UNITS_DISTANCE.addUnit(new GeneralUnit(1609.344, "mi")); - UNITS_DISTANCE.addUnit(new GeneralUnit(1852, "nmi")); - - UNITS_ALL_LENGTHS = new UnitGroup(); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(0.001, "mm")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(0.01, "cm")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(1, "m")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(1000, "km")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(0.0254, "in")); - UNITS_ALL_LENGTHS.addUnit(new FractionalUnit(0.0254, "in/64", "in", 64, 1d / 16d, 0.5d / 64d)); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(0.3048, "ft")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(0.9144, "yd")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(1609.344, "mi")); - UNITS_ALL_LENGTHS.addUnit(new GeneralUnit(1852, "nmi")); - UNITS_ALL_LENGTHS.setDefaultUnit(2); - - UNITS_AREA = new UnitGroup(); - UNITS_AREA.addUnit(new GeneralUnit(pow2(0.001), "mm" + SQUARED)); - UNITS_AREA.addUnit(new GeneralUnit(pow2(0.01), "cm" + SQUARED)); - UNITS_AREA.addUnit(new GeneralUnit(1, "m" + SQUARED)); - UNITS_AREA.addUnit(new GeneralUnit(pow2(0.0254), "in" + SQUARED)); - UNITS_AREA.addUnit(new GeneralUnit(pow2(0.3048), "ft" + SQUARED)); - UNITS_AREA.setDefaultUnit(1); - - - UNITS_STABILITY = new UnitGroup(); - UNITS_STABILITY.addUnit(new GeneralUnit(1, "m")); - UNITS_STABILITY.addUnit(new GeneralUnit(0.001, "mm")); - UNITS_STABILITY.addUnit(new GeneralUnit(0.01, "cm")); - UNITS_STABILITY.addUnit(new GeneralUnit(0.0254, "in")); - UNITS_STABILITY.addUnit(new CaliberUnit((Rocket) null)); - UNITS_STABILITY.setDefaultUnit(3); - - UNITS_STABILITY_CALIBERS = new UnitGroup(); - UNITS_STABILITY_CALIBERS.addUnit(new GeneralUnit(1, "cal")); - - - UNITS_VELOCITY = new UnitGroup(); - UNITS_VELOCITY.addUnit(new GeneralUnit(1, "m/s")); - UNITS_VELOCITY.addUnit(new GeneralUnit(1 / 3.6, "km/h")); - UNITS_VELOCITY.addUnit(new GeneralUnit(0.3048, "ft/s")); - UNITS_VELOCITY.addUnit(new GeneralUnit(0.44704, "mph")); - - UNITS_WINDSPEED = new UnitGroup(); - UNITS_WINDSPEED.addUnit(new GeneralUnit(1, "m/s")); - UNITS_WINDSPEED.addUnit(new GeneralUnit(1 / 3.6, "km/h")); - UNITS_WINDSPEED.addUnit(new GeneralUnit(0.3048, "ft/s")); - UNITS_WINDSPEED.addUnit(new GeneralUnit(0.44704, "mph")); - - UNITS_ACCELERATION = new UnitGroup(); - UNITS_ACCELERATION.addUnit(new GeneralUnit(1, "m/s" + SQUARED)); - UNITS_ACCELERATION.addUnit(new GeneralUnit(0.3048, "ft/s" + SQUARED)); - UNITS_ACCELERATION.addUnit(new GeneralUnit(9.80665, "G")); - - UNITS_MASS = new UnitGroup(); - UNITS_MASS.addUnit(new GeneralUnit(0.001, "g")); - UNITS_MASS.addUnit(new GeneralUnit(1, "kg")); - UNITS_MASS.addUnit(new GeneralUnit(0.0283495231, "oz")); - UNITS_MASS.addUnit(new GeneralUnit(0.45359237, "lb")); - - UNITS_INERTIA = new UnitGroup(); - UNITS_INERTIA.addUnit(new GeneralUnit(0.0001, "kg" + DOT + "cm" + SQUARED)); - UNITS_INERTIA.addUnit(new GeneralUnit(1, "kg" + DOT + "m" + SQUARED)); - UNITS_INERTIA.addUnit(new GeneralUnit(1.82899783e-5, "oz" + DOT + "in" + SQUARED)); - UNITS_INERTIA.addUnit(new GeneralUnit(0.000292639653, "lb" + DOT + "in" + SQUARED)); - UNITS_INERTIA.addUnit(new GeneralUnit(0.0421401101, "lb" + DOT + "ft" + SQUARED)); - UNITS_INERTIA.addUnit(new GeneralUnit(1.35581795, "lbf" + DOT + "ft" + DOT + "s" + SQUARED)); - UNITS_INERTIA.setDefaultUnit(1); - - UNITS_ANGLE = new UnitGroup(); - UNITS_ANGLE.addUnit(new DegreeUnit()); - UNITS_ANGLE.addUnit(new FixedPrecisionUnit("rad", 0.01)); - UNITS_ANGLE.addUnit(new GeneralUnit(1.0 / 3437.74677078, "arcmin")); - - UNITS_DENSITY_BULK = new UnitGroup(); - UNITS_DENSITY_BULK.addUnit(new GeneralUnit(1000, "g/cm" + CUBED)); - UNITS_DENSITY_BULK.addUnit(new GeneralUnit(1000, "kg/dm" + CUBED)); - UNITS_DENSITY_BULK.addUnit(new GeneralUnit(1, "kg/m" + CUBED)); - UNITS_DENSITY_BULK.addUnit(new GeneralUnit(1729.99404, "oz/in" + CUBED)); - UNITS_DENSITY_BULK.addUnit(new GeneralUnit(16.0184634, "lb/ft" + CUBED)); - - UNITS_DENSITY_SURFACE = new UnitGroup(); - UNITS_DENSITY_SURFACE.addUnit(new GeneralUnit(10, "g/cm" + SQUARED)); - UNITS_DENSITY_SURFACE.addUnit(new GeneralUnit(0.001, "g/m" + SQUARED)); - UNITS_DENSITY_SURFACE.addUnit(new GeneralUnit(1, "kg/m" + SQUARED)); - UNITS_DENSITY_SURFACE.addUnit(new GeneralUnit(43.9418487, "oz/in" + SQUARED)); - UNITS_DENSITY_SURFACE.addUnit(new GeneralUnit(0.305151727, "oz/ft" + SQUARED)); - UNITS_DENSITY_SURFACE.addUnit(new GeneralUnit(4.88242764, "lb/ft" + SQUARED)); - UNITS_DENSITY_SURFACE.setDefaultUnit(1); - - UNITS_DENSITY_LINE = new UnitGroup(); - UNITS_DENSITY_LINE.addUnit(new GeneralUnit(0.001, "g/m")); - UNITS_DENSITY_LINE.addUnit(new GeneralUnit(1, "kg/m")); - UNITS_DENSITY_LINE.addUnit(new GeneralUnit(0.0930102465, "oz/ft")); - - UNITS_FORCE = new UnitGroup(); - UNITS_FORCE.addUnit(new GeneralUnit(1, "N")); - UNITS_FORCE.addUnit(new GeneralUnit(4.44822162, "lbf")); - UNITS_FORCE.addUnit(new GeneralUnit(9.80665, "kgf")); - - UNITS_IMPULSE = new UnitGroup(); - UNITS_IMPULSE.addUnit(new GeneralUnit(1, "Ns")); - UNITS_IMPULSE.addUnit(new GeneralUnit(4.44822162, "lbf" + DOT + "s")); - - UNITS_TIME_STEP = new UnitGroup(); - UNITS_TIME_STEP.addUnit(new FixedPrecisionUnit("ms", 1, 0.001)); - UNITS_TIME_STEP.addUnit(new FixedPrecisionUnit("s", 0.01)); - UNITS_TIME_STEP.setDefaultUnit(1); - - UNITS_SHORT_TIME = new UnitGroup(); - UNITS_SHORT_TIME.addUnit(new GeneralUnit(1, "s")); - - UNITS_FLIGHT_TIME = new UnitGroup(); - UNITS_FLIGHT_TIME.addUnit(new GeneralUnit(1, "s")); - UNITS_FLIGHT_TIME.addUnit(new GeneralUnit(60, "min")); - - UNITS_ROLL = new UnitGroup(); - UNITS_ROLL.addUnit(new GeneralUnit(1, "rad/s")); - UNITS_ROLL.addUnit(new GeneralUnit(2 * Math.PI, "r/s")); - UNITS_ROLL.addUnit(new GeneralUnit(2 * Math.PI / 60, "rpm")); - UNITS_ROLL.setDefaultUnit(1); - - UNITS_TEMPERATURE = new UnitGroup(); - UNITS_TEMPERATURE.addUnit(new FixedPrecisionUnit("K", 1)); - UNITS_TEMPERATURE.addUnit(new TemperatureUnit(1, 273.15, DEGREE + "C")); - UNITS_TEMPERATURE.addUnit(new TemperatureUnit(5.0 / 9.0, 459.67, DEGREE + "F")); - UNITS_TEMPERATURE.setDefaultUnit(1); - - UNITS_PRESSURE = new UnitGroup(); - UNITS_PRESSURE.addUnit(new FixedPrecisionUnit("mbar", 1, 1.0e2)); - UNITS_PRESSURE.addUnit(new FixedPrecisionUnit("bar", 0.001, 1.0e5)); - UNITS_PRESSURE.addUnit(new FixedPrecisionUnit("atm", 0.001, 1.01325e5)); - UNITS_PRESSURE.addUnit(new GeneralUnit(101325.0 / 760.0, "mmHg")); - UNITS_PRESSURE.addUnit(new GeneralUnit(3386.389, "inHg")); - UNITS_PRESSURE.addUnit(new GeneralUnit(6894.75729, "psi")); - UNITS_PRESSURE.addUnit(new GeneralUnit(1, "Pa")); - - UNITS_RELATIVE = new UnitGroup(); - UNITS_RELATIVE.addUnit(new FixedPrecisionUnit("" + ZWSP, 0.01, 1.0)); - UNITS_RELATIVE.addUnit(new GeneralUnit(0.01, "%")); - UNITS_RELATIVE.addUnit(new FixedPrecisionUnit("" + PERMILLE, 1, 0.001)); - // UNITS_RELATIVE.addUnit(new FixedPrecisionUnit("" + ZWSP, 0.01, 1.0)); - // UNITS_RELATIVE.addUnit(new FixedPrecisionUnit("%", 1, 0.01)); - // UNITS_RELATIVE.addUnit(new FixedPrecisionUnit("" + PERMILLE, 1, 0.001)); - UNITS_RELATIVE.setDefaultUnit(1); - - - UNITS_ROUGHNESS = new UnitGroup(); - UNITS_ROUGHNESS.addUnit(new GeneralUnit(1, "m")); // just added - UNITS_ROUGHNESS.addUnit(new GeneralUnit(0.000001, MICRO + "m")); - UNITS_ROUGHNESS.addUnit(new GeneralUnit(0.0000254, "mil")); - - - UNITS_COEFFICIENT = new UnitGroup(); - UNITS_COEFFICIENT.addUnit(new FixedPrecisionUnit("" + ZWSP, 0.01)); // zero-width space - - - // This is not used by OpenRocket, and not extensively tested: - UNITS_FREQUENCY = new UnitGroup(); - // UNITS_FREQUENCY.addUnit(new GeneralUnit(1, "s")); - // UNITS_FREQUENCY.addUnit(new GeneralUnit(0.001, "ms")); - // UNITS_FREQUENCY.addUnit(new GeneralUnit(0.000001, MICRO + "s")); - UNITS_FREQUENCY.addUnit(new FrequencyUnit(.001, "mHz")); - UNITS_FREQUENCY.addUnit(new FrequencyUnit(1, "Hz")); - UNITS_FREQUENCY.addUnit(new FrequencyUnit(1000, "kHz")); - UNITS_FREQUENCY.setDefaultUnit(1); - - - HashMap<String, UnitGroup> map = new HashMap<String, UnitGroup>(); - map.put("NONE", UNITS_NONE); - map.put("LENGTH", UNITS_LENGTH); - map.put("ALL_LENGTHS", UNITS_ALL_LENGTHS); - map.put("MOTOR_DIMENSIONS", UNITS_MOTOR_DIMENSIONS); - map.put("DISTANCE", UNITS_DISTANCE); - map.put("VELOCITY", UNITS_VELOCITY); - map.put("ACCELERATION", UNITS_ACCELERATION); - map.put("AREA", UNITS_AREA); - map.put("STABILITY", UNITS_STABILITY); - map.put("MASS", UNITS_MASS); - map.put("INERTIA", UNITS_INERTIA); - map.put("ANGLE", UNITS_ANGLE); - map.put("DENSITY_BULK", UNITS_DENSITY_BULK); - map.put("DENSITY_SURFACE", UNITS_DENSITY_SURFACE); - map.put("DENSITY_LINE", UNITS_DENSITY_LINE); - map.put("FORCE", UNITS_FORCE); - map.put("IMPULSE", UNITS_IMPULSE); - map.put("TIME_STEP", UNITS_TIME_STEP); - map.put("SHORT_TIME", UNITS_SHORT_TIME); - map.put("FLIGHT_TIME", UNITS_FLIGHT_TIME); - map.put("ROLL", UNITS_ROLL); - map.put("TEMPERATURE", UNITS_TEMPERATURE); - map.put("PRESSURE", UNITS_PRESSURE); - map.put("RELATIVE", UNITS_RELATIVE); - map.put("ROUGHNESS", UNITS_ROUGHNESS); - map.put("COEFFICIENT", UNITS_COEFFICIENT); - map.put("VOLTAGE", UNITS_VOLTAGE); - map.put("CURRENT", UNITS_CURRENT); - map.put("ENERGY", UNITS_ENERGY); - map.put("POWER", UNITS_POWER); - map.put("MOMENTUM", UNITS_MOMENTUM); - map.put("FREQUENCY", UNITS_FREQUENCY); - - UNITS = Collections.unmodifiableMap(map); - - HashMap<String, UnitGroup> simap = new HashMap<String, UnitGroup>(); - simap.put("m", UNITS_ALL_LENGTHS); - simap.put("m^2", UNITS_AREA); - simap.put("m/s", UNITS_VELOCITY); - simap.put("m/s^2", UNITS_ACCELERATION); - simap.put("kg", UNITS_MASS); - simap.put("kg m^2", UNITS_INERTIA); - simap.put("kg/m^3", UNITS_DENSITY_BULK); - simap.put("N", UNITS_FORCE); - simap.put("Ns", UNITS_IMPULSE); - simap.put("s", UNITS_FLIGHT_TIME); - simap.put("Pa", UNITS_PRESSURE); - simap.put("V", UNITS_VOLTAGE); - simap.put("A", UNITS_CURRENT); - simap.put("J", UNITS_ENERGY); - simap.put("W", UNITS_POWER); - simap.put("kg m/s", UNITS_MOMENTUM); - simap.put("Hz", UNITS_FREQUENCY); - simap.put("K", UNITS_TEMPERATURE); - - SIUNITS = Collections.unmodifiableMap(simap); - } - - public static void setDefaultMetricUnits() { - UNITS_LENGTH.setDefaultUnit("cm"); - UNITS_MOTOR_DIMENSIONS.setDefaultUnit("mm"); - UNITS_DISTANCE.setDefaultUnit("m"); - UNITS_AREA.setDefaultUnit("cm" + SQUARED); - UNITS_STABILITY.setDefaultUnit("cal"); - UNITS_VELOCITY.setDefaultUnit("m/s"); - UNITS_ACCELERATION.setDefaultUnit("m/s" + SQUARED); - UNITS_MASS.setDefaultUnit("g"); - UNITS_INERTIA.setDefaultUnit("kg" + DOT + "m" + SQUARED); - UNITS_ANGLE.setDefaultUnit("" + DEGREE); - UNITS_DENSITY_BULK.setDefaultUnit("g/cm" + CUBED); - UNITS_DENSITY_SURFACE.setDefaultUnit("g/m" + SQUARED); - UNITS_DENSITY_LINE.setDefaultUnit("g/m"); - UNITS_FORCE.setDefaultUnit("N"); - UNITS_IMPULSE.setDefaultUnit("Ns"); - UNITS_TIME_STEP.setDefaultUnit("s"); - UNITS_FLIGHT_TIME.setDefaultUnit("s"); - UNITS_ROLL.setDefaultUnit("r/s"); - UNITS_TEMPERATURE.setDefaultUnit(DEGREE + "C"); - UNITS_WINDSPEED.setDefaultUnit("m/s"); - UNITS_PRESSURE.setDefaultUnit("mbar"); - UNITS_RELATIVE.setDefaultUnit("%"); - UNITS_ROUGHNESS.setDefaultUnit(MICRO + "m"); - } - - public static void setDefaultImperialUnits() { - UNITS_LENGTH.setDefaultUnit("in"); - UNITS_MOTOR_DIMENSIONS.setDefaultUnit("in"); - UNITS_DISTANCE.setDefaultUnit("ft"); - UNITS_AREA.setDefaultUnit("in" + SQUARED); - UNITS_STABILITY.setDefaultUnit("cal"); - UNITS_VELOCITY.setDefaultUnit("ft/s"); - UNITS_ACCELERATION.setDefaultUnit("ft/s" + SQUARED); - UNITS_MASS.setDefaultUnit("oz"); - UNITS_INERTIA.setDefaultUnit("lb" + DOT + "ft" + SQUARED); - UNITS_ANGLE.setDefaultUnit("" + DEGREE); - UNITS_DENSITY_BULK.setDefaultUnit("oz/in" + CUBED); - UNITS_DENSITY_SURFACE.setDefaultUnit("oz/ft" + SQUARED); - UNITS_DENSITY_LINE.setDefaultUnit("oz/ft"); - UNITS_FORCE.setDefaultUnit("N"); - UNITS_IMPULSE.setDefaultUnit("Ns"); - UNITS_TIME_STEP.setDefaultUnit("s"); - UNITS_FLIGHT_TIME.setDefaultUnit("s"); - UNITS_ROLL.setDefaultUnit("r/s"); - UNITS_TEMPERATURE.setDefaultUnit(DEGREE + "F"); - UNITS_WINDSPEED.setDefaultUnit("mph"); - UNITS_PRESSURE.setDefaultUnit("mbar"); - UNITS_RELATIVE.setDefaultUnit("%"); - UNITS_ROUGHNESS.setDefaultUnit("mil"); - } - - - /** - * Return a UnitGroup for stability units based on the rocket. - * - * @param rocket the rocket from which to calculate the caliber - * @return the unit group - */ - public static UnitGroup stabilityUnits(Rocket rocket) { - return new StabilityUnitGroup(rocket); - } - - - /** - * Return a UnitGroup for stability units based on the rocket configuration. - * - * @param config the rocket configuration from which to calculate the caliber - * @return the unit group - */ - public static UnitGroup stabilityUnits(Configuration config) { - return new StabilityUnitGroup(config); - } - - - /** - * Return a UnitGroup for stability units based on a constant caliber. - * - * @param reference the constant reference length - * @return the unit group - */ - public static UnitGroup stabilityUnits(double reference) { - return new StabilityUnitGroup(reference); - } - - - ////////////////////////////////////////////////////// - - - protected ArrayList<Unit> units = new ArrayList<Unit>(); - protected int defaultUnit = 0; - - public int getUnitCount() { - return units.size(); - } - - public Unit getDefaultUnit() { - return units.get(defaultUnit); - } - - public int getDefaultUnitIndex() { - return defaultUnit; - } - - public void setDefaultUnit(int n) { - if (n < 0 || n >= units.size()) { - throw new IllegalArgumentException("index out of range: " + n); - } - defaultUnit = n; - } - - public Unit getSIUnit(){ - for (Unit u : units){ - if (u.multiplier == 1){ - return u; - } - } - return UNITS_NONE.getDefaultUnit(); - } - - /** - * Find a unit by approximate unit name. Only letters and (ordinary) numbers are - * considered in the matching. This method is mainly means for testing, allowing - * a simple means to obtain a particular unit. - * - * @param str the unit name. - * @return the corresponding unit, or <code>null</code> if not found. - */ - public Unit findApproximate(String str) { - str = str.replaceAll("\\W", "").trim(); - for (Unit u : units) { - String name = u.getUnit().replaceAll("\\W", "").trim(); - if (str.equalsIgnoreCase(name)) - return u; - } - return null; - } - - /** - * Set the default unit based on the unit name. Throws an exception if a - * unit with the provided name is not available. - * - * @param name the unit name. - * @throws IllegalArgumentException if the corresponding unit is not found in the group. - */ - public void setDefaultUnit(String name) throws IllegalArgumentException { - for (int i = 0; i < units.size(); i++) { - if (units.get(i).getUnit().equals(name)) { - setDefaultUnit(i); - return; - } - } - throw new IllegalArgumentException("name=" + name); - } - - public Unit getUnit(String name) throws IllegalArgumentException { - for (int i = 0; i < units.size(); i++) { - if (units.get(i).getUnit().equals(name)) { - return units.get(i); - } - } - throw new IllegalArgumentException("name=" + name); - } - - public Unit getUnit(int n) { - return units.get(n); - } - - public int getUnitIndex(Unit u) { - return units.indexOf(u); - } - - public void addUnit(Unit u) { - units.add(u); - } - - public boolean contains(Unit u) { - return units.contains(u); - } - - public Unit[] getUnits() { - return units.toArray(new Unit[0]); - } - - /** - * Return the value in SI units from the default unit of this group. - * It is the same as calling <code>getDefaultUnit().fromUnit(value)</code> - * - * @param value the default unit value to convert - * @return the value in SI units. - * @see Unit#fromUnit(double) - */ - public double fromUnit( double value ) { - return this.getDefaultUnit().fromUnit(value); - } - - /** - * Return the value formatted by the default unit of this group. - * It is the same as calling <code>getDefaultUnit().toString(value)</code>. - * - * @param value the SI value to format. - * @return the formatted string. - * @see Unit#toString(double) - */ - public String toString(double value) { - return this.getDefaultUnit().toString(value); - } - - - /** - * Return the value formatted by the default unit of this group including the unit. - * It is the same as calling <code>getDefaultUnit().toStringUnit(value)</code>. - * - * @param value the SI value to format. - * @return the formatted string. - * @see Unit#toStringUnit(double) - */ - public String toStringUnit(double value) { - return this.getDefaultUnit().toStringUnit(value); - } - - - - - - /** - * Creates a new Value object with the specified value and the default unit of this group. - * - * @param value the value to set. - * @return a new Value object. - */ - public Value toValue(double value) { - return this.getDefaultUnit().toValue(value); - } - - @Override - public String toString(){ - return this.getClass().getSimpleName()+":"+this.getSIUnit().toString(); - } - - @Override - public boolean equals(Object o){ - UnitGroup u = (UnitGroup) o; - int size = units.size(); - if (size != u.units.size()){ - return false; - } - - for (int i=0; i<size; i++){ - if ( !units.get(i).equals(u.units.get(i)) ){ - return false; - } - } - - return true; - - } - - - private static final Pattern STRING_PATTERN = Pattern.compile("^\\s*([0-9.,-]+)(.*?)$"); - - /** - * Converts a string into an SI value. If the string has one of the units in this - * group appended to it, that unit will be used in conversion. Otherwise the default - * unit will be used. If an unknown unit is specified or the value does not parse - * with <code>Double.parseDouble</code> then a <code>NumberFormatException</code> - * is thrown. - * <p> - * This method is applicable only for simple units without e.g. powers. - * - * @param str the string to parse. - * @return the SI value. - * @throws NumberFormatException if the string cannot be parsed. - */ - public double fromString(String str) { - Matcher matcher = STRING_PATTERN.matcher(str); - - if (!matcher.matches()) { - throw new NumberFormatException("string did not match required pattern"); - } - - double value = Double.parseDouble(matcher.group(1)); - String unit = matcher.group(2).trim(); - - if (unit.equals("")) { - value = this.getDefaultUnit().fromUnit(value); - } else { - int i; - for (i = 0; i < units.size(); i++) { - Unit u = units.get(i); - if (unit.equalsIgnoreCase(u.getUnit())) { - value = u.fromUnit(value); - break; - } - } - if (i >= units.size()) { - throw new NumberFormatException("unknown unit " + unit); - } - } - - return value; - } - - - /////////////////////////// - - - @Override - public int hashCode() { - int code = 0; - for (Unit u : units){ - code = code + u.hashCode(); - } - return code; - } - - /** - * A private class that switches the CaliberUnit to a rocket-specific CaliberUnit. - * All other methods are passed through to UNITS_STABILITY. - */ - private static class StabilityUnitGroup extends UnitGroup { - - public StabilityUnitGroup(double ref) { - this(new CaliberUnit(ref)); - } - - public StabilityUnitGroup(Rocket rocket) { - this(new CaliberUnit(rocket)); - } - - public StabilityUnitGroup(Configuration config) { - this(new CaliberUnit(config)); - } - - private StabilityUnitGroup(CaliberUnit caliberUnit) { - this.units.addAll(UnitGroup.UNITS_STABILITY.units); - this.defaultUnit = UnitGroup.UNITS_STABILITY.defaultUnit; - for (int i = 0; i < units.size(); i++) { - if (units.get(i) instanceof CaliberUnit) { - units.set(i, caliberUnit); - } - } - } - - - @Override - public void setDefaultUnit(int n) { - super.setDefaultUnit(n); - UNITS_STABILITY.setDefaultUnit(n); - } - } -} diff --git a/core/src/net/sf/openrocket/unit/Value.java b/core/src/net/sf/openrocket/unit/Value.java deleted file mode 100644 index 65382523..00000000 --- a/core/src/net/sf/openrocket/unit/Value.java +++ /dev/null @@ -1,153 +0,0 @@ -package net.sf.openrocket.unit; - -import net.sf.openrocket.util.MathUtil; - -/** - * An immutable class representing an SI value and a unit. The toString() method yields the - * current value in the current units. This class may be used to encapsulate - * a sortable value for example for tables. The sorting is performed by the - * value in the current units, ignoring the unit. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Value implements Comparable<Value> { - - private final double value; - private final Unit unit; - - - /** - * Create a new Value object. - * - * @param value the value to set. - * @param unit the unit to set (<code>null</code> not allowed) - */ - public Value(double value, Unit unit) { - if (unit == null) { - throw new IllegalArgumentException("unit is null"); - } - this.value = value; - this.unit = unit; - } - - - /** - * Creates a new Value object using unit group. Currently it simply uses the default - * unit of the group, but may later change. - * - * @param value the value to set. - * @param group the group the value belongs to. - */ - public Value(double value, UnitGroup group) { - this(value, group.getDefaultUnit()); - } - - - /** - * Get the value of this object (in SI units). - * - * @return the value - */ - public double getValue() { - return value; - } - - - - /** - * Get the value of this object in the current units. - * - * @return the value in the current units. - */ - public double getUnitValue() { - return unit.toUnit(value); - } - - - /** - * Get the unit of this object. - * - * @return the unit - */ - public Unit getUnit() { - return unit; - } - - - /** - * Return a string formatted using the {@link Unit#toStringUnit(double)} method - * of the current unit. If the unit is <code>null</code> then the UNITS_NONE - * group is used. - */ - @Override - public String toString() { - return unit.toStringUnit(value); - } - - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - - Value other = (Value) obj; - if (this.unit != other.unit) { - return false; - } - - if (!MathUtil.equals(this.value, other.value)) { - return false; - } - - return true; - } - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((unit == null) ? 0 : unit.hashCode()); - long temp; - temp = Double.doubleToLongBits(value); - result = prime * result + (int) (temp ^ (temp >>> 32)); - return result; - } - - - /** - * Compare this value to another value. The comparison is performed primarily by - * the unit text, secondarily the value in the unit values. - */ - @Override - public int compareTo(Value o) { - int n = this.getUnit().getUnit().compareTo(o.getUnit().getUnit()); - if (n != 0) - return n; - - double us = this.getUnitValue(); - double them = o.getUnitValue(); - - if (Double.isNaN(us)) { - if (Double.isNaN(them)) - return 0; - else - return 1; - } - if (Double.isNaN(them)) - return -1; - - if (us < them) - return -1; - else if (us > them) - return 1; - else - return 0; - } - -} diff --git a/core/src/net/sf/openrocket/unit/ValueComparator.java b/core/src/net/sf/openrocket/unit/ValueComparator.java deleted file mode 100644 index a948e9d2..00000000 --- a/core/src/net/sf/openrocket/unit/ValueComparator.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.sf.openrocket.unit; - -import java.util.Comparator; - -public class ValueComparator implements Comparator<Value> { - - public static final ValueComparator INSTANCE = new ValueComparator(); - - @Override - public int compare(Value o1, Value o2) { - return o1.compareTo(o2); - } - -} diff --git a/core/src/net/sf/openrocket/util/AbstractChangeSource.java b/core/src/net/sf/openrocket/util/AbstractChangeSource.java deleted file mode 100644 index 57664aed..00000000 --- a/core/src/net/sf/openrocket/util/AbstractChangeSource.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.EventListener; -import java.util.EventObject; -import java.util.List; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * Abstract implementation of a ChangeSource. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public abstract class AbstractChangeSource implements ChangeSource { - private static final LogHelper log = Application.getLogger(); - - private final List<EventListener> listeners = new ArrayList<EventListener>(); - - private final EventObject event = new EventObject(this); - - - @Override - public final void addChangeListener(EventListener listener) { - listeners.add(listener); - log.verbose(1, "Adding change listeners, listener count is now " + listeners.size()); - } - - @Override - public final void removeChangeListener(EventListener listener) { - listeners.remove(listener); - log.verbose(1, "Removing change listeners, listener count is now " + listeners.size()); - } - - - /** - * Fire a change event to all listeners. - */ - protected void fireChangeEvent() { - // Copy the list before iterating to prevent concurrent modification exceptions. - EventListener[] list = listeners.toArray(new EventListener[0]); - for (EventListener l : list) { - if ( l instanceof StateChangeListener ) { - ((StateChangeListener)l).stateChanged(event); - } - } - } -} diff --git a/core/src/net/sf/openrocket/util/AlphanumComparator.java b/core/src/net/sf/openrocket/util/AlphanumComparator.java deleted file mode 100644 index c7a7b488..00000000 --- a/core/src/net/sf/openrocket/util/AlphanumComparator.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * The Alphanum Algorithm is an improved sorting algorithm for strings - * containing numbers. Instead of sorting numbers in ASCII order like - * a standard sort, this algorithm sorts numbers in numeric order. - * - * The Alphanum Algorithm is discussed at http://www.DaveKoelle.com - * - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* - * Subsequently this code had been hacked up to make it genericized and support - * folding upper/lower case. - */ -package net.sf.openrocket.util; - -import java.text.Collator; -import java.util.Comparator; - -/** - * This is an updated version with enhancements made by Daniel Migowski, - * Andre Bogus, and David Koelle - * - * To convert to use Templates (Java 1.5+): - * - Change "implements Comparator" to "implements Comparator<String>" - * - Change "compare(Object o1, Object o2)" to "compare(String s1, String s2)" - * - Remove the type checking and casting in compare(). - * - * To use this class: - * Use the static "sort" method from the java.util.Collections class: - * Collections.sort(your list, new AlphanumComparator()); - */ -public class AlphanumComparator implements Comparator<String> -{ - - private static final Collator sorter = Collator.getInstance(); - static { - sorter.setStrength(Collator.TERTIARY); - sorter.setDecomposition(Collator.CANONICAL_DECOMPOSITION); - } - - private final boolean isDigit(char ch) - { - return ch >= 48 && ch <= 57; - } - - /** Length of string is passed in for improved efficiency (only need to calculate it once) **/ - private final String getChunk(String s, int slength, int marker) - { - StringBuilder chunk = new StringBuilder(); - char c = s.charAt(marker); - chunk.append(c); - marker++; - if (isDigit(c)) - { - while (marker < slength) - { - c = s.charAt(marker); - if (!isDigit(c)) - break; - chunk.append(c); - marker++; - } - } else - { - while (marker < slength) - { - c = s.charAt(marker); - if (isDigit(c)) - break; - chunk.append(c); - marker++; - } - } - return chunk.toString(); - } - - @Override - public int compare(String s1, String s2) - { - - int thisMarker = 0; - int thatMarker = 0; - int s1Length = s1.length(); - int s2Length = s2.length(); - - while (thisMarker < s1Length && thatMarker < s2Length) - { - String thisChunk = getChunk(s1, s1Length, thisMarker); - thisMarker += thisChunk.length(); - - String thatChunk = getChunk(s2, s2Length, thatMarker); - thatMarker += thatChunk.length(); - - // If both chunks contain numeric characters, sort them numerically - int result = 0; - if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) - { - // Simple chunk comparison by length. - int thisChunkLength = thisChunk.length(); - result = thisChunkLength - thatChunk.length(); - // If equal, the first different number counts - if (result == 0) - { - for (int i = 0; i < thisChunkLength; i++) - { - result = thisChunk.charAt(i) - thatChunk.charAt(i); - if (result != 0) - { - return result; - } - } - } - } else - { - result = sorter.compare(thisChunk, thatChunk); - } - - if (result != 0) - return result; - } - - return s1Length - s2Length; - } -} diff --git a/core/src/net/sf/openrocket/util/ArrayList.java b/core/src/net/sf/openrocket/util/ArrayList.java deleted file mode 100644 index a91deaa4..00000000 --- a/core/src/net/sf/openrocket/util/ArrayList.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Collection; - -/** - * An implementation of an ArrayList with a type-safe {@link #clone()} method. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class ArrayList<E> extends java.util.ArrayList<E> { - - public ArrayList() { - super(); - } - - public ArrayList(Collection<? extends E> c) { - super(c); - } - - public ArrayList(int initialCapacity) { - super(initialCapacity); - } - - @SuppressWarnings("unchecked") - @Override - public ArrayList<E> clone() { - return (ArrayList<E>) super.clone(); - } - -} diff --git a/core/src/net/sf/openrocket/util/ArrayUtils.java b/core/src/net/sf/openrocket/util/ArrayUtils.java deleted file mode 100644 index d0293940..00000000 --- a/core/src/net/sf/openrocket/util/ArrayUtils.java +++ /dev/null @@ -1,250 +0,0 @@ -package net.sf.openrocket.util; - -import java.lang.reflect.Array; - -public class ArrayUtils { - - /** - * Returns a double array with values from start to end with given step. - * Starts exactly at start and stops at the multiple of step <= stop. - */ - public static double[] range(double start, double stop, double step){ - - int size = (int) Math.floor(((stop - start) / step)) + 1; - - //System.out.println("Range from "+start+" to "+stop+" step "+step+" has length "+size); - - double[] output = new double[size]; - int i = 0; - double x = start; - while (i<size){ - output[i] = x; - x = x+step; - i++; - } - - return output; - } - - /** - * Return the mean of an array - */ - public static double mean(double[] vals){ - double subtotal = 0; - for (int i = 0; i < vals.length; i++ ){ - if (!Double.isNaN(vals[i])){ - subtotal += vals[i]; - } - } - subtotal = subtotal / vals.length; - return subtotal; - } - - /** - * Returns the maximum value in the array. - */ - - public static double max(double[] vals) { - double m = vals[0]; - for (int i = 1; i < vals.length; i++) - m = Math.max(m, vals[i]); - return m; - } - - /** - * Returns the minimum value in the array. - */ - - public static double min(double[] vals) { - double m = vals[0]; - for (int i = 1; i < vals.length; i++) - m = Math.min(m, vals[i]); - return m; - } - - /** - * Returns the variance of the array of doubles - */ - public static double variance(double[] vals) { - double mu = mean(vals); - double sumsq = 0.0; - double temp = 0; - for (int i = 0; i < vals.length; i++){ - if (!Double.isNaN(vals[i])){ - temp = (mu - vals[i]); - sumsq += temp*temp; - } - } - return sumsq / (vals.length); - } - - /** - * Returns the standard deviation of an array of doubles - */ - public static double stdev(double[] vals) { - return Math.sqrt(variance(vals)); - } - - /** - * Returns the RMS value of an array of doubles - */ - public static double rms(double[] vals) { - double m = mean(vals); - double s = stdev(vals); - return Math.sqrt( m*m + s*s ); - } - - /** - * Returns the integral of a given array calculated by the trapezoidal rule - * dt is the time step between each array value. Any NaN values are treated as zero - */ - public static double trapz(double[] y, double dt){ - double stop = (y.length -1) * dt; - - if (y.length <= 1 || dt <= 0) return 0; - - double[] x = range(0, stop, dt); - - double sum = 0.0; - for (int i = 1; i < x.length; i++) { - double temp = (x[i] - x[i-1]) * (y[i] + y[i-1]); - if (!Double.isNaN(temp)){ - sum += temp; - } - } - return sum * 0.5; - } - - /** - * Returns the nearest value in an array to a given value - * Search starts from the lowest array index - */ - public static double tnear(double[] range, double near, double start, double step){ - double min = Double.POSITIVE_INFINITY; - int mini = 0; - - //System.out.println("Nearest to "+near+" in range length "+range.length); - for (int i=0; i < range.length; i++){ - double x = Math.abs(range[i] - near); - if (x < min){ - min = x; - mini = i; - } - } - - //System.out.println("Found nearest at i="+mini); - return start + (mini*step); - } - - - public static <T> T[] copyOf( T[] original, int length ) { - return copyOfRange(original,0,length); - } - - /** - * Implementation of java.util.Arrays.copyOfRange - * - * Since Froyo does not include this function it must be implemented here. - * - * @param original - * @param start - * @param end - * @return - */ - public static <T> T[] copyOfRange( T[] original, int start, int end ) { - - if ( original == null ) { - throw new NullPointerException(); - } - - if ( start < 0 || start > original.length ) { - throw new ArrayIndexOutOfBoundsException(); - } - - if ( start > end ) { - throw new IllegalArgumentException(); - } - - T[] result = (T[]) Array.newInstance( original.getClass().getComponentType(), end-start ); - - int index = 0; - int stop = original.length < end ? original.length : end; - for ( int i = start; i < stop; i ++ ) { - if ( i < original.length ) { - result[index] = original[i]; - } - index++; - } - - return result; - - } - - public static double[] copyOf( double[] original, int length ) { - return copyOfRange(original,0,length); - } - - public static double[] copyOfRange( double[] original, int start, int end ) { - - if ( original == null ) { - throw new NullPointerException(); - } - - if ( start < 0 || start > original.length ) { - throw new ArrayIndexOutOfBoundsException(); - } - - if ( start > end ) { - throw new IllegalArgumentException(); - } - - double[] result = new double[(end-start)]; - - int index = 0; - int stop = original.length < end ? original.length : end; - for ( int i = start; i < stop; i ++ ) { - if ( i < original.length ) { - result[index] = original[i]; - } - index++; - } - - return result; - - } - - public static byte[] copyOf( byte[] original, int length ) { - return copyOfRange(original,0,length); - } - - public static byte[] copyOfRange( byte[] original, int start, int end ) { - - if ( original == null ) { - throw new NullPointerException(); - } - - if ( start < 0 || start > original.length ) { - throw new ArrayIndexOutOfBoundsException(); - } - - if ( start > end ) { - throw new IllegalArgumentException(); - } - - byte[] result = new byte[(end-start)]; - - int index = 0; - int stop = original.length < end ? original.length : end; - for ( int i = start; i < stop; i ++ ) { - if ( i < original.length ) { - result[index] = original[i]; - } - index++; - } - - return result; - - } - -} - diff --git a/core/src/net/sf/openrocket/util/Base64.java b/core/src/net/sf/openrocket/util/Base64.java deleted file mode 100644 index aeed54a1..00000000 --- a/core/src/net/sf/openrocket/util/Base64.java +++ /dev/null @@ -1,168 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class Base64 { - - public static final int DEFAULT_CHARS_PER_LINE = 72; - - private static final char[] ALPHABET = new char[] { - 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', - 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', - 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', - 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' - }; - private static final char PAD = '='; - -// private static final byte[] REVERSE; -// static { -// REVERSE = new byte[128]; -// Arrays.fill(REVERSE, (byte)-1); -// for (int i=0; i<64; i++) { -// REVERSE[ALPHABET[i]] = (byte)i; -// } -// REVERSE['-'] = 62; -// REVERSE['_'] = 63; -// REVERSE[PAD] = 0; -// } - - private static final Map<Character,Integer> REVERSE = new HashMap<Character,Integer>(); - static { - for (int i=0; i<64; i++) { - REVERSE.put(ALPHABET[i], i); - } - REVERSE.put('-', 62); - REVERSE.put('_', 63); - REVERSE.put(PAD, 0); - } - - - public static String encode(byte[] data) { - return encode(data, DEFAULT_CHARS_PER_LINE); - } - - public static String encode(byte[] data, int maxColumn) { - StringBuilder builder = new StringBuilder(); - int column = 0; - - for (int position=0; position < data.length; position+=3) { - if (column+4 > maxColumn) { - builder.append('\n'); - column = 0; - } - builder.append(encodeGroup(data, position)); - column += 4; - } - builder.append('\n'); - return builder.toString(); - } - - - - - public static byte[] decode(String data) { - byte[] array = new byte[data.length()*3/4]; - char[] block = new char[4]; - int length = 0; - - for (int position=0; position < data.length(); ) { - int p; - for (p=0; p<4 && position < data.length(); position++) { - char c = data.charAt(position); - if (!Character.isWhitespace(c)) { - block[p] = c; - p++; - } - } - - if (p==0) - break; - if (p!=4) { - throw new IllegalArgumentException("Data ended when decoding Base64, data=" + data + ", p="+p); - } - - int l = decodeGroup(block, array, length); - length += l; - if (l < 3) - break; - } - return Arrays.copyOf(array, length); - } - - - //// Helper methods - - - /** - * Encode three bytes of data into four characters. - */ - private static char[] encodeGroup(byte[] data, int position) { - char[] c = new char[] { '=','=','=','=' }; - int b1=0, b2=0, b3=0; - int length = data.length - position; - - if (length == 0) - return c; - - if (length >= 1) { - b1 = ((int)data[position])&0xFF; - } - if (length >= 2) { - b2 = ((int)data[position+1])&0xFF; - } - if (length >= 3) { - b3 = ((int)data[position+2])&0xFF; - } - - c[0] = ALPHABET[b1>>2]; - c[1] = ALPHABET[(b1 & 3)<<4 | (b2>>4)]; - if (length == 1) - return c; - c[2] = ALPHABET[(b2 & 15)<<2 | (b3>>6)]; - if (length == 2) - return c; - c[3] = ALPHABET[b3 & 0x3f]; - return c; - } - - - /** - * Decode four chars from data into 0-3 bytes of data starting at position in array. - * @return the number of bytes decoded. - */ - private static int decodeGroup(char[] data, byte[] array, int position) { - int b1, b2, b3, b4; - - try { - b1 = REVERSE.get(data[0]); - b2 = REVERSE.get(data[1]); - b3 = REVERSE.get(data[2]); - b4 = REVERSE.get(data[3]); - } catch (NullPointerException e) { - // If auto-boxing fails - throw new IllegalArgumentException("Illegal characters in the sequence to be "+ - "decoded: "+Arrays.toString(data)); - } - - array[position] = (byte)((b1 << 2) | (b2 >> 4)); - array[position+1] = (byte)((b2 << 4) | (b3 >> 2)); - array[position+2] = (byte)((b3 << 6) | (b4)); - - // Check the amount of data decoded - if (data[0] == PAD) - return 0; - if (data[1] == PAD) { - throw new IllegalArgumentException("Illegal character padding in sequence to be "+ - "decoded: "+Arrays.toString(data)); - } - if (data[2] == PAD) - return 1; - if (data[3] == PAD) - return 2; - - return 3; - } - -} diff --git a/core/src/net/sf/openrocket/util/BugException.java b/core/src/net/sf/openrocket/util/BugException.java deleted file mode 100644 index 8d113add..00000000 --- a/core/src/net/sf/openrocket/util/BugException.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.util; - -/** - * Thrown when a bug is noticed. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class BugException extends FatalException { - - public BugException(String message) { - super("BUG: " + message); - } - - public BugException(Throwable cause) { - super("BUG: " + cause.getMessage(), cause); - } - - public BugException(String message, Throwable cause) { - super("BUG: " + message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/util/BuildProperties.java b/core/src/net/sf/openrocket/util/BuildProperties.java deleted file mode 100644 index 9e88e93e..00000000 --- a/core/src/net/sf/openrocket/util/BuildProperties.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.sf.openrocket.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.MissingResourceException; -import java.util.Properties; - -public class BuildProperties { - - private static final Properties PROPERTIES; - private static final String BUILD_VERSION; - private static final String BUILD_SOURCE; - private static final boolean DEFAULT_CHECK_UPDATES; - - /** - * Return the OpenRocket version number. - */ - public static String getVersion() { - return BUILD_VERSION; - } - - /** - * Return the OpenRocket build source (e.g. "default" or "Debian") - */ - public static String getBuildSource() { - return BUILD_SOURCE; - } - - public static boolean getDefaultCheckUpdates() { - return DEFAULT_CHECK_UPDATES; - } - - static { - try { - InputStream is = BuildProperties.class.getClassLoader().getResourceAsStream("build.properties"); - if (is == null) { - throw new MissingResourceException( - "build.properties not found, distribution built wrong" + - " classpath:" + System.getProperty("java.class.path"), - "build.properties", "build.version"); - } - - PROPERTIES = new Properties(); - PROPERTIES.load(is); - is.close(); - - String version = PROPERTIES.getProperty("build.version"); - if (version == null) { - throw new MissingResourceException( - "build.version not found in property file", - "build.properties", "build.version"); - } - BUILD_VERSION = version.trim(); - - BUILD_SOURCE = PROPERTIES.getProperty("build.source"); - if (BUILD_SOURCE == null) { - throw new MissingResourceException( - "build.source not found in property file", - "build.properties", "build.source"); - } - - String value = PROPERTIES.getProperty("build.checkupdates"); - if (value != null) - DEFAULT_CHECK_UPDATES = Boolean.parseBoolean(value); - else - DEFAULT_CHECK_UPDATES = true; - - } catch (IOException e) { - throw new MissingResourceException( - "Error reading build.properties", - "build.properties", "build.version"); - } - } - -} diff --git a/core/src/net/sf/openrocket/util/ChangeSource.java b/core/src/net/sf/openrocket/util/ChangeSource.java deleted file mode 100644 index f6669ef3..00000000 --- a/core/src/net/sf/openrocket/util/ChangeSource.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.EventListener; - -/** - * An interface defining an object firing ChangeEvents. Why isn't this included in the Java API?? - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public interface ChangeSource { - - public void addChangeListener(EventListener listener); - public void removeChangeListener(EventListener listener); - -} diff --git a/core/src/net/sf/openrocket/util/Chars.java b/core/src/net/sf/openrocket/util/Chars.java deleted file mode 100644 index 1b2857a2..00000000 --- a/core/src/net/sf/openrocket/util/Chars.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.sf.openrocket.util; - -/** - * A class defining various non-ASCII characters for easier use. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Chars { - - /** The fraction 1/2 */ - public static final char FRAC12 = '\u00BD'; - /** The fraction 1/4 */ - public static final char FRAC14 = '\u00BC'; - /** The fraction 3/4 */ - public static final char FRAC34 = '\u00BE'; - /** Fraction slash */ - public static final char FRACTION = '\u2044'; - - /** Degree sign */ - public static final char DEGREE = '\u00B0'; - - /** Squared, superscript 2 */ - public static final char SQUARED = '\u00B2'; - /** Cubed, superscript 3 */ - public static final char CUBED = '\u00B3'; - - /** Per mille sign */ - public static final char PERMILLE = '\u2030'; - - /** Middle dot, multiplication */ - public static final char DOT = '\u00B7'; - /** Multiplication sign, cross */ - public static final char TIMES = '\u00D7'; - - /** No-break space */ - public static final char NBSP = '\u00A0'; - /** Zero-width space */ - public static final char ZWSP = '\u200B'; - - /** Em dash */ - public static final char EMDASH = '\u2014'; - - /** Micro sign (Greek letter mu) */ - public static final char MICRO = '\u00B5'; - - /** Alpha */ - public static final char ALPHA = '\u03b1'; - /** Theta */ - public static final char THETA = '\u0398'; - - /** Copyright symbol */ - public static final char COPY = '\u00A9'; - /** A centered bullet */ - public static final char BULLET = '\u2022'; - - /** Left arrow (light) */ - public static final char LEFT_ARROW = '\u2190'; - /** Right arrow (light) */ - public static final char RIGHT_ARROW = '\u2192'; - -} diff --git a/core/src/net/sf/openrocket/util/Color.java b/core/src/net/sf/openrocket/util/Color.java deleted file mode 100644 index 5f56a173..00000000 --- a/core/src/net/sf/openrocket/util/Color.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.sf.openrocket.util; - -public class Color { - - public static Color BLACK = new Color(255,255,255); - - private int red; - private int green; - private int blue; - private int alpha; - - public Color( int red, int green, int blue ) { - this.red = red; - this.green = green; - this.blue = blue; - this.alpha = 255; - } - - public Color( int red, int green, int blue, int alpha ) { - this.red = red; - this.green = green; - this.blue = blue; - this.alpha = alpha; - } - - public int getRed() { - return red; - } - - public void setRed(int red) { - this.red = red; - } - - public int getGreen() { - return green; - } - - public void setGreen(int green) { - this.green = green; - } - - public int getBlue() { - return blue; - } - - public void setBlue(int blue) { - this.blue = blue; - } - - public int getAlpha() { - return alpha; - } - - public void setAlpha(int alpha) { - this.alpha = alpha; - } - -} diff --git a/core/src/net/sf/openrocket/util/ComparablePair.java b/core/src/net/sf/openrocket/util/ComparablePair.java deleted file mode 100644 index 7b879683..00000000 --- a/core/src/net/sf/openrocket/util/ComparablePair.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.util; - -/** - * Sortable storage of a pair of objects. A list of these objects can be sorted according - * to the first object. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - * @param <U> the first object type, according to which comparisons are performed. - * @param <V> the second object type. - */ -public class ComparablePair<U extends Comparable<U>, V> extends Pair<U, V> - implements Comparable<ComparablePair<U, V>>{ - - public ComparablePair(U u, V v) { - super(u, v); - } - - - /** - * Compares the first objects. If either of the objects is <code>null</code> this - * method throws <code>NullPointerException</code>. - */ - @Override - public int compareTo(ComparablePair<U, V> other) { - return this.getU().compareTo(other.getU()); - } - -} diff --git a/core/src/net/sf/openrocket/util/ConcurrencyException.java b/core/src/net/sf/openrocket/util/ConcurrencyException.java deleted file mode 100644 index 252267c8..00000000 --- a/core/src/net/sf/openrocket/util/ConcurrencyException.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.sf.openrocket.util; - -/** - * An exception that indicates a concurrency bug in the software. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class ConcurrencyException extends FatalException { - - public ConcurrencyException() { - super(); - } - - public ConcurrencyException(String message, Throwable cause) { - super(message, cause); - } - - public ConcurrencyException(String message) { - super(message); - } - - public ConcurrencyException(Throwable cause) { - super(cause); - } - -} diff --git a/core/src/net/sf/openrocket/util/ConfigurationException.java b/core/src/net/sf/openrocket/util/ConfigurationException.java deleted file mode 100644 index 692b3ac1..00000000 --- a/core/src/net/sf/openrocket/util/ConfigurationException.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.sf.openrocket.util; - -/** - * An exception to be thrown when a fatal problem with the environment - * is encountered (for example some file cannot be found). - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class ConfigurationException extends FatalException { - - public ConfigurationException() { - } - - public ConfigurationException(String message) { - super(message); - } - - public ConfigurationException(Throwable cause) { - super(cause); - } - - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/util/Coordinate.java b/core/src/net/sf/openrocket/util/Coordinate.java deleted file mode 100644 index 0f65ffa4..00000000 --- a/core/src/net/sf/openrocket/util/Coordinate.java +++ /dev/null @@ -1,325 +0,0 @@ -package net.sf.openrocket.util; - -import java.io.Serializable; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * An immutable class of weighted coordinates. The weights are non-negative. - * - * Can also be used as non-weighted coordinates with weight=0. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public final class Coordinate implements Cloneable, Serializable { - private static final LogHelper log = Application.getLogger(); - - // Defined for backwards compatibility after adding clone(). - static final long serialVersionUID = 585574649794259293L; - - //////// Debug section - /* - * Debugging info. If openrocket.debug.coordinatecount is defined, a line is - * printed every 1000000 instantiations (or as many as defined). - */ - private static final boolean COUNT_DEBUG; - private static final int COUNT_DIFF; - static { - String str = System.getProperty("openrocket.debug.coordinatecount"); - int diff = 0; - if (str == null) { - COUNT_DEBUG = false; - COUNT_DIFF = 0; - } else { - COUNT_DEBUG = true; - try { - diff = Integer.parseInt(str); - } catch (NumberFormatException ignore) { - } - if (diff < 1000) - diff = 1000000; - COUNT_DIFF = diff; - } - } - - private static int count = 0; - { - // Debug count - if (COUNT_DEBUG) { - synchronized (Coordinate.class) { - count++; - if ((count % COUNT_DIFF) == 0) { - log.debug("Coordinate instantiated " + count + " times."); - } - } - } - } - - //////// End debug section - - - - public static final Coordinate NUL = new Coordinate(0, 0, 0, 0); - public static final Coordinate NaN = new Coordinate(Double.NaN, Double.NaN, - Double.NaN, Double.NaN); - - public final double x, y, z; - public final double weight; - - - private double length = -1; /* Cached when calculated */ - - - public Coordinate() { - this(0, 0, 0, 0); - } - - public Coordinate(double x) { - this(x, 0, 0, 0); - } - - public Coordinate(double x, double y) { - this(x, y, 0, 0); - } - - public Coordinate(double x, double y, double z) { - this(x, y, z, 0); - } - - public Coordinate(double x, double y, double z, double w) { - this.x = x; - this.y = y; - this.z = z; - this.weight = w; - - } - - - public boolean isWeighted() { - return (weight != 0); - } - - /** - * Check whether any of the coordinate values is NaN. - * - * @return true if the x, y, z or weight is NaN - */ - public boolean isNaN() { - return Double.isNaN(x) || Double.isNaN(y) || Double.isNaN(z) || Double.isNaN(weight); - } - - public Coordinate setX(double x) { - return new Coordinate(x, this.y, this.z, this.weight); - } - - public Coordinate setY(double y) { - return new Coordinate(this.x, y, this.z, this.weight); - } - - public Coordinate setZ(double z) { - return new Coordinate(this.x, this.y, z, this.weight); - } - - public Coordinate setWeight(double weight) { - return new Coordinate(this.x, this.y, this.z, weight); - } - - public Coordinate setXYZ(Coordinate c) { - return new Coordinate(c.x, c.y, c.z, this.weight); - } - - - /** - * Add the coordinate and weight of two coordinates. - * - * @param other the other <code>Coordinate</code> - * @return the sum of the coordinates - */ - public Coordinate add(Coordinate other) { - return new Coordinate(this.x + other.x, this.y + other.y, this.z + other.z, - this.weight + other.weight); - } - - public Coordinate add(double x, double y, double z) { - return new Coordinate(this.x + x, this.y + y, this.z + z, this.weight); - } - - public Coordinate add(double x, double y, double z, double weight) { - return new Coordinate(this.x + x, this.y + y, this.z + z, this.weight + weight); - } - - /** - * Subtract a Coordinate from this Coordinate. The weight of the resulting Coordinate - * is the same as of this Coordinate, the weight of the argument is ignored. - * - * @param other Coordinate to subtract from this. - * @return The result - */ - public Coordinate sub(Coordinate other) { - return new Coordinate(this.x - other.x, this.y - other.y, this.z - other.z, this.weight); - } - - /** - * Subtract the specified values from this Coordinate. The weight of the result - * is the same as the weight of this Coordinate. - * - * @param x x value to subtract - * @param y y value to subtract - * @param z z value to subtract - * @return the result. - */ - public Coordinate sub(double x, double y, double z) { - return new Coordinate(this.x - x, this.y - y, this.z - z, this.weight); - } - - - /** - * Multiply the <code>Coordinate</code> with a scalar. All coordinates and the - * weight are multiplied by the given scalar. - - * @param m Factor to multiply by. - * @return The product. - */ - public Coordinate multiply(double m) { - return new Coordinate(this.x * m, this.y * m, this.z * m, this.weight * m); - } - - /** - * Dot product of two Coordinates, taken as vectors. Equal to - * x1*x2+y1*y2+z1*z2 - * @param other Coordinate to take product with. - * @return The dot product. - */ - public double dot(Coordinate other) { - return this.x * other.x + this.y * other.y + this.z * other.z; - } - - /** - * Dot product of two Coordinates. - */ - public static double dot(Coordinate v1, Coordinate v2) { - return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; - } - - /** - * Distance from the origin to the Coordinate. - */ - public double length() { - if (length < 0) { - length = MathUtil.safeSqrt(x * x + y * y + z * z); - } - return length; - } - - /** - * Square of the distance from the origin to the Coordinate. - */ - public double length2() { - return x * x + y * y + z * z; - } - - - /** - * Return the largest of the absolute values of the coordinates. This can be - * used as a norm of the vector that is faster to calculate than the - * 2-norm. - * - * @return the largest absolute value of (x,y,z) - */ - public double max() { - return MathUtil.max(Math.abs(x), Math.abs(y), Math.abs(z)); - } - - - /** - * Returns a new coordinate which has the same direction from the origin as this - * coordinate but is at a distance of one. If this coordinate is the origin, - * this method throws an <code>IllegalStateException</code>. The weight of the - * coordinate is unchanged. - * - * @return the coordinate normalized to distance one of the origin. - * @throws IllegalStateException if this coordinate is the origin. - */ - public Coordinate normalize() { - double l = length(); - if (l < 0.0000001) { - throw new IllegalStateException("Cannot normalize zero coordinate"); - } - return new Coordinate(x / l, y / l, z / l, weight); - } - - - - - /** - * Weighted average of two coordinates. If either of the weights are positive, - * the result is the weighted average of the coordinates and the weight is the sum - * of the original weights. If the sum of the weights is zero (and especially if - * both of the weights are zero), the result is the unweighted average of the - * coordinates with weight zero. - * <p> - * If <code>other</code> is <code>null</code> then this <code>Coordinate</code> is - * returned. - */ - public Coordinate average(Coordinate other) { - double x, y, z, w; - - if (other == null) - return this; - - w = this.weight + other.weight; - if (Math.abs(w) < MathUtil.pow2(MathUtil.EPSILON)) { - x = (this.x + other.x) / 2; - y = (this.y + other.y) / 2; - z = (this.z + other.z) / 2; - w = 0; - } else { - x = (this.x * this.weight + other.x * other.weight) / w; - y = (this.y * this.weight + other.y * other.weight) / w; - z = (this.z * this.weight + other.z * other.weight) / w; - } - return new Coordinate(x, y, z, w); - } - - - /** - * Tests whether the coordinates are the equal. - * - * @param other Coordinate to compare to. - * @return true if the coordinates are equal (x, y, z and weight) - */ - @Override - public boolean equals(Object other) { - if (!(other instanceof Coordinate)) - return false; - - final Coordinate c = (Coordinate) other; - return (MathUtil.equals(this.x, c.x) && - MathUtil.equals(this.y, c.y) && - MathUtil.equals(this.z, c.z) && MathUtil.equals(this.weight, c.weight)); - } - - /** - * Hash code method compatible with {@link #equals(Object)}. - */ - @Override - public int hashCode() { - return (int) ((x + y + z) * 100000); - } - - - @Override - public String toString() { - if (isWeighted()) - return String.format("(%.3f,%.3f,%.3f,w=%.3f)", x, y, z, weight); - else - return String.format("(%.3f,%.3f,%.3f)", x, y, z); - } - - @Override - public Coordinate clone() { - return new Coordinate( this.x, this.y, this.z, this.weight ); - } - -} diff --git a/core/src/net/sf/openrocket/util/ExpressionParser.java b/core/src/net/sf/openrocket/util/ExpressionParser.java deleted file mode 100644 index d3a3fa62..00000000 --- a/core/src/net/sf/openrocket/util/ExpressionParser.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.sf.openrocket.util; - -import java.text.DecimalFormatSymbols; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; -import de.congrace.exp4j.Calculable; -import de.congrace.exp4j.ExpressionBuilder; - -public class ExpressionParser { - private static final LogHelper log = Application.getLogger(); - - private static final char DECIMAL_SEPARATOR; - private static final char MINUS_SIGN; - static { - DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(); - DECIMAL_SEPARATOR = symbols.getDecimalSeparator(); - MINUS_SIGN = symbols.getMinusSign(); - } - - public double parse(String expression) throws InvalidExpressionException { - - String modified = null; - try { - modified = modify(expression); - ExpressionBuilder builder = new ExpressionBuilder(modified); - Calculable calc = builder.build(); - double n = calc.calculate().getDoubleValue(); - log.debug("Evaluated expression '" + expression + "' (modified='" + modified + "') to " + n); - return n; - } catch (Exception e) { - log.warn("Unable to parse expression '" + expression + "' (modified='" + modified + "')", e); - throw new InvalidExpressionException("Invalid expression: " + expression, e); - } - } - - private String modify(String exp) throws InvalidExpressionException { - - // Normalize digit equivalents, fraction sign, decimal separators and minus sign - char[] chars = exp.toCharArray(); - for (int i = 0; i < chars.length; i++) { - int value = Character.getNumericValue(chars[i]); - if (value >= 0 && value < 10) { - chars[i] = Character.toChars(48 + value)[0]; - } - if (chars[i] == Chars.FRACTION) { - chars[i] = '/'; - } - if (chars[i] == DECIMAL_SEPARATOR || chars[i] == ',') { - chars[i] = '.'; - } - if (chars[i] == MINUS_SIGN) { - chars[i] = '-'; - } - } - exp = String.copyValueOf(chars); - - // Replace fraction equivalents "1 3/4" with "(1+3/4)" - exp = exp.replaceAll("(?<![\\d.])(\\d+)\\s+(\\d+)\\s*/\\s*(\\d+)(?![\\d.])", "($1+$2/$3)"); - - // Disallow spaces between numbers - default is to remove spaces! - if (exp.matches(".*[0-9.]\\s+[0-9.].*")) { - throw new InvalidExpressionException("Expression contains excess space: " + exp); - } - return exp; - } -} diff --git a/core/src/net/sf/openrocket/util/FatalException.java b/core/src/net/sf/openrocket/util/FatalException.java deleted file mode 100644 index b50feef1..00000000 --- a/core/src/net/sf/openrocket/util/FatalException.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.sf.openrocket.util; - -/** - * A superclass for all types of fatal error conditions. This class is - * abstract so only subclasses can be used. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - * @see BugException - * @see ConfigurationException - */ -public abstract class FatalException extends RuntimeException { - - public FatalException() { - } - - public FatalException(String message) { - super(message); - } - - public FatalException(Throwable cause) { - super(cause); - } - - public FatalException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/util/GeodeticComputationStrategy.java b/core/src/net/sf/openrocket/util/GeodeticComputationStrategy.java deleted file mode 100644 index 0721e893..00000000 --- a/core/src/net/sf/openrocket/util/GeodeticComputationStrategy.java +++ /dev/null @@ -1,291 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Locale; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; - -/** - * A strategy that performs computations on WorldCoordinates. - * <p> - * The directions of the coordinate is: - * positive X = EAST - * positive Y = NORTH - * positive Z = UPWARDS - */ -public enum GeodeticComputationStrategy { - - - /** - * Perform computations using a flat Earth approximation. addCoordinate computes the - * location using a direct meters-per-degree scaling and getCoriolisAcceleration always - * returns NUL. - */ - FLAT { - private static final double METERS_PER_DEGREE_LATITUDE = 111325; // "standard figure" - private static final double METERS_PER_DEGREE_LONGITUDE_EQUATOR = 111050; - - - @Override - public WorldCoordinate addCoordinate(WorldCoordinate location, Coordinate delta) { - - double metersPerDegreeLongitude = METERS_PER_DEGREE_LONGITUDE_EQUATOR * Math.cos(location.getLatitudeRad()); - // Limit to 1 meter per degree near poles - metersPerDegreeLongitude = MathUtil.max(metersPerDegreeLongitude, 1); - - double newLat = location.getLatitudeDeg() + delta.y / METERS_PER_DEGREE_LATITUDE; - double newLon = location.getLongitudeDeg() + delta.x / metersPerDegreeLongitude; - double newAlt = location.getAltitude() + delta.z; - - return new WorldCoordinate(newLat, newLon, newAlt); - } - - @Override - public Coordinate getCoriolisAcceleration(WorldCoordinate location, Coordinate velocity) { - return Coordinate.NUL; - } - }, - - /** - * Perform geodetic computations with a spherical Earch approximation. - */ - SPHERICAL { - - @Override - public WorldCoordinate addCoordinate(WorldCoordinate location, Coordinate delta) { - double newAlt = location.getAltitude() + delta.z; - - // bearing (in radians, clockwise from north); - // d/R is the angular distance (in radians), where d is the distance traveled and R is the earth's radius - double d = MathUtil.hypot(delta.x, delta.y); - - // Check for zero movement before computing bearing - if (MathUtil.equals(d, 0)) { - return new WorldCoordinate(location.getLatitudeDeg(), location.getLongitudeDeg(), newAlt); - } - - double bearing = Math.atan2(delta.x, delta.y); - - // Calculate the new lat and lon - double newLat, newLon; - double sinLat = Math.sin(location.getLatitudeRad()); - double cosLat = Math.cos(location.getLatitudeRad()); - double sinDR = Math.sin(d / WorldCoordinate.REARTH); - double cosDR = Math.cos(d / WorldCoordinate.REARTH); - - newLat = Math.asin(sinLat * cosDR + cosLat * sinDR * Math.cos(bearing)); - newLon = location.getLongitudeRad() + Math.atan2(Math.sin(bearing) * sinDR * cosLat, cosDR - sinLat * Math.sin(newLat)); - - if (Double.isNaN(newLat) || Double.isNaN(newLon)) { - throw new BugException("addCoordinate resulted in NaN location: location=" + location + " delta=" + delta - + " newLat=" + newLat + " newLon=" + newLon); - } - - return new WorldCoordinate(Math.toDegrees(newLat), Math.toDegrees(newLon), newAlt); - } - - @Override - public Coordinate getCoriolisAcceleration(WorldCoordinate location, Coordinate velocity) { - return computeCoriolisAcceleration(location, velocity); - } - - }, - - /** - * Perform geodetic computations on a WGS84 reference ellipsoid using Vincenty Direct Solution. - */ - WGS84 { - - @Override - public WorldCoordinate addCoordinate(WorldCoordinate location, Coordinate delta) { - double newAlt = location.getAltitude() + delta.z; - - // bearing (in radians, clockwise from north); - // d/R is the angular distance (in radians), where d is the distance traveled and R is the earth's radius - double d = MathUtil.hypot(delta.x, delta.y); - - // Check for zero movement before computing bearing - if (MathUtil.equals(d, 0)) { - return new WorldCoordinate(location.getLatitudeDeg(), location.getLongitudeDeg(), newAlt); - } - - double bearing = Math.atan(delta.x / delta.y); - if (delta.y < 0) - bearing = bearing + Math.PI; - - // Calculate the new lat and lon - double newLat, newLon; - double ret[] = dirct1(location.getLatitudeRad(), location.getLongitudeRad(), bearing, d, 6378137, 1.0 / 298.25722210088); - newLat = ret[0]; - newLon = ret[1]; - - if (Double.isNaN(newLat) || Double.isNaN(newLon)) { - throw new BugException("addCoordinate resulted in NaN location: location=" + location + " delta=" + delta - + " newLat=" + newLat + " newLon=" + newLon); - } - - return new WorldCoordinate(Math.toDegrees(newLat), Math.toDegrees(newLon), newAlt); - } - - @Override - public Coordinate getCoriolisAcceleration(WorldCoordinate location, Coordinate velocity) { - return computeCoriolisAcceleration(location, velocity); - } - }; - - - private static final Translator trans = Application.getTranslator(); - - private static final double PRECISION_LIMIT = 0.5e-13; - - - /** - * Return the name of this geodetic computation method. - */ - public String getName() { - return trans.get(name().toLowerCase(Locale.ENGLISH) + ".name"); - } - - /** - * Return a description of the geodetic computation methods. - */ - public String getDescription() { - return trans.get(name().toLowerCase(Locale.ENGLISH) + ".desc"); - } - - @Override - public String toString() { - return getName(); - } - - - /** - * Add a cartesian movement coordinate to a WorldCoordinate. - */ - public abstract WorldCoordinate addCoordinate(WorldCoordinate location, Coordinate delta); - - - /** - * Compute the coriolis acceleration at a specified WorldCoordinate and velocity. - */ - public abstract Coordinate getCoriolisAcceleration(WorldCoordinate location, Coordinate velocity); - - - - - - private static Coordinate computeCoriolisAcceleration(WorldCoordinate latlon, Coordinate velocity) { - - double sinlat = Math.sin(latlon.getLatitudeRad()); - double coslat = Math.cos(latlon.getLatitudeRad()); - - double v_n = velocity.y; - double v_e = -1 * velocity.x; - double v_u = velocity.z; - - // Not exactly sure why I have to reverse the x direction, but this gives the precession in the - // correct direction (e.g, flying north in northern hemisphere should cause defection to the east (+ve x)) - // All the directions are very confusing because they are tied to the wind direction (to/from?), in which - // +ve x or east according to WorldCoordinate is what everything is relative to. - // The directions of everything need so thought, ideally the wind direction and launch rod should be - // able to be set independently and in terms of bearing with north == +ve y. - - Coordinate coriolis = new Coordinate(2.0 * WorldCoordinate.EROT * (v_n * sinlat - v_u * coslat), - 2.0 * WorldCoordinate.EROT * (-1.0 * v_e * sinlat), - 2.0 * WorldCoordinate.EROT * (v_e * coslat) - ); - return coriolis; - } - - - - // ******************************************************************** // - // The Vincenty Direct Solution. - // Code from GeoConstants.java, Ian Cameron Smith, GPL - // ******************************************************************** // - - /** - * Solution of the geodetic direct problem after T. Vincenty. - * Modified Rainsford's method with Helmert's elliptical terms. - * Effective in any azimuth and at any distance short of antipodal. - * - * Programmed for the CDC-6600 by lcdr L. Pfeifer, NGS Rockville MD, - * 20 Feb 1975. - * - * @param glat1 The latitude of the starting point, in radians, - * positive north. - * @param glon1 The latitude of the starting point, in radians, - * positive east. - * @param azimuth The azimuth to the desired location, in radians - * clockwise from north. - * @param dist The distance to the desired location, in meters. - * @param axis The semi-major axis of the reference ellipsoid, - * in meters. - * @param flat The flattening of the reference ellipsoid. - * @return An array containing the latitude and longitude - * of the desired point, in radians, and the - * azimuth back from that point to the starting - * point, in radians clockwise from north. - */ - private static double[] dirct1(double glat1, double glon1, - double azimuth, double dist, - double axis, double flat) { - double r = 1.0 - flat; - - double tu = r * Math.sin(glat1) / Math.cos(glat1); - - double sf = Math.sin(azimuth); - double cf = Math.cos(azimuth); - - double baz = 0.0; - - if (cf != 0.0) - baz = Math.atan2(tu, cf) * 2.0; - - double cu = 1.0 / Math.sqrt(tu * tu + 1.0); - double su = tu * cu; - double sa = cu * sf; - double c2a = -sa * sa + 1.0; - - double x = Math.sqrt((1.0 / r / r - 1.0) * c2a + 1.0) + 1.0; - x = (x - 2.0) / x; - double c = 1.0 - x; - c = (x * x / 4.0 + 1) / c; - double d = (0.375 * x * x - 1.0) * x; - tu = dist / r / axis / c; - double y = tu; - - double sy, cy, cz, e; - do { - sy = Math.sin(y); - cy = Math.cos(y); - cz = Math.cos(baz + y); - e = cz * cz * 2.0 - 1.0; - - c = y; - x = e * cy; - y = e + e - 1.0; - y = (((sy * sy * 4.0 - 3.0) * y * cz * d / 6.0 + x) * - d / 4.0 - cz) * sy * d + tu; - } while (Math.abs(y - c) > PRECISION_LIMIT); - - baz = cu * cy * cf - su * sy; - c = r * Math.sqrt(sa * sa + baz * baz); - d = su * cy + cu * sy * cf; - double glat2 = Math.atan2(d, c); - c = cu * cy - su * sy * cf; - x = Math.atan2(sy * sf, c); - c = ((-3.0 * c2a + 4.0) * flat + 4.0) * c2a * flat / 16.0; - d = ((e * cy * c + cz) * sy * c + y) * sa; - double glon2 = glon1 + x - (1.0 - c) * d * flat; - baz = Math.atan2(sa, baz) + Math.PI; - - double[] ret = new double[3]; - ret[0] = glat2; - ret[1] = glon2; - ret[2] = baz; - return ret; - } - - -} diff --git a/core/src/net/sf/openrocket/util/Inertia.java b/core/src/net/sf/openrocket/util/Inertia.java deleted file mode 100644 index f7d65c41..00000000 --- a/core/src/net/sf/openrocket/util/Inertia.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.util; - -import static net.sf.openrocket.util.MathUtil.pow2; -public final class Inertia { - - private Inertia() { - } - - - /** - * Return the rotational unit moment of inertia of a solid cylinder. - * - * @param radius the radius of the cylinder. - */ - public static double filledCylinderRotational(double radius) { - return pow2(radius) / 2; - } - - /** - * Return the longitudinal unit moment of inertia of a solid cylinder, - * relative to the midpoint lengthwise. - * - * @param radius the radius of the cylinder. - * @param length the total length of the cylinder (reference at midpoint) - */ - public static double filledCylinderLongitudinal(double radius, double length) { - return (3*pow2(radius) + pow2(length))/12; - } - - - /** - * Return the unit moment of inertia that is shifted from the CG of an object - * by a specified distance. The rotation axis are parallel. - * - * @param cgInertia the unit moment of inertia through the CG of the object - * @param distance the distance to shift the rotation axis - */ - public static double shift(double cgInertia, double distance) { - return cgInertia + pow2(distance); - } - -} diff --git a/core/src/net/sf/openrocket/util/InvalidExpressionException.java b/core/src/net/sf/openrocket/util/InvalidExpressionException.java deleted file mode 100644 index 118cefe0..00000000 --- a/core/src/net/sf/openrocket/util/InvalidExpressionException.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.util; - -/** - * Exception indicating an invalid expression. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class InvalidExpressionException extends Exception { - - public InvalidExpressionException(String message) { - super(message); - } - - public InvalidExpressionException(Throwable cause) { - super(cause); - } - - public InvalidExpressionException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/core/src/net/sf/openrocket/util/Invalidatable.java b/core/src/net/sf/openrocket/util/Invalidatable.java deleted file mode 100644 index 94499894..00000000 --- a/core/src/net/sf/openrocket/util/Invalidatable.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.sf.openrocket.util; - -/** - * An object that can be invalidated (in some sense of the word). After calling the - * invalidate method the object should not be used any more and it may enforce - * disusage for certain methods. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public interface Invalidatable { - - /** - * Invalidate this object. - */ - public void invalidate(); - -} diff --git a/core/src/net/sf/openrocket/util/Invalidator.java b/core/src/net/sf/openrocket/util/Invalidator.java deleted file mode 100644 index 9e40c102..00000000 --- a/core/src/net/sf/openrocket/util/Invalidator.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.sf.openrocket.util; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.startup.Application; - -/** - * A class that performs object invalidation functions. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Invalidator implements Invalidatable { - private static final boolean USE_CHECKS = Application.useSafetyChecks(); - - private static final LogHelper log = Application.getLogger(); - - private final Object monitorable; - private TraceException invalidated = null; - - - /** - * Sole constructor. The parameter is used when writing error messages, and - * is not referenced otherwise. - * - * @param monitorable the object this invalidator is monitoring (may be null or a descriptive string) - */ - public Invalidator(Object monitorable) { - this.monitorable = monitorable; - } - - - /** - * Check whether the object has been invalidated. Depending on the parameter either - * a BugException is thrown or a warning about the object access is logged. - * - * @param throwException whether to throw an exception or log a warning. - * @return <code>true</code> when the object has not been invalidated, <code>false</code> if it has - * @throws BugException if the object has been invalidated and <code>throwException</code> is true. - */ - public boolean check(boolean throwException) { - if (invalidated != null) { - if (throwException) { - throw new BugException(monitorable + ": This object has been invalidated", invalidated); - } else { - log.warn(1, monitorable + ": This object has been invalidated", - new TraceException("Usage was attempted here", invalidated)); - } - return false; - } - return true; - } - - - /** - * Check whether the object has been invalidated. - * @return <code>true</code> if the object has been invalidated, <code>false</code> otherwise. - */ - public boolean isInvalidated() { - return invalidated != null; - } - - - @Override - public void invalidate() { - if (USE_CHECKS) { - if (invalidated != null) { - log.warn(1, monitorable + ": This object has already been invalidated, ignoring", invalidated); - } - invalidated = new TraceException("Invalidation occurred here"); - } - } - -} diff --git a/core/src/net/sf/openrocket/util/JarUtil.java b/core/src/net/sf/openrocket/util/JarUtil.java deleted file mode 100644 index 545cfa58..00000000 --- a/core/src/net/sf/openrocket/util/JarUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.sf.openrocket.util; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.CodeSource; - -import net.sf.openrocket.database.Database; - -public class JarUtil { - - /** - * Return the a File object pointing to the JAR file that this class belongs to, - * or <code>null</code> if it cannot be found. - * - * @return a File object of the current Java archive, or <code>null</code> - */ - public static File getCurrentJarFile() { - // Find the jar file this class is contained in - - URL jarUrl = null; - CodeSource codeSource; - try { - codeSource = new URL("rsrc:.").openConnection().getClass().getProtectionDomain().getCodeSource(); - } catch (Throwable e) { - codeSource = Database.class.getProtectionDomain().getCodeSource(); - } - - if (codeSource != null) - jarUrl = codeSource.getLocation(); - - if (jarUrl == null) { - return null; - } - - File file = urlToFile(jarUrl); - if (file.isFile()) - return file; - return null; - } - - - - public static File urlToFile(URL url) { - URI uri; - try { - uri = url.toURI(); - } catch (URISyntaxException e) { - try { - uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), - url.getPort(), url.getPath(), url.getQuery(), url.getRef()); - } catch (URISyntaxException e1) { - throw new IllegalArgumentException("Broken URL: " + url); - } - } - return new File(uri); - } - - -} diff --git a/core/src/net/sf/openrocket/util/LimitedInputStream.java b/core/src/net/sf/openrocket/util/LimitedInputStream.java deleted file mode 100644 index 4e264fa1..00000000 --- a/core/src/net/sf/openrocket/util/LimitedInputStream.java +++ /dev/null @@ -1,83 +0,0 @@ -package net.sf.openrocket.util; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * A filtering InputStream that limits the number of bytes that can be - * read from a stream. This can be used to enforce security, so that overlong - * input is ignored. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class LimitedInputStream extends FilterInputStream { - - private int remaining; - - public LimitedInputStream(InputStream is, int limit) { - super(is); - this.remaining = limit; - } - - - @Override - public int available() throws IOException { - int available = super.available(); - return Math.min(available, remaining); - } - - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (remaining <= 0) - return -1; - - int result = super.read(b, off, Math.min(len, remaining)); - if (result >= 0) - remaining -= result; - return result; - } - - - @Override - public long skip(long n) throws IOException { - if (n > remaining) - n = remaining; - long result = super.skip(n); - remaining -= result; - return result; - } - - - @Override - public int read() throws IOException { - if (remaining <= 0) - return -1; - - int result = super.read(); - if (result >= 0) - remaining--; - return result; - } - - - - // Disable mark support - - @Override - public void mark(int readlimit) { - - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public synchronized void reset() throws IOException { - throw new IOException("mark/reset not supported"); - } - -} diff --git a/core/src/net/sf/openrocket/util/LineStyle.java b/core/src/net/sf/openrocket/util/LineStyle.java deleted file mode 100644 index fc2b4fdc..00000000 --- a/core/src/net/sf/openrocket/util/LineStyle.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Arrays; - -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.startup.Application; - -/** - * An enumeration of line styles. The line styles are defined by an array of - * floats suitable for <code>BasicStroke</code>. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - -public enum LineStyle { - - - //// Solid - SOLID("LineStyle.Solid", new float[] { 10f, 0f }), - //// Dashed - DASHED("LineStyle.Dashed", new float[] { 6f, 4f }), - //// Dotted - DOTTED("LineStyle.Dotted", new float[] { 2f, 3f }), - //// Dash-dotted - DASHDOT("LineStyle.Dash-dotted", new float[] { 8f, 3f, 2f, 3f }); - - private static final Translator trans = Application.getTranslator(); - private final String name; - private final float[] dashes; - - LineStyle(String name, float[] dashes) { - this.name = name; - this.dashes = dashes; - } - - public float[] getDashes() { - return Arrays.copyOf(dashes, dashes.length); - } - - @Override - public String toString() { - return trans.get(name); - } -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/util/LinearInterpolator.java b/core/src/net/sf/openrocket/util/LinearInterpolator.java deleted file mode 100644 index e16726bb..00000000 --- a/core/src/net/sf/openrocket/util/LinearInterpolator.java +++ /dev/null @@ -1,154 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Iterator; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -public class LinearInterpolator implements Cloneable { - - private TreeMap<Double, Double> sortMap = new TreeMap<Double,Double>(); - - /** - * Construct a <code>LinearInterpolator</code> with no points. Some points must be - * added using {@link #addPoints(double[], double[])} before using the interpolator. - */ - public LinearInterpolator() { - } - - /** - * Construct a <code>LinearInterpolator</code> with the given points. - * - * @param x the x-coordinates of the points. - * @param y the y-coordinates of the points. - * @throws IllegalArgumentException if the lengths of <code>x</code> and <code>y</code> - * are not equal. - * @see #addPoints(double[], double[]) - */ - public LinearInterpolator(double[] x, double[] y) { - addPoints(x,y); - } - - public LinearInterpolator(List<Double> x, List<Double> y) { - addPoints(x,y); - } - - /** - * Add the point to the linear interpolation. - * - * @param x the x-coordinate of the point. - * @param y the y-coordinate of the point. - */ - public void addPoint(double x, double y) { - sortMap.put(x, y); - } - - /** - * Add the points to the linear interpolation. - * - * @param x the x-coordinates of the points. - * @param y the y-coordinates of the points. - * @throws IllegalArgumentException if the lengths of <code>x</code> and <code>y</code> - * are not equal. - */ - public void addPoints(double[] x, double[] y) { - if (x.length != y.length) { - throw new IllegalArgumentException("Array lengths do not match, x="+x.length + - " y="+y.length); - } - for (int i=0; i < x.length; i++) { - sortMap.put(x[i],y[i]); - } - } - - public void addPoints(List<Double> x, List<Double> y){ - if (x.size() != y.size()) { - throw new IllegalArgumentException("Array lengths do not match, x="+x.size() + - " y="+y.size()); - } - for (int i=0; i < x.size(); i++) { - sortMap.put( (Double) x.toArray()[i], (Double) y.toArray()[i]); - } - } - - - public double getValue(double x) { - double x1, x2; - Double y1, y2; - // Froyo does not support floorEntry, firstEntry or higherEntry. We instead have to - // resort to using other more awkward methods. - - y1 = sortMap.get(x); - - if ( y1 != null ) { - // Wow, x was a key in the map. Such luck. - return y1.doubleValue(); - } - - // we now know that x is not in the map, so we need to find the lower and higher keys. - - // let's just make certain that our map is not empty. - if ( sortMap.isEmpty() ) { - throw new IllegalStateException("No points added yet to the interpolator."); - } - - // firstKey in the map - cannot be null since the map is not empty. - Double firstKey = sortMap.firstKey(); - - // x is smaller than the first entry in the map. - if ( x < firstKey.doubleValue() ) { - y1 = sortMap.get(firstKey); - return y1.doubleValue(); - } - - // floor key is the largest key smaller than x - since we have at least one key, - // and x>=firstKey, we know that floorKey != null. - Double floorKey = sortMap.subMap(firstKey, x).lastKey(); - - x1 = floorKey.doubleValue(); - y1 = sortMap.get(floorKey); - - // Now we need to find the key that is greater or equal to x - SortedMap<Double,Double> tailMap = sortMap.tailMap(x); - - // Check if x is bigger than all the entries. - if ( tailMap.isEmpty() ) { - return y1.doubleValue(); - } - Double ceilKey = tailMap.firstKey(); - - // Check if x is bigger than all the entries. - if ( ceilKey == null ) { - return y1.doubleValue(); - } - - x2 = ceilKey.doubleValue(); - y2 = sortMap.get(ceilKey); - - return (x - x1)/(x2-x1) * (y2-y1) + y1; - } - - - public double[] getXPoints() { - double[] x = new double[sortMap.size()]; - Iterator<Double> iter = sortMap.keySet().iterator(); - for (int i=0; iter.hasNext(); i++) { - x[i] = iter.next(); - } - return x; - } - - - @SuppressWarnings("unchecked") - @Override - public LinearInterpolator clone() { - try { - LinearInterpolator other = (LinearInterpolator)super.clone(); - other.sortMap = (TreeMap<Double,Double>)this.sortMap.clone(); - return other; - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException?!",e); - } - } - -} diff --git a/core/src/net/sf/openrocket/util/ListenerList.java b/core/src/net/sf/openrocket/util/ListenerList.java deleted file mode 100644 index b4f4c02b..00000000 --- a/core/src/net/sf/openrocket/util/ListenerList.java +++ /dev/null @@ -1,264 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Iterator; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.startup.Application; - -/** - * A list of listeners of a specific type. This class contains various utility, - * safety and debugging methods for handling listeners. - * <p> - * Note that unlike normal listener implementations, this list does NOT allow the - * exact same listener (equality using ==) twice. While adding a listener twice to - * a event source would in principle be valid, in practice it's most likely a bug. - * For example the Swing implementation Sun JRE contains such bugs. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - * @param <T> the type of the listeners. - */ -public class ListenerList<T> implements Invalidatable, Iterable<T> { - private static final LogHelper log = Application.getLogger(); - - private final ArrayList<ListenerData<T>> listeners = new ArrayList<ListenerData<T>>(); - private final TraceException instantiationLocation; - - private TraceException invalidated = null; - - - /** - * Sole contructor. - */ - public ListenerList() { - this.instantiationLocation = new TraceException(1, 1); - } - - - /** - * Adds the specified listener to this list. The listener is not added if it - * already is in the list (checked by the equality operator ==). This method throws - * a BugException if {@link #invalidate()} has been called. - * - * @param listener the listener to add. - * @return whether the listeners was actually added to the list. - * @throws BugException if this listener list has been invalidated. - */ - public boolean addListener(T listener) { - checkState(true); - - ListenerData<T> data = new ListenerData<T>(listener); - if (listeners.contains(data)) { - log.warn(1, "Attempting to add duplicate listener " + listener); - return false; - } - listeners.add(data); - return true; - } - - - /** - * Remove the specified listener from the list. The listener is removed based on the - * quality operator ==, not by the equals() method. - * - * @param listener the listener to remove. - * @return whether the listener was actually removed. - */ - public boolean removeListener(T listener) { - checkState(false); - - Iterator<ListenerData<T>> iterator = listeners.iterator(); - while (iterator.hasNext()) { - if (iterator.next().listener == listener) { - iterator.remove(); - log.verbose(1, "Removing listener " + listener); - return true; - } - } - log.info(1, "Attempting to remove non-existant listener " + listener); - return false; - } - - - /** - * Return the number of listeners in this list. - */ - public int getListenerCount() { - return listeners.size(); - } - - - /** - * Return an iterator that iterates of the listeners. This iterator is backed by - * a copy of the iterator list, so {@link #addListener(Object)} and {@link #removeListener(Object)} - * may be called while iterating the list without effect on the iteration. The returned - * iterator does not support the {@link Iterator#remove()} method. - */ - @Override - public Iterator<T> iterator() { - checkState(false); - return new ListenerDataIterator(); - } - - /** - * Return the instantiation location of this listener list. - * @return the location where this listener list was instantiated. - */ - public TraceException getInstantiationLocation() { - return instantiationLocation; - } - - - /** - * Invalidate this listener list. Invalidation removes all listeners from the list. - * After invalidation {@link #addListener(Object)} will throw an exception, the other - * methods produce a warning log message. - */ - @Override - public void invalidate() { - this.invalidated = new TraceException("Invalidation occurred at this point"); - if (!listeners.isEmpty()) { - log.info("Invalidating " + this + " while still having listeners " + listeners); - } - listeners.clear(); - } - - - public boolean isInvalidated() { - return this.invalidated != null; - } - - - private void checkState(boolean error) { - if (this.invalidated != null) { - if (error) { - throw new BugException(this + ": this ListenerList has been invalidated", invalidated); - } else { - log.warn(1, this + ": this ListenerList has been invalidated", - new TraceException("ListenerList was attempted to be used here", invalidated)); - } - } - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("ListenerList["); - - if (this.invalidated != null) { - sb.append("INVALIDATED]"); - return sb.toString(); - } - - if (listeners.isEmpty()) { - sb.append("empty"); - } else { - boolean first = true; - for (ListenerData<T> l : listeners) { - if (!first) { - sb.append("; "); - } - first = false; - sb.append(l); - } - } - sb.append("]"); - return sb.toString(); - } - - - /** - * A class containing data about a listener. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - * @param <T> the listener type - */ - public static class ListenerData<T> { - private final T listener; - private final long addTimestamp; - private final TraceException addLocation; - private long accessTimestamp; - - /** - * Sole constructor. - */ - private ListenerData(T listener) { - if (listener == null) { - throw new NullPointerException("listener is null"); - } - this.listener = listener; - this.addTimestamp = System.currentTimeMillis(); - this.accessTimestamp = this.addTimestamp; - this.addLocation = new TraceException("Listener " + listener + " add position"); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!(obj instanceof ListenerData)) - return false; - ListenerData<?> other = (ListenerData<?>) obj; - return this.listener == other.listener; - } - - @Override - public int hashCode() { - return listener.hashCode(); - } - - /** - * Return the listener. - */ - public T getListener() { - return listener; - } - - /** - * Return the millisecond timestamp when this listener was added to the - * listener list. - */ - public long getAddTimestamp() { - return addTimestamp; - } - - /** - * Return the location where this listener was added to the listener list. - */ - public TraceException getAddLocation() { - return addLocation; - } - - /** - * Return the millisecond timestamp when this listener was last accessed through - * the listener list iterator. - */ - public long getAccessTimestamp() { - return accessTimestamp; - } - } - - - private class ListenerDataIterator implements Iterator<T> { - private final Iterator<ListenerData<T>> iterator = listeners.clone().iterator(); - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - ListenerData<T> data = iterator.next(); - data.accessTimestamp = System.currentTimeMillis(); - return data.listener; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported"); - } - } - -} diff --git a/core/src/net/sf/openrocket/util/MathUtil.java b/core/src/net/sf/openrocket/util/MathUtil.java deleted file mode 100644 index 09a31689..00000000 --- a/core/src/net/sf/openrocket/util/MathUtil.java +++ /dev/null @@ -1,367 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -public class MathUtil { - private static final LogHelper log = Application.getLogger(); - - public static final double EPSILON = 0.00000001; // 10mm^3 in m^3 - - /** - * The square of x (x^2). On Sun's JRE using this method is as fast as typing x*x. - * @param x x - * @return x^2 - */ - public static double pow2(double x) { - return x * x; - } - - /** - * The cube of x (x^3). - * @param x x - * @return x^3 - */ - public static double pow3(double x) { - return x * x * x; - } - - public static double pow4(double x) { - return (x * x) * (x * x); - } - - /** - * Clamps the value x to the range min - max. - * @param x Original value. - * @param min Minimum value to return. - * @param max Maximum value to return. - * @return The clamped value. - */ - public static double clamp(double x, double min, double max) { - if (x < min) - return min; - if (x > max) - return max; - return x; - } - - public static float clamp(float x, float min, float max) { - if (x < min) - return min; - if (x > max) - return max; - return x; - } - - public static int clamp(int x, int min, int max) { - if (x < min) - return min; - if (x > max) - return max; - return x; - } - - - /** - * Maps a value from one value range to another. - * - * @param value the value to map. - * @param fromMin the minimum of the starting range. - * @param fromMax the maximum of the starting range. - * @param toMin the minimum of the destination range. - * @param toMax the maximum of the destination range. - * @return the mapped value. - * @throws IllegalArgumentException if fromMin == fromMax, but toMin != toMax. - */ - public static double map(double value, double fromMin, double fromMax, - double toMin, double toMax) { - if (equals(toMin, toMax)) - return toMin; - if (equals(fromMin, fromMax)) { - throw new IllegalArgumentException("from range is singular and to range is not: " + - "value=" + value + " fromMin=" + fromMin + " fromMax=" + fromMax + - "toMin=" + toMin + " toMax=" + toMax); - } - return (value - fromMin) / (fromMax - fromMin) * (toMax - toMin) + toMin; - } - - - /** - * Maps a coordinate from one value range to another. - * - * @param value the value to map. - * @param fromMin the minimum of the starting range. - * @param fromMax the maximum of the starting range. - * @param toMin the minimum coordinate of the destination; - * @param toMax the maximum coordinate of the destination; - * @return the mapped value. - * @throws IllegalArgumentException if fromMin == fromMax, but toMin != toMax. - */ - public static Coordinate map(double value, double fromMin, double fromMax, - Coordinate toMin, Coordinate toMax) { - if (toMin.equals(toMax)) - return toMin; - if (equals(fromMin, fromMax)) { - throw new IllegalArgumentException("from range is singular and to range is not: " + - "value=" + value + " fromMin=" + fromMin + " fromMax=" + fromMax + - "toMin=" + toMin + " toMax=" + toMax); - } - double a = (value - fromMin) / (fromMax - fromMin); - return toMax.multiply(a).add(toMin.multiply(1 - a)); - } - - - /** - * Compute the minimum of two values. This is performed by direct comparison. - * However, if one of the values is NaN and the other is not, the non-NaN value is - * returned. - */ - public static double min(double x, double y) { - if (Double.isNaN(y)) - return x; - return (x < y) ? x : y; - } - - /** - * Compute the maximum of two values. This is performed by direct comparison. - * However, if one of the values is NaN and the other is not, the non-NaN value is - * returned. - */ - public static double max(double x, double y) { - if (Double.isNaN(x)) - return y; - return (x < y) ? y : x; - } - - /** - * Compute the minimum of three values. This is performed by direct comparison. - * However, if one of the values is NaN and the other is not, the non-NaN value is - * returned. - */ - public static double min(double x, double y, double z) { - if (x < y || Double.isNaN(y)) { - return min(x, z); - } else { - return min(y, z); - } - } - - - - /** - * Compute the minimum of three values. This is performed by direct comparison. - * However, if one of the values is NaN and the other is not, the non-NaN value is - * returned. - */ - public static double min(double w, double x, double y, double z) { - return min(min(w, x), min(y, z)); - } - - - /** - * Compute the maximum of three values. This is performed by direct comparison. - * However, if one of the values is NaN and the other is not, the non-NaN value is - * returned. - */ - public static double max(double x, double y, double z) { - if (x > y || Double.isNaN(y)) { - return max(x, z); - } else { - return max(y, z); - } - } - - /** - * Calculates the hypotenuse <code>sqrt(x^2+y^2)</code>. This method is SIGNIFICANTLY - * faster than <code>Math.hypot(x,y)</code>. - */ - public static double hypot(double x, double y) { - return Math.sqrt(x * x + y * y); - } - - /** - * Reduce the angle x to the range 0 - 2*PI. - * @param x Original angle. - * @return The equivalent angle in the range 0 ... 2*PI. - */ - public static double reduce360(double x) { - double d = Math.floor(x / (2 * Math.PI)); - return x - d * 2 * Math.PI; - } - - /** - * Reduce the angle x to the range -PI - PI. - * - * Either -PI and PI might be returned, depending on the rounding function. - * - * @param x Original angle. - * @return The equivalent angle in the range -PI ... PI. - */ - public static double reduce180(double x) { - double d = Math.rint(x / (2 * Math.PI)); - return x - d * 2 * Math.PI; - } - - - /** - * Return the square root of a value. If the value is negative, zero is returned. - * This is safer in cases where rounding errors might make a value slightly negative. - * - * @param d the value of which the square root is to be taken. - * @return the square root of the value. - */ - public static double safeSqrt(double d) { - if (d < 0) { - if (d < 0.01) { - log.warn(1, "Attempting to compute sqrt(" + d + ")"); - } - return 0; - } - return Math.sqrt(d); - } - - - - public static boolean equals(double a, double b) { - double absb = Math.abs(b); - - if (absb < EPSILON / 2) { - // Near zero - return Math.abs(a) < EPSILON / 2; - } - return Math.abs(a - b) < EPSILON * absb; - } - - - /** - * Return the sign of the number. This corresponds to Math.signum, but ignores - * the special cases of zero and NaN. The value returned for those is arbitrary. - * <p> - * This method is about 4 times faster than Math.signum(). - * - * @param x the checked value. - * @return -1.0 if x<0; 1.0 if x>0; otherwise either -1.0 or 1.0. - */ - public static double sign(double x) { - return (x < 0) ? -1.0 : 1.0; - } - - /* Math.abs() is about 3x as fast as this: - - public static double abs(double x) { - return (x<0) ? -x : x; - } - */ - - - public static double average(Collection<? extends Number> values) { - if (values.isEmpty()) { - return Double.NaN; - } - - double avg = 0.0; - int count = 0; - for (Number n : values) { - avg += n.doubleValue(); - count++; - } - return avg / count; - } - - public static double stddev(Collection<? extends Number> values) { - if (values.size() < 2) { - return Double.NaN; - } - - double avg = average(values); - double stddev = 0.0; - int count = 0; - for (Number n : values) { - stddev += pow2(n.doubleValue() - avg); - count++; - } - stddev = Math.sqrt(stddev / (count - 1)); - return stddev; - } - - public static double median(Collection<? extends Number> values) { - if (values.isEmpty()) { - return Double.NaN; - } - - List<Number> sorted = new ArrayList<Number>(values); - Collections.sort(sorted, new Comparator<Number>() { - @Override - public int compare(Number o1, Number o2) { - return Double.compare(o1.doubleValue(), o2.doubleValue()); - } - }); - - int n = sorted.size(); - if (n % 2 == 0) { - return (sorted.get(n / 2).doubleValue() + sorted.get(n / 2 - 1).doubleValue()) / 2; - } else { - return sorted.get(n / 2).doubleValue(); - } - } - - /** - * Use interpolation to determine the value of the function at point t. - * Current implementation uses simple linear interpolation. The domain - * and range lists must include the same number of values, t must be within - * the domain, and the domain list must be sorted. - * - * @param domain list containing domain samples - * @param range list of corresponding range samples - * @param t domain value at which to interpolate - * @return returns Double.NaN if either list is null or empty or different size, or if t is outsize the domain. - */ - public static double interpolate( List<Double> domain, List<Double> range, double t ) { - - if ( domain == null || range == null || domain.size() != range.size() ) { - return Double.NaN; - } - - int length = domain.size(); - if ( length <= 1 || t < domain.get(0) || t > domain.get( length-1 ) ) { - return Double.NaN; - } - - // Look for the index of the right end point. - int right = 1; - while( t > domain.get(right) ) { - right ++; - } - int left = right -1; - - // Points are: - - double deltax = domain.get(right) - domain.get(left); - double deltay = range.get(right) - range.get(left); - - // For numerical stability, if deltax is small, - if ( Math.abs(deltax) < EPSILON ) { - if ( deltay < -1.0 * EPSILON ) { - // return neg infinity if deltay is negative - return Double.NEGATIVE_INFINITY; - } - else if ( deltay > EPSILON ) { - // return infinity if deltay is large - return Double.POSITIVE_INFINITY; - } else { - // otherwise return 0 - return 0.0d; - } - } - - return range.get(left) + ( t - domain.get(left) ) * deltay / deltax; - - } - -} diff --git a/core/src/net/sf/openrocket/util/MemoryManagement.java b/core/src/net/sf/openrocket/util/MemoryManagement.java deleted file mode 100644 index 7b55200b..00000000 --- a/core/src/net/sf/openrocket/util/MemoryManagement.java +++ /dev/null @@ -1,194 +0,0 @@ -package net.sf.openrocket.util; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * A class that performs certain memory-management operations for debugging purposes. - * For example, complex objects that are being discarded and that should be garbage-collectable - * (such as dialog windows) should be registered for monitoring by calling - * {@link #collectable(Object)}. This will allow monitoring whether the object really is - * garbage-collected or whether it is retained in memory due to a memory leak. - * Only complex objects should be registered due to the overhead of the monitoring. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public final class MemoryManagement { - private static final LogHelper log = Application.getLogger(); - - /** Purge cleared references every this many calls to {@link #collectable(Object)} */ - private static final int PURGE_CALL_COUNT = 1000; - - - /** - * Storage of the objects. This is basically a mapping from the objects (using weak references) - * to - */ - private static List<MemoryData> objects = new LinkedList<MemoryData>(); - private static int collectableCallCount = 0; - - - private static List<WeakReference<ListenerList<?>>> listenerLists = new LinkedList<WeakReference<ListenerList<?>>>(); - private static int listenerCallCount = 0; - - - private MemoryManagement() { - } - - - /** - * Mark an object that should be garbage-collectable by the GC. This class will monitor - * whether the object actually gets garbage-collected or not by holding a weak reference - * to the object. - * - * @param o the object to monitor. - */ - public static synchronized void collectable(Object o) { - if (o == null) { - throw new IllegalArgumentException("object is null"); - } - log.debug("Adding object into collectable list: " + o); - objects.add(new MemoryData(o)); - collectableCallCount++; - if (collectableCallCount % PURGE_CALL_COUNT == 0) { - purgeCollectables(); - } - } - - - /** - * Return a list of MemoryData objects corresponding to the objects that have been - * registered by {@link #collectable(Object)} and have not been garbage-collected properly. - * This method first calls <code>System.gc()</code> multiple times to attempt to - * force any remaining garbage collection. - * - * @return a list of MemoryData objects for objects that have not yet been garbage-collected. - */ - public static synchronized List<MemoryData> getRemainingCollectableObjects() { - for (int i = 0; i < 5; i++) { - System.runFinalization(); - System.gc(); - try { - Thread.sleep(1); - } catch (InterruptedException e) { - } - } - purgeCollectables(); - return new ArrayList<MemoryData>(objects); - } - - - - - /** - * Register a new ListenerList object. This can be used to monitor freeing of listeners - * and find memory leaks. The objects are held by a weak reference, allowing them to be - * garbage-collected. - * - * @param list the listener list to register - */ - public static synchronized void registerListenerList(ListenerList<?> list) { - listenerLists.add(new WeakReference<ListenerList<?>>(list)); - listenerCallCount++; - if (listenerCallCount % PURGE_CALL_COUNT == 0) { - purgeListeners(); - } - - } - - /** - * Return a list of listener list objects corresponding to the objects that have been - * registered by {@link #registerListenerList(ListenerList)} and have not been garbage-collected yet. - * This method first calls <code>System.gc()</code> multiple times to attempt to - * force any remaining garbage collection. - * - * @return a list of listener list objects that have not yet been garbage-collected. - */ - public static synchronized List<ListenerList<?>> getRemainingListenerLists() { - for (int i = 0; i < 5; i++) { - System.runFinalization(); - System.gc(); - try { - Thread.sleep(1); - } catch (InterruptedException e) { - } - } - purgeListeners(); - List<ListenerList<?>> list = new ArrayList<ListenerList<?>>(); - for (WeakReference<ListenerList<?>> ref : listenerLists) { - ListenerList<?> l = ref.get(); - if (l != null) { - list.add(l); - } - } - return list; - } - - - - /** - * Purge all cleared references from the object list. - */ - private static void purgeCollectables() { - int origCount = objects.size(); - Iterator<MemoryData> iterator = objects.iterator(); - while (iterator.hasNext()) { - MemoryData data = iterator.next(); - if (data.getReference().get() == null) { - iterator.remove(); - } - } - log.debug(objects.size() + " of " + origCount + " objects remaining in discarded objects list after purge."); - } - - - /** - * Purge all cleared references from the object list. - */ - private static void purgeListeners() { - int origCount = listenerLists.size(); - Iterator<WeakReference<ListenerList<?>>> iterator = listenerLists.iterator(); - while (iterator.hasNext()) { - WeakReference<ListenerList<?>> ref = iterator.next(); - if (ref.get() == null) { - iterator.remove(); - } - } - log.debug(listenerLists.size() + " of " + origCount + " listener lists remaining after purge."); - } - - /** - * A value object class containing data of a discarded object reference. - */ - public static final class MemoryData { - private final WeakReference<Object> reference; - private final long registrationTime; - - private MemoryData(Object object) { - this.reference = new WeakReference<Object>(object); - this.registrationTime = System.currentTimeMillis(); - } - - /** - * Return the weak reference to the discarded object. - */ - public WeakReference<Object> getReference() { - return reference; - } - - /** - * Return the time when the object was discarded. - * @return a millisecond timestamp of when the object was discarded. - */ - public long getRegistrationTime() { - return registrationTime; - } - } - -} diff --git a/core/src/net/sf/openrocket/util/Monitorable.java b/core/src/net/sf/openrocket/util/Monitorable.java deleted file mode 100644 index bff7480e..00000000 --- a/core/src/net/sf/openrocket/util/Monitorable.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.sf.openrocket.util; - -/** - * Interface describing objects whose state changes can be monitored based on - * a modification ID number. If a specific object has the same modification ID - * at two different points in time, the object state is guaranteed to be the same. - * This does not necessarily hold between two different instances of an object type. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public interface Monitorable { - - /** - * Return a modification ID unique to the current state of this object and contained objects. - * The general contract is that if a specific object has the same modification ID at two moments - * in time, then the state of the object has not changed in between. Additionally the - * modification ID value must be monotonically increasing. This value can be used as a monitor - * to whether an object has been changed between two points of time. - * <p> - * Implementations may optionally fulfill the stronger requirement that any two objects of the same - * type that have the same modification ID will be equal, though for complex objects guaranteeing - * this may be impractical. - * <p> - * Objects that contain only primitive types or immutable objects can implement this method by - * increasing a modification counter or retrieving a new unique ID every time a value is set. - * <p> - * Objects that contain other objects with a mutable state may for example return the sum of the - * object's own modification ID, a modification ID counter (initially zero) and the modification IDs - * of the contained objects. When a mutable object is set, the modification counter is increased by - * the modification ID of the current object in order to preserve monotonicity. - * <p> - * If an object does not have any fields, this method can simply return zero. - * <p> - * Cloned objects may or may not have the same modification ID as the original object. - * - * @return a modification ID value for this object. - * @see UniqueID#next() - */ - public int getModID(); - -} diff --git a/core/src/net/sf/openrocket/util/MonitorableSet.java b/core/src/net/sf/openrocket/util/MonitorableSet.java deleted file mode 100644 index a7601bdf..00000000 --- a/core/src/net/sf/openrocket/util/MonitorableSet.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; - -/** - * A Set that additionally implements the Monitorable interface. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class MonitorableSet<E> extends HashSet<E> implements Monitorable { - - private int modID; - - @Override - public boolean add(E e) { - modID++; - return super.add(e); - }; - - @Override - public boolean addAll(Collection<? extends E> c) { - modID++; - return super.addAll(c); - } - - @Override - public void clear() { - modID++; - super.clear(); - } - - @Override - public Iterator<E> iterator() { - return new MonitorableIterator<E>(super.iterator()); - } - - @Override - public boolean remove(Object o) { - modID++; - return super.remove(o); - } - - @Override - public boolean removeAll(Collection<?> c) { - modID++; - return super.removeAll(c); - } - - @Override - public boolean retainAll(Collection<?> c) { - modID++; - return super.retainAll(c); - } - - - @Override - public int getModID() { - return modID; - } - - @SuppressWarnings("unchecked") - @Override - public MonitorableSet<E> clone() { - return (MonitorableSet<E>) super.clone(); - } - - private class MonitorableIterator<F> implements Iterator<F> { - private final Iterator<F> iterator; - - public MonitorableIterator(Iterator<F> iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public F next() { - return iterator.next(); - } - - @Override - public void remove() { - iterator.remove(); - modID++; - } - } -} diff --git a/core/src/net/sf/openrocket/util/Mutable.java b/core/src/net/sf/openrocket/util/Mutable.java deleted file mode 100644 index c7c91359..00000000 --- a/core/src/net/sf/openrocket/util/Mutable.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.sf.openrocket.util; - -import net.sf.openrocket.logging.TraceException; - -/** - * A utility class helping an object to be made immutable after a certain point of time. - * An object should contain an instance of Mutable and an immute() method which calls - * {@link #immute()}. Additionally, every method that changes the state of the object - * should call {@link #check()} before modification. - * <p> - * This class also provides a stack trace of the position where the object was made - * immutable to help in debugging modifications of immuted objects. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Mutable implements Cloneable { - - private TraceException immuteTrace = null; - - /** - * Mark the object immutable. Once the object has been called the object - * cannot be made mutable again. Repeated calls to this method have no effect. - */ - public void immute() { - if (immuteTrace == null) { - immuteTrace = new TraceException(1, 2); - } - } - - /** - * Check that the object is still mutable, and throw an exception if it is not. - * <p> - * The thrown exception will contain a trace of the position where the object was made - * immutable to help in debugging. - * - * @throws IllegalStateException if {@link #immute()} has been called for this object. - */ - public void check() { - if (immuteTrace != null) { - throw new IllegalStateException("Object has been made immutable at " - + immuteTrace.getMessage(), immuteTrace); - } - } - - /** - * Check whether this object is still mutable. - * - * @return whether this object is still mutable. - */ - public boolean isMutable() { - return immuteTrace == null; - } - - - /** - * Return a new Mutable instance with the same state as the current object. - */ - @Override - public Mutable clone() { - try { - return (Mutable) super.clone(); - } catch (CloneNotSupportedException e) { - throw new BugException("CloneNotSupportedException", e); - } - } -} diff --git a/core/src/net/sf/openrocket/util/Named.java b/core/src/net/sf/openrocket/util/Named.java deleted file mode 100644 index b91ae46a..00000000 --- a/core/src/net/sf/openrocket/util/Named.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.util; - -import java.text.Collator; - -/** - * An object holder that provides a custom toString return value. - * <p> - * The class supports sorting by the name. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - * @param <T> the holder type - */ -public class Named<T> implements Comparable<Named<T>> { - - private final T object; - private final String name; - - private Collator collator = null; - - /** - * Sole constructor. - * - * @param object the held object - * @param name the value to return by toString(). - */ - public Named(T object, String name) { - this.object = object; - this.name = name; - } - - - /** - * Get the held object. - * - * @return the object. - */ - public T get() { - return object; - } - - @Override - public String toString() { - return name; - } - - - @Override - public int compareTo(Named<T> other) { - if (collator == null) { - collator = Collator.getInstance(); - } - - return collator.compare(this.toString(), other.toString()); - } - -} diff --git a/core/src/net/sf/openrocket/util/NumericComparator.java b/core/src/net/sf/openrocket/util/NumericComparator.java deleted file mode 100644 index a337dee6..00000000 --- a/core/src/net/sf/openrocket/util/NumericComparator.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Comparator; - -public class NumericComparator implements Comparator<Object> { - - public static final NumericComparator INSTANCE = new NumericComparator(); - - @Override - public int compare(Object o1, Object o2) { - double v1 = getValue(o1); - double v2 = getValue(o2); - - if (Double.isNaN(v1) || Double.isNaN(v2)) { - String s1 = o1.toString(); - String s2 = o2.toString(); - return s1.compareTo(s2); - } - - return Double.compare(v1, v2); - } - - private double getValue(Object o) { - if (o instanceof Number) { - return ((Number) o).doubleValue(); - } - String s = o.toString(); - try { - return Double.parseDouble(s); - } catch (NumberFormatException e) { - return Double.NaN; - } - } - -} diff --git a/core/src/net/sf/openrocket/util/Pair.java b/core/src/net/sf/openrocket/util/Pair.java deleted file mode 100644 index 9a562cb8..00000000 --- a/core/src/net/sf/openrocket/util/Pair.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.sf.openrocket.util; - -/** - * Storage for a pair of objects. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - * @param <U> the first object type. - * @param <V> the second object type. - */ -public class Pair<U,V> { - - private final U u; - private final V v; - - - public Pair(U u, V v) { - this.u = u; - this.v = v; - } - - public U getU() { - return u; - } - - public V getV() { - return v; - } - - - /** - * Compare both components of the Pair to another object. - * The pair is equal iff both items are equal (or null). - */ - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object other) { - if (!(other instanceof Pair)) - return false; - Object otherU = ((Pair)other).getU(); - Object otherV = ((Pair)other).getV(); - - if (otherU == null) { - if (this.u != null) - return false; - } else { - if (!otherU.equals(this.u)) - return false; - } - - if (otherV == null) { - if (this.v != null) - return false; - } else { - if (!otherV.equals(this.v)) - return false; - } - return true; - } - - @Override - public int hashCode() { - return ((u != null) ? u.hashCode() : 0) + ((v != null) ? v.hashCode() : 0); - } - - - @Override - public String toString() { - return "[" + u + ";" + v + "]"; - } - -} diff --git a/core/src/net/sf/openrocket/util/PinkNoise.java b/core/src/net/sf/openrocket/util/PinkNoise.java deleted file mode 100644 index 572ad032..00000000 --- a/core/src/net/sf/openrocket/util/PinkNoise.java +++ /dev/null @@ -1,140 +0,0 @@ -package net.sf.openrocket.util; -import java.util.Random; - - -/** - * A class that provides a source of pink noise with a power spectrum density - * proportional to 1/f^alpha. The values are computed by applying an IIR filter to - * generated Gaussian random numbers. The number of poles used in the filter may be - * specified. Values as low as 3 produce good results, but using a larger number of - * poles allows lower frequencies to be amplified. Below the cutoff frequency the - * power spectrum density if constant. - * <p> - * The IIR filter use by this class is presented by N. Jeremy Kasdin, Proceedings of - * the IEEE, Vol. 83, No. 5, May 1995, p. 822. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class PinkNoise { - private final int poles; - private final double[] multipliers; - - private final double[] values; - private final Random rnd; - - - /** - * Generate pink noise with alpha=1.0 using a five-pole IIR. - */ - public PinkNoise() { - this(1.0, 5, new Random()); - } - - - /** - * Generate a specific pink noise using a five-pole IIR. - * - * @param alpha the exponent of the pink noise, 1/f^alpha. - */ - public PinkNoise(double alpha) { - this(alpha, 5, new Random()); - } - - - /** - * Generate pink noise specifying alpha and the number of poles. The larger the - * number of poles, the lower are the lowest frequency components that are amplified. - * - * @param alpha the exponent of the pink noise, 1/f^alpha. - * @param poles the number of poles to use. - */ - public PinkNoise(double alpha, int poles) { - this(alpha, poles, new Random()); - } - - - /** - * Generate pink noise specifying alpha, the number of poles and the randomness source. - * - * @param alpha the exponent of the pink noise, 1/f^alpha. - * @param poles the number of poles to use. - * @param random the randomness source. - */ - public PinkNoise(double alpha, int poles, Random random) { - this.rnd = random; - this.poles = poles; - this.multipliers = new double[poles]; - this.values = new double[poles]; - - double a = 1; - for (int i=0; i < poles; i++) { - a = (i - alpha/2) * a / (i+1); - multipliers[i] = a; - } - - // Fill the history with random values - for (int i=0; i < 5*poles; i++) - this.nextValue(); - } - - - - public double nextValue() { - double x = rnd.nextGaussian(); -// double x = rnd.nextDouble()-0.5; - - for (int i=0; i < poles; i++) { - x -= multipliers[i] * values[i]; - } - System.arraycopy(values, 0, values, 1, values.length-1); - values[0] = x; - - return x; - } - - - public static void main(String[] arg) { - - PinkNoise source; - - source = new PinkNoise(1.0, 100); - double std = 0; - for (int i=0; i < 1000000; i++) { - - } - - -// int n = 5000000; -// double avgavg=0; -// double avgstd = 0; -// double[] val = new double[n]; -// -// for (int j=0; j < 10; j++) { -// double avg=0, std=0; -// source = new PinkNoise(5.0/3.0, 2); -// -// for (int i=0; i < n; i++) { -// val[i] = source.nextValue(); -// avg += val[i]; -// } -// avg /= n; -// for (int i=0; i < n; i++) { -// std += (val[i]-avg)*(val[i]-avg); -// } -// std /= n; -// std = Math.sqrt(std); -// -// System.out.println("avg:"+avg+" stddev:"+std); -// avgavg += avg; -// avgstd += std; -// } -// avgavg /= 10; -// avgstd /= 10; -// System.out.println("Average avg:"+avgavg+" std:"+avgstd); -// - // Two poles: - - } - - -} diff --git a/core/src/net/sf/openrocket/util/PolyInterpolator.java b/core/src/net/sf/openrocket/util/PolyInterpolator.java deleted file mode 100644 index 134f7178..00000000 --- a/core/src/net/sf/openrocket/util/PolyInterpolator.java +++ /dev/null @@ -1,231 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Arrays; - -/** - * A class for polynomial interpolation. The interpolation constraints can be specified - * either as function values or values of the n'th derivative of the function. - * Using an interpolation consists of three steps: - * <p> - * 1. constructing a <code>PolyInterpolator</code> using the interpolation x coordinates <br> - * 2. generating the interpolation polynomial using the function and derivative values <br> - * 3. evaluating the polynomial at the desired point - * <p> - * The constructor takes an array of double arrays. The first array defines x coordinate - * values for the function values, the second array x coordinate values for the function's - * derivatives, the third array for second derivatives and so on. Constructing the - * <code>PolyInterpolator</code> is relatively slow, O(n^3) where n is the order of the - * polynomial. (It contains calculation of the inverse of an n x n matrix.) - * <p> - * Generating the interpolation polynomial is performed by the method - * {@link #interpolator(double...)}, which takes as an argument the function and - * derivative values. This operation takes O(n^2) time. - * <p> - * Finally, evaluating the polynomial at different positions takes O(n) time. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class PolyInterpolator { - - // Order of the polynomial - private final int count; - - private final double[][] interpolationMatrix; - - - /** - * Construct a polynomial interpolation generator. All arguments to the constructor - * are the x coordinates of the interpolated function. The first array correspond to - * the function values, the second to function derivatives, the third to second - * derivatives and so forth. The order of the polynomial is automatically calculated - * from the total number of constraints. - * <p> - * The construction takes O(n^3) time. - * - * @param points an array of constraints, the first corresponding to function value - * constraints, the second to derivative constraints etc. - */ - public PolyInterpolator(double[] ... points) { - int count = 0; - for (int i=0; i < points.length; i++) { - count += points[i].length; - } - if (count == 0) { - throw new IllegalArgumentException("No interpolation points defined."); - } - - this.count = count; - - int[] mul = new int[count]; - Arrays.fill(mul, 1); - - double[][] matrix = new double[count][count]; - int row = 0; - for (int j=0; j < points.length; j++) { - - for (int i=0; i < points[j].length; i++) { - double x = 1; - for (int col = count-1-j; col>= 0; col--) { - matrix[row][col] = x*mul[col]; - x *= points[j][i]; - } - row++; - } - - for (int i=0; i < count; i++) { - mul[i] *= (count-i-j-1); - } - } - assert(row == count); - - interpolationMatrix = inverse(matrix); - } - - - /** - * Generates an interpolation polynomial. The arguments supplied to this method - * are the function values, derivatives, second derivatives etc. in the order - * specified in the constructor (i.e. values first, then derivatives etc). - * <p> - * This method takes O(n^2) time. - * - * @param values the function values, derivatives etc. at positions defined in the - * constructor. - * @return the coefficients of the interpolation polynomial, the highest order - * term first and the constant last. - */ - public double[] interpolator(double... values) { - if (values.length != count) { - throw new IllegalArgumentException("Wrong number of arguments "+values.length+ - " expected "+count); - } - - double[] ret = new double[count]; - - for (int j=0; j < count; j++) { - for (int i=0; i < count; i++) { - ret[j] += interpolationMatrix[j][i] * values[i]; - } - } - - return ret; - } - - - /** - * Interpolate the given values at the point <code>x</code>. This is equivalent - * to generating an interpolation polynomial and evaluating the polynomial at the - * specified point. - * - * @param x point at which to evaluate the interpolation polynomial. - * @param values the function, derivatives etc. at position defined in the - * constructor. - * @return the value of the interpolation. - */ - public double interpolate(double x, double... values) { - return eval(x, interpolator(values)); - } - - - /** - * Evaluate a polynomial at the specified point <code>x</code>. The coefficients are - * assumed to have the highest order coefficient first and the constant term last. - * - * @param x position at which to evaluate the polynomial. - * @param coefficients polynomial coefficients, highest term first and constant last. - * @return the value of the polynomial. - */ - public static double eval(double x, double[] coefficients) { - double v = 1; - double result = 0; - for (int i = coefficients.length-1; i >= 0; i--) { - result += coefficients[i] * v; - v *= x; - } - return result; - } - - - - - private static double[][] inverse(double[][] matrix) { - int n = matrix.length; - - double x[][] = new double[n][n]; - double b[][] = new double[n][n]; - int index[] = new int[n]; - for (int i=0; i<n; ++i) - b[i][i] = 1; - - // Transform the matrix into an upper triangle - gaussian(matrix, index); - - // Update the matrix b[i][j] with the ratios stored - for (int i=0; i<n-1; ++i) - for (int j=i+1; j<n; ++j) - for (int k=0; k<n; ++k) - b[index[j]][k] -= matrix[index[j]][i]*b[index[i]][k]; - - // Perform backward substitutions - for (int i=0; i<n; ++i) { - x[n-1][i] = b[index[n-1]][i]/matrix[index[n-1]][n-1]; - for (int j=n-2; j>=0; --j) { - x[j][i] = b[index[j]][i]; - for (int k=j+1; k<n; ++k) { - x[j][i] -= matrix[index[j]][k]*x[k][i]; - } - x[j][i] /= matrix[index[j]][j]; - } - } - return x; - } - - private static void gaussian(double a[][], - int index[]) { - int n = index.length; - double c[] = new double[n]; - - // Initialize the index - for (int i=0; i<n; ++i) index[i] = i; - - // Find the rescaling factors, one from each row - for (int i=0; i<n; ++i) { - double c1 = 0; - for (int j=0; j<n; ++j) { - double c0 = Math.abs(a[i][j]); - if (c0 > c1) c1 = c0; - } - c[i] = c1; - } - - // Search the pivoting element from each column - int k = 0; - for (int j=0; j<n-1; ++j) { - double pi1 = 0; - for (int i=j; i<n; ++i) { - double pi0 = Math.abs(a[index[i]][j]); - pi0 /= c[index[i]]; - if (pi0 > pi1) { - pi1 = pi0; - k = i; - } - } - - // Interchange rows according to the pivoting order - int itmp = index[j]; - index[j] = index[k]; - index[k] = itmp; - for (int i=j+1; i<n; ++i) { - double pj = a[index[i]][j]/a[index[j]][j]; - - // Record pivoting ratios below the diagonal - a[index[i]][j] = pj; - - // Modify other elements accordingly - for (int l=j+1; l<n; ++l) - a[index[i]][l] -= pj*a[index[j]][l]; - } - } - } - -} diff --git a/core/src/net/sf/openrocket/util/PrintProperties.java b/core/src/net/sf/openrocket/util/PrintProperties.java deleted file mode 100644 index d3d4fe11..00000000 --- a/core/src/net/sf/openrocket/util/PrintProperties.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.SortedSet; -import java.util.TreeSet; - -public class PrintProperties { - - public static void main(String[] args) { - - // Sort the keys - SortedSet<String> keys = new TreeSet<String>(); - for (Object key: System.getProperties().keySet()) { - keys.add((String)key); - } - - for (String key: keys) { - System.out.println(key + "=" + System.getProperty((String)key)); - } - - } - -} diff --git a/core/src/net/sf/openrocket/util/Quaternion.java b/core/src/net/sf/openrocket/util/Quaternion.java deleted file mode 100644 index e82eb9d2..00000000 --- a/core/src/net/sf/openrocket/util/Quaternion.java +++ /dev/null @@ -1,321 +0,0 @@ -package net.sf.openrocket.util; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.startup.Application; - -/** - * An immutable quaternion class. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class Quaternion { - private static final LogHelper log = Application.getLogger(); - - - //////// Debug section - /* - * Debugging info. If openrocket.debug.quaternioncount is defined, a line is - * printed every 1000000 instantiations (or as many as defined). - */ - private static final boolean COUNT_DEBUG; - private static final int COUNT_DIFF; - static { - String str = System.getProperty("openrocket.debug.quaternioncount"); - int diff = 0; - if (str == null) { - COUNT_DEBUG = false; - COUNT_DIFF = 0; - } else { - COUNT_DEBUG = true; - try { - diff = Integer.parseInt(str); - } catch (NumberFormatException ignore) { - } - if (diff < 1000) - diff = 1000000; - COUNT_DIFF = diff; - } - } - - private static int count = 0; - { - // Debug count - if (COUNT_DEBUG) { - synchronized (Quaternion.class) { - count++; - if ((count % COUNT_DIFF) == 0) { - log.debug("Quaternion instantiated " + count + " times."); - } - } - } - } - - //////// End debug section - - - - private final double w, x, y, z; - private double norm = -1; - - - /** - * Construct a new "one" quaternion. This is equivalent to <code>new Quaternion(1,0,0,0)</code>. - */ - public Quaternion() { - this(1, 0, 0, 0); - } - - - public Quaternion(double w, double x, double y, double z) { - this.w = w; - this.x = x; - this.y = y; - this.z = z; - } - - - /** - * Create a rotation quaternion corresponding to the rotation vector. The rotation axis is - * the direction of vector, and rotation angle is the length of the vector. - * <p> - * The cost of the operation is approximately that of computing the length of the coordinate - * and computing two trigonometric functions. - * - * @param rotation the rotation vector - * @return the quaternion corresponding to the rotation vector - */ - public static Quaternion rotation(Coordinate rotation) { - double length = rotation.length(); - if (length < 0.000001) { - return new Quaternion(1, 0, 0, 0); - } - double sin = Math.sin(length / 2); - double cos = Math.cos(length / 2); - return new Quaternion(cos, - sin * rotation.x / length, sin * rotation.y / length, sin * rotation.z / length); - } - - /** - * Create a rotation quaternion corresponding to the rotation around the provided vector with - * the provided angle. - * - * @param axis the rotation axis - * @param angle the rotation angle - * @return the corresponding quaternion - */ - public static Quaternion rotation(Coordinate axis, double angle) { - Coordinate a = axis.normalize(); - double sin = Math.sin(angle); - double cos = Math.cos(angle); - return new Quaternion(cos, sin * a.x, sin * a.y, sin * a.z); - } - - - public double getW() { - return w; - } - - public double getX() { - return x; - } - - public double getY() { - return y; - } - - public double getZ() { - return z; - } - - - /** - * Check whether any of the quaternion values is NaN. - * - * @return true if w, x, y or z is NaN - */ - public boolean isNaN() { - return Double.isNaN(x) || Double.isNaN(y) || Double.isNaN(z) || Double.isNaN(w); - } - - - /** - * Multiply this quaternion by the other quaternion from the right side. This - * calculates the product <code>result = this * other</code>. - * - * @param other the quaternion to multiply this quaternion by. - * @return this quaternion. - */ - public Quaternion multiplyRight(Quaternion other) { - double newW = (this.w * other.w - this.x * other.x - this.y * other.y - this.z * other.z); - double newX = (this.w * other.x + this.x * other.w + this.y * other.z - this.z * other.y); - double newY = (this.w * other.y + this.y * other.w + this.z * other.x - this.x * other.z); - double newZ = (this.w * other.z + this.z * other.w + this.x * other.y - this.y * other.x); - - return new Quaternion(newW, newX, newY, newZ); - } - - /** - * Multiply this quaternion by the other quaternion from the left side. This - * calculates the product <code>result = other * this</code>. - * - * @param other the quaternion to multiply this quaternion by. - * @return this quaternion. - */ - public Quaternion multiplyLeft(Quaternion other) { - /* other(abcd) * this(wxyz) */ - - double newW = (other.w * this.w - other.x * this.x - other.y * this.y - other.z * this.z); - double newX = (other.w * this.x + other.x * this.w + other.y * this.z - other.z * this.y); - double newY = (other.w * this.y + other.y * this.w + other.z * this.x - other.x * this.z); - double newZ = (other.w * this.z + other.z * this.w + other.x * this.y - other.y * this.x); - - return new Quaternion(newW, newX, newY, newZ); - } - - - - - - /** - * Return a normalized version of this quaternion. If this quaternion is the zero quaternion, throws - * <code>IllegalStateException</code>. - * - * @return a normalized version of this quaternion. - * @throws IllegalStateException if the norm of this quaternion is zero. - */ - public Quaternion normalize() { - double n = norm(); - if (n < 0.0000001) { - throw new IllegalStateException("attempting to normalize zero-quaternion"); - } - return new Quaternion(w / n, x / n, y / n, z / n); - } - - - /** - * Normalize the quaternion if the norm is more than 1ppm from one. - * - * @return this quaternion or a normalized version of this quaternion. - * @throws IllegalStateException if the norm of this quaternion is zero. - */ - public Quaternion normalizeIfNecessary() { - double n2 = norm2(); - if (n2 < 0.999999 || n2 > 1.000001) { - return normalize(); - } else { - return this; - } - } - - - - /** - * Return the norm of this quaternion. - * - * @return the norm of this quaternion sqrt(w^2 + x^2 + y^2 + z^2). - */ - public double norm() { - if (norm < 0) { - norm = MathUtil.safeSqrt(x * x + y * y + z * z + w * w); - } - return norm; - } - - /** - * Return the square of the norm of this quaternion. - * - * @return the square of the norm of this quaternion (w^2 + x^2 + y^2 + z^2). - */ - public double norm2() { - return x * x + y * y + z * z + w * w; - } - - - /** - * Perform a coordinate rotation using this unit quaternion. The result is - * <code>this * coord * this^(-1)</code>. - * <p> - * This method assumes that the norm of this quaternion is one. - * - * @param coord the coordinate to rotate. - * @return the rotated coordinate. - */ - public Coordinate rotate(Coordinate coord) { - double a, b, c, d; - - assert (Math.abs(norm2() - 1) < 0.00001) : "Quaternion not unit length: " + this; - - - // (a,b,c,d) = this * coord = (w,x,y,z) * (0,cx,cy,cz) - a = -x * coord.x - y * coord.y - z * coord.z; // w - b = w * coord.x + y * coord.z - z * coord.y; // x i - c = w * coord.y - x * coord.z + z * coord.x; // y j - d = w * coord.z + x * coord.y - y * coord.x; // z k - - - // return = (a,b,c,d) * (this)^-1 = (a,b,c,d) * (w,-x,-y,-z) - - // Assert that the w-value is zero - assert (Math.abs(a * w + b * x + c * y + d * z) < coord.max() * MathUtil.EPSILON) : ("Should be zero: " + (a * w + b * x + c * y + d * z) + " in " + this + " c=" + coord); - - return new Coordinate( - -a * x + b * w - c * z + d * y, - -a * y + b * z + c * w - d * x, - -a * z - b * y + c * x + d * w, - coord.weight); - } - - /** - * Perform an inverse coordinate rotation using this unit quaternion. The result is - * <code>this^(-1) * coord * this</code>. - * <p> - * This method assumes that the norm of this quaternion is one. - * - * @param coord the coordinate to rotate. - * @return the rotated coordinate. - */ - public Coordinate invRotate(Coordinate coord) { - double a, b, c, d; - - assert (Math.abs(norm2() - 1) < 0.00001) : "Quaternion not unit length: " + this; - - // (a,b,c,d) = (this)^-1 * coord = (w,-x,-y,-z) * (0,cx,cy,cz) - a = +x * coord.x + y * coord.y + z * coord.z; - b = w * coord.x - y * coord.z + z * coord.y; - c = w * coord.y + x * coord.z - z * coord.x; - d = w * coord.z - x * coord.y + y * coord.x; - - - // return = (a,b,c,d) * this = (a,b,c,d) * (w,x,y,z) - assert (Math.abs(a * w - b * x - c * y - d * z) < Math.max(coord.max(), 1) * MathUtil.EPSILON) : ("Should be zero: " + (a * w - b * x - c * y - d * z) + " in " + this + " c=" + coord); - - return new Coordinate( - a * x + b * w + c * z - d * y, - a * y - b * z + c * w + d * x, - a * z + b * y - c * x + d * w, - coord.weight); - } - - - /** - * Rotate the coordinate (0,0,1) using this quaternion. The result is returned - * as a Coordinate. This method is equivalent to calling - * <code>q.rotate(new Coordinate(0,0,1))</code> but requires only about half of the - * multiplications. - * - * @return The coordinate (0,0,1) rotated using this quaternion. - */ - public Coordinate rotateZ() { - return new Coordinate( - 2 * (w * y + x * z), - 2 * (y * z - w * x), - w * w - x * x - y * y + z * z); - } - - - @Override - public String toString() { - return String.format("Quaternion[%f,%f,%f,%f,norm=%f]", w, x, y, z, this.norm()); - } - -} diff --git a/core/src/net/sf/openrocket/util/QuaternionMultiply.java b/core/src/net/sf/openrocket/util/QuaternionMultiply.java deleted file mode 100644 index 099ecf8d..00000000 --- a/core/src/net/sf/openrocket/util/QuaternionMultiply.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.sf.openrocket.util; - -public class QuaternionMultiply { - - private static class Value { - public int sign = 1; - public String value; - - public Value multiply(Value other) { - Value result = new Value(); - result.sign = this.sign * other.sign; - if (this.value.compareTo(other.value) < 0) - result.value = this.value + "*" + other.value; - else - result.value = other.value + "*" + this.value; - return result; - } - @Override - public String toString() { - String s; - - if (sign < 0) - s = "-"; - else - s = "+"; - - if (sign == 0) - s += " 0"; - else - s += " " + value; - - return s; - } - } - - - - private static Value[] multiply(Value[] first, Value[] second) { - return null; - } - - - public static void main(String[] arg) { - if (arg.length % 4 != 0 || arg.length < 4) { - System.out.println("Must have modulo 4 args, at least 4"); - return; - } - - Value[][] values = new Value[arg.length/4][4]; - - for (int i=0; i<arg.length; i++) { - Value value = new Value(); - - if (arg[i].equals("")) { - value.sign = 0; - } else { - if (arg[i].startsWith("-")) { - value.sign = -1; - value.value = arg[i].substring(1); - } else if (arg[i].startsWith("+")) { - value.sign = 1; - value.value = arg[i].substring(1); - } else { - value.sign = 1; - value.value = arg[i]; - } - } - - values[i/4][i%4] = value; - } - - System.out.println("Multiplying:"); - for (int i=0; i < values.length; i++) { - print(values[i]); - } - System.out.println("Result:"); - - Value[] result = values[0]; - for (int i=1; i < values.length; i++) { - result = multiply(result, values[i]); - } - print(result); - } - - private static void print(Value[] q) { - System.out.println(" " + q[0] + " " + q[1] + " i " + q[2] + " j " + q[3] + " k"); - } - -} - diff --git a/core/src/net/sf/openrocket/util/Reflection.java b/core/src/net/sf/openrocket/util/Reflection.java deleted file mode 100644 index b3c66f62..00000000 --- a/core/src/net/sf/openrocket/util/Reflection.java +++ /dev/null @@ -1,197 +0,0 @@ -package net.sf.openrocket.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import net.sf.openrocket.rocketcomponent.RocketComponent; - - -public class Reflection { - - private static final String ROCKETCOMPONENT_PACKAGE = "net.sf.openrocket.rocketcomponent"; - - /** - * Simple wrapper class that converts the Method.invoke() exceptions into suitable - * RuntimeExceptions. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - public static class Method { - private final java.lang.reflect.Method method; - - public Method(java.lang.reflect.Method m) { - if (m == null) { - throw new IllegalArgumentException("method is null"); - } - method = m; - } - - /** - * Same as Method.invoke(), but the possible exceptions are wrapped into - * RuntimeExceptions. - */ - public Object invoke(Object obj, Object... args) { - try { - return method.invoke(obj, args); - } catch (IllegalArgumentException e) { - throw new BugException("Error while invoking method '" + method + "'. " + - "Please report this as a bug.", e); - } catch (IllegalAccessException e) { - throw new BugException("Error while invoking method '" + method + "'. " + - "Please report this as a bug.", e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - } - - /** - * Invoke static method. Equivalent to invoke(null, args...). - */ - public Object invokeStatic(Object... args) { - return invoke(null, args); - } - - /** - * Same as Method.toString(). - */ - @Override - public String toString() { - return method.toString(); - } - } - - - /** - * Handles an InvocationTargetException gracefully. If the cause is an unchecked - * exception it is thrown, otherwise it is encapsulated in a BugException. - * <p> - * This method has a return type of Error in order to allow writing code like: - * <pre>throw Reflection.handleInvocationTargetException(e)</pre> - * This allows the compiler verifying that the call will never succeed correctly - * and ending that branch of execution. - * - * @param e the InvocationTargetException that occurred (not null). - * @return never returns normally. - */ - public static Error handleWrappedException(Exception e) { - Throwable cause = e.getCause(); - if (cause == null) { - throw new BugException("wrapped exception without cause", e); - } - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; - } - if (cause instanceof Error) { - throw (Error) cause; - } - throw new BugException("wrapped exception occurred", cause); - } - - - - /** - * Find a method from the rocket component classes. - * Throws an exception if method not found. - */ - public static Reflection.Method findMethod( - Class<? extends RocketComponent> componentClass, - String method, Class<?>... params) { - Reflection.Method m = findMethod(ROCKETCOMPONENT_PACKAGE, componentClass, - "", method, params); - if (m == null) { - throw new BugException("Could not find method for componentClass=" - + componentClass + " method=" + method); - } - return m; - } - - - - public static Reflection.Method findMethod(String pack, RocketComponent component, - String method, Class<?>... params) { - return findMethod(pack, component.getClass(), "", method, params); - } - - - public static Reflection.Method findMethod(String pack, RocketComponent component, - String suffix, String method, Class<?>... params) { - return findMethod(pack, component.getClass(), suffix, method, params); - } - - - public static Reflection.Method findMethod(String pack, - Class<? extends RocketComponent> componentClass, - String suffix, String method, Class<?>... params) { - Class<?> currentclass; - String name; - - currentclass = componentClass; - while ((currentclass != null) && (currentclass != Object.class)) { - name = currentclass.getCanonicalName(); - if (name.lastIndexOf('.') >= 0) - name = name.substring(name.lastIndexOf(".") + 1); - name = pack + "." + name + suffix; - - try { - Class<?> c = Class.forName(name); - java.lang.reflect.Method m = c.getMethod(method, params); - return new Reflection.Method(m); - } catch (ClassNotFoundException ignore) { - } catch (NoSuchMethodException ignore) { - } - - currentclass = currentclass.getSuperclass(); - } - return null; - } - - - public static Object construct(String pack, RocketComponent component, String suffix, - Object... params) { - - Class<?> currentclass; - String name; - - currentclass = component.getClass(); - while ((currentclass != null) && (currentclass != Object.class)) { - name = currentclass.getCanonicalName(); - if (name.lastIndexOf('.') >= 0) - name = name.substring(name.lastIndexOf(".") + 1); - name = pack + "." + name + suffix; - - try { - Class<?> c = Class.forName(name); - Class<?>[] paramClasses = new Class<?>[params.length]; - for (int i = 0; i < params.length; i++) { - paramClasses[i] = params[i].getClass(); - } - - // Constructors must be searched manually. Why?! - main: for (Constructor<?> constructor : c.getConstructors()) { - Class<?>[] parameterTypes = constructor.getParameterTypes(); - if (params.length != parameterTypes.length) - continue; - for (int i = 0; i < params.length; i++) { - if (!parameterTypes[i].isInstance(params[i])) - continue main; - } - // Matching constructor found - return constructor.newInstance(params); - } - } catch (ClassNotFoundException ignore) { - } catch (IllegalArgumentException e) { - throw new BugException("Construction of " + name + " failed", e); - } catch (InstantiationException e) { - throw new BugException("Construction of " + name + " failed", e); - } catch (IllegalAccessException e) { - throw new BugException("Construction of " + name + " failed", e); - } catch (InvocationTargetException e) { - throw Reflection.handleWrappedException(e); - } - - currentclass = currentclass.getSuperclass(); - } - throw new BugException("Suitable constructor for component " + component + - " not found"); - } -} diff --git a/core/src/net/sf/openrocket/util/Rotation2D.java b/core/src/net/sf/openrocket/util/Rotation2D.java deleted file mode 100644 index 1672a011..00000000 --- a/core/src/net/sf/openrocket/util/Rotation2D.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.sf.openrocket.util; - -public class Rotation2D { - - public static final Rotation2D ID = new Rotation2D(0.0, 1.0); - - public final double sin, cos; - - - public Rotation2D(double angle) { - this(Math.sin(angle), Math.cos(angle)); - } - - public Rotation2D(double sin, double cos) { - this.sin = sin; - this.cos = cos; - } - - public Coordinate rotateX(Coordinate c) { - return new Coordinate(c.x, cos*c.y - sin*c.z, cos*c.z + sin*c.y, c.weight); - } - - public Coordinate rotateY(Coordinate c) { - return new Coordinate(cos*c.x + sin*c.z, c.y, cos*c.z - sin*c.x, c.weight); - } - - public Coordinate rotateZ(Coordinate c) { - return new Coordinate(cos*c.x - sin*c.y, cos*c.y + sin*c.x, c.z, c.weight); - } - - - public Coordinate invRotateX(Coordinate c) { - return new Coordinate(c.x, cos*c.y + sin*c.z, cos*c.z - sin*c.y, c.weight); - } - - public Coordinate invRotateY(Coordinate c) { - return new Coordinate(cos*c.x - sin*c.z, c.y, cos*c.z + sin*c.x, c.weight); - } - - public Coordinate invRotateZ(Coordinate c) { - return new Coordinate(cos*c.x + sin*c.y, cos*c.y - sin*c.x, c.z, c.weight); - } - -} diff --git a/core/src/net/sf/openrocket/util/SafetyMutex.java b/core/src/net/sf/openrocket/util/SafetyMutex.java deleted file mode 100644 index 646c54e4..00000000 --- a/core/src/net/sf/openrocket/util/SafetyMutex.java +++ /dev/null @@ -1,237 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.LinkedList; - -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.TraceException; -import net.sf.openrocket.startup.Application; - -/** - * A mutex that can be used for verifying thread safety. This class cannot be - * used to perform synchronization, only to detect concurrency issues. This - * class can be used by the main methods of non-thread-safe classes to ensure - * the class is not wrongly used from multiple threads concurrently. - * <p> - * This mutex is not reentrant even for the same thread that has locked it. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public abstract class SafetyMutex { - private static final boolean USE_CHECKS = Application.useSafetyChecks(); - private static final LogHelper log = Application.getLogger(); - - - /** - * Return a new instance of a safety mutex. This returns an actual implementation - * or a bogus implementation depending on whether safety checks are enabled or disabled. - * - * @return a new instance of a safety mutex - */ - public static SafetyMutex newInstance() { - if (USE_CHECKS) { - return new ConcreteSafetyMutex(); - } else { - return new BogusSafetyMutex(); - } - } - - - /** - * Verify that this mutex is unlocked, but don't lock it. This has the same effect - * as <code>mutex.lock(); mutex.unlock();</code> and is useful for methods that return - * immediately (e.g. getters). - * - * @throws ConcurrencyException if this mutex is already locked. - */ - public abstract void verify(); - - - /** - * Lock this mutex. If this mutex is already locked an error is raised and - * a ConcurrencyException is thrown. The location parameter is used to distinguish - * the locking location, and it should be e.g. the method name. - * - * @param location a string describing the location where this mutex was locked (cannot be null). - * - * @throws ConcurrencyException if this mutex is already locked. - */ - public abstract void lock(String location); - - - /** - * Unlock this mutex. If this mutex is not locked at the position of the parameter - * or was locked by another thread than the current thread an error is raised, - * but an exception is not thrown. - * <p> - * This method is guaranteed never to throw an exception, so it can safely be used in finally blocks. - * - * @param location a location string matching that which locked the mutex - * @return whether the unlocking was successful (this normally doesn't need to be checked) - */ - public abstract boolean unlock(String location); - - - - /** - * Bogus implementation of a safety mutex (used when safety checking is not performed). - */ - static class BogusSafetyMutex extends SafetyMutex { - - @Override - public void verify() { - } - - @Override - public void lock(String location) { - } - - @Override - public boolean unlock(String location) { - return true; - } - - } - - /** - * A concrete, working implementation of a safety mutex. - */ - static class ConcreteSafetyMutex extends SafetyMutex { - private static final boolean STORE_LOCKING_LOCATION = (System.getProperty("openrocket.debug.mutexlocation") != null); - - // Package-private for unit testing - static volatile boolean errorReported = false; - - // lockingThread is set when this mutex is locked. - Thread lockingThread = null; - // longingLocation is set when lockingThread is, if STORE_LOCKING_LOCATION is true - TraceException lockingLocation = null; - // Stack of places that have locked this mutex - final LinkedList<String> locations = new LinkedList<String>(); - - - - @Override - public synchronized void verify() { - checkState(true); - if (lockingThread != null && lockingThread != Thread.currentThread()) { - error("Mutex is already locked", true); - } - } - - - - @Override - public synchronized void lock(String location) { - if (location == null) { - throw new IllegalArgumentException("location is null"); - } - checkState(true); - - Thread currentThread = Thread.currentThread(); - if (lockingThread != null && lockingThread != currentThread) { - error("Mutex is already locked", true); - } - - lockingThread = currentThread; - if (STORE_LOCKING_LOCATION) { - lockingLocation = new TraceException("Location where mutex was locked '" + location + "'"); - } - locations.push(location); - } - - - - - @Override - public synchronized boolean unlock(String location) { - try { - - if (location == null) { - Application.getExceptionHandler().handleErrorCondition("location is null"); - location = ""; - } - checkState(false); - - - // Check that the mutex is locked - if (lockingThread == null) { - error("Mutex was not locked", false); - return false; - } - - // Check that the mutex is locked by the current thread - if (lockingThread != Thread.currentThread()) { - error("Mutex is being unlocked from differerent thread than where it was locked", false); - return false; - } - - // Check that the unlock location is correct - String lastLocation = locations.pop(); - if (!location.equals(lastLocation)) { - locations.push(lastLocation); - error("Mutex unlocking location does not match locking location, location=" + location, false); - return false; - } - - // Unlock the mutex if the last one - if (locations.isEmpty()) { - lockingThread = null; - lockingLocation = null; - } - return true; - } catch (Exception e) { - Application.getExceptionHandler().handleErrorCondition("An exception occurred while unlocking a mutex, " + - "locking thread=" + lockingThread + " locations=" + locations, e); - return false; - } - } - - - - /** - * Check that the internal state of the mutex (lockingThread vs. locations) is correct. - */ - private void checkState(boolean throwException) { - /* - * Disallowed states: - * lockingThread == null && !locations.isEmpty() - * lockingThread != null && locations.isEmpty() - */ - if ((lockingThread == null) ^ (locations.isEmpty())) { - // Clear the mutex only after error() has executed (and possibly thrown an exception) - try { - error("Mutex data inconsistency occurred - unlocking mutex", throwException); - } finally { - lockingThread = null; - lockingLocation = null; - locations.clear(); - } - } - } - - - /** - * Raise an error. The first occurrence is passed directly to the exception handler, - * later errors are simply logged. - */ - private void error(String message, boolean throwException) { - message = message + - ", current thread = " + Thread.currentThread() + - ", locking thread=" + lockingThread + - ", locking locations=" + locations; - - ConcurrencyException ex = new ConcurrencyException(message, lockingLocation); - - if (!errorReported) { - errorReported = true; - Application.getExceptionHandler().handleErrorCondition(ex); - } else { - log.error(message, ex); - } - - if (throwException) { - throw ex; - } - } - } -} diff --git a/core/src/net/sf/openrocket/util/SimpleStack.java b/core/src/net/sf/openrocket/util/SimpleStack.java deleted file mode 100644 index 6bdd9671..00000000 --- a/core/src/net/sf/openrocket/util/SimpleStack.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.NoSuchElementException; -/** - * SimpleStack implementation backed by an ArrayList. - * - */ -public class SimpleStack<T> extends ArrayList<T> { - - public void push( T value ) { - this.add(value); - } - - public T peek() { - if ( size() <= 0 ) { - return null; - } - return this.get( size() -1 ); - } - - public T pop() { - if ( size() <= 0 ) { - throw new NoSuchElementException(); - } - T value = this.remove( size() -1 ); - return value; - } - -} diff --git a/core/src/net/sf/openrocket/util/StateChangeListener.java b/core/src/net/sf/openrocket/util/StateChangeListener.java deleted file mode 100644 index 2d5e5df9..00000000 --- a/core/src/net/sf/openrocket/util/StateChangeListener.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.EventListener; -import java.util.EventObject; - -public interface StateChangeListener extends EventListener { - - public void stateChanged( EventObject e ); - -} diff --git a/core/src/net/sf/openrocket/util/Statistics.java b/core/src/net/sf/openrocket/util/Statistics.java deleted file mode 100644 index f96adf19..00000000 --- a/core/src/net/sf/openrocket/util/Statistics.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.sf.openrocket.util; - -public interface Statistics { - - public String getStatistics(); - - public void resetStatistics(); - -} diff --git a/core/src/net/sf/openrocket/util/TestRockets.java b/core/src/net/sf/openrocket/util/TestRockets.java deleted file mode 100644 index 7a670e16..00000000 --- a/core/src/net/sf/openrocket/util/TestRockets.java +++ /dev/null @@ -1,570 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Random; - -import net.sf.openrocket.database.Databases; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.material.Material.Type; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.FinSet.CrossSection; -import net.sf.openrocket.rocketcomponent.FreeformFinSet; -import net.sf.openrocket.rocketcomponent.IllegalFinPointException; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.InternalComponent; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.ReferenceType; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent.Position; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.rocketcomponent.Transition.Shape; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.startup.Application; - -public class TestRockets { - - private final String key; - private final Random rnd; - - - public TestRockets(String key) { - - if (key == null) { - Random rnd = new Random(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 6; i++) { - int n = rnd.nextInt(62); - if (n < 10) { - sb.append((char) ('0' + n)); - } else if (n < 36) { - sb.append((char) ('A' + n - 10)); - } else { - sb.append((char) ('a' + n - 36)); - } - } - key = sb.toString(); - } - - this.key = key; - this.rnd = new Random(key.hashCode()); - - } - - - /** - * Create a new test rocket based on the value 'key'. The rocket utilizes most of the - * properties and features available. The same key always returns the same rocket, - * but different key values produce slightly different rockets. A key value of - * <code>null</code> generates a rocket using a random key. - * <p> - * The rocket created by this method is not fly-worthy. It is also NOT guaranteed - * that later versions would produce exactly the same rocket! - * - * @return a rocket design. - */ - public Rocket makeTestRocket() { - - Rocket rocket = new Rocket(); - setBasics(rocket); - rocket.setCustomReferenceLength(rnd(0.05)); - rocket.setDesigner("Designer " + key); - rocket.setReferenceType((ReferenceType) randomEnum(ReferenceType.class)); - rocket.setRevision("Rocket revision " + key); - rocket.setName(key); - - - Stage stage = new Stage(); - setBasics(stage); - rocket.addChild(stage); - - - NoseCone nose = new NoseCone(); - setBasics(stage); - nose.setAftRadius(rnd(0.03)); - nose.setAftRadiusAutomatic(rnd.nextBoolean()); - nose.setAftShoulderCapped(rnd.nextBoolean()); - nose.setAftShoulderLength(rnd(0.02)); - nose.setAftShoulderRadius(rnd(0.02)); - nose.setAftShoulderThickness(rnd(0.002)); - nose.setClipped(rnd.nextBoolean()); - nose.setThickness(rnd(0.002)); - nose.setFilled(rnd.nextBoolean()); - nose.setForeRadius(rnd(0.1)); // Unset - nose.setLength(rnd(0.15)); - nose.setShapeParameter(rnd(0.5)); - nose.setType((Shape) randomEnum(Shape.class)); - stage.addChild(nose); - - - Transition shoulder = new Transition(); - setBasics(shoulder); - shoulder.setAftRadius(rnd(0.06)); - shoulder.setAftRadiusAutomatic(rnd.nextBoolean()); - shoulder.setAftShoulderCapped(rnd.nextBoolean()); - shoulder.setAftShoulderLength(rnd(0.02)); - shoulder.setAftShoulderRadius(rnd(0.05)); - shoulder.setAftShoulderThickness(rnd(0.002)); - shoulder.setClipped(rnd.nextBoolean()); - shoulder.setThickness(rnd(0.002)); - shoulder.setFilled(rnd.nextBoolean()); - shoulder.setForeRadius(rnd(0.03)); - shoulder.setForeRadiusAutomatic(rnd.nextBoolean()); - shoulder.setForeShoulderCapped(rnd.nextBoolean()); - shoulder.setForeShoulderLength(rnd(0.02)); - shoulder.setForeShoulderRadius(rnd(0.02)); - shoulder.setForeShoulderThickness(rnd(0.002)); - shoulder.setLength(rnd(0.15)); - shoulder.setShapeParameter(rnd(0.5)); - shoulder.setThickness(rnd(0.003)); - shoulder.setType((Shape) randomEnum(Shape.class)); - stage.addChild(shoulder); - - - BodyTube body = new BodyTube(); - setBasics(body); - body.setThickness(rnd(0.002)); - body.setFilled(rnd.nextBoolean()); - body.setIgnitionDelay(rnd.nextDouble() * 3); - body.setIgnitionEvent((IgnitionEvent) randomEnum(IgnitionEvent.class)); - body.setLength(rnd(0.3)); - body.setMotorMount(rnd.nextBoolean()); - body.setMotorOverhang(rnd.nextGaussian() * 0.03); - body.setOuterRadius(rnd(0.06)); - body.setOuterRadiusAutomatic(rnd.nextBoolean()); - stage.addChild(body); - - - Transition boattail = new Transition(); - setBasics(boattail); - boattail.setAftRadius(rnd(0.03)); - boattail.setAftRadiusAutomatic(rnd.nextBoolean()); - boattail.setAftShoulderCapped(rnd.nextBoolean()); - boattail.setAftShoulderLength(rnd(0.02)); - boattail.setAftShoulderRadius(rnd(0.02)); - boattail.setAftShoulderThickness(rnd(0.002)); - boattail.setClipped(rnd.nextBoolean()); - boattail.setThickness(rnd(0.002)); - boattail.setFilled(rnd.nextBoolean()); - boattail.setForeRadius(rnd(0.06)); - boattail.setForeRadiusAutomatic(rnd.nextBoolean()); - boattail.setForeShoulderCapped(rnd.nextBoolean()); - boattail.setForeShoulderLength(rnd(0.02)); - boattail.setForeShoulderRadius(rnd(0.05)); - boattail.setForeShoulderThickness(rnd(0.002)); - boattail.setLength(rnd(0.15)); - boattail.setShapeParameter(rnd(0.5)); - boattail.setThickness(rnd(0.003)); - boattail.setType((Shape) randomEnum(Shape.class)); - stage.addChild(boattail); - - - MassComponent mass = new MassComponent(); - setBasics(mass); - mass.setComponentMass(rnd(0.05)); - mass.setLength(rnd(0.05)); - mass.setRadialDirection(rnd(100)); - mass.setRadialPosition(rnd(0.02)); - mass.setRadius(rnd(0.05)); - nose.addChild(mass); - - - - - return rocket; - } - - - private void setBasics(RocketComponent c) { - c.setComment(c.getComponentName() + " comment " + key); - c.setName(c.getComponentName() + " name " + key); - - c.setCGOverridden(rnd.nextBoolean()); - c.setMassOverridden(rnd.nextBoolean()); - c.setOverrideCGX(rnd(0.2)); - c.setOverrideMass(rnd(0.05)); - c.setOverrideSubcomponents(rnd.nextBoolean()); - - if (c.isMassive()) { - // Only massive components are drawn - c.setColor(randomColor()); - c.setLineStyle((LineStyle) randomEnum(LineStyle.class)); - } - - if (c instanceof ExternalComponent) { - ExternalComponent e = (ExternalComponent) c; - e.setFinish((Finish) randomEnum(Finish.class)); - double d = rnd(100); - e.setMaterial(Databases.findMaterial(Type.BULK, "Testmat " + d, d)); - } - - if (c instanceof InternalComponent) { - InternalComponent i = (InternalComponent) c; - i.setRelativePosition((Position) randomEnum(Position.class)); - i.setPositionValue(rnd(0.3)); - } - } - - - - private double rnd(double scale) { - return (rnd.nextDouble() * 0.2 + 0.9) * scale; - } - - private Color randomColor() { - return new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); - } - - private <T extends Enum<T>> Enum<T> randomEnum(Class<T> c) { - Enum<T>[] values = c.getEnumConstants(); - if (values.length == 0) - return null; - - return values[rnd.nextInt(values.length)]; - } - - - - - - public Rocket makeSmallFlyable() { - double noseconeLength = 0.10, noseconeRadius = 0.01; - double bodytubeLength = 0.20, bodytubeRadius = 0.01, bodytubeThickness = 0.001; - - int finCount = 3; - double finRootChord = 0.04, finTipChord = 0.05, finSweep = 0.01, finThickness = 0.003, finHeight = 0.03; - - - Rocket rocket; - Stage stage; - NoseCone nosecone; - BodyTube bodytube; - TrapezoidFinSet finset; - - rocket = new Rocket(); - stage = new Stage(); - stage.setName("Stage1"); - - nosecone = new NoseCone(Transition.Shape.ELLIPSOID, noseconeLength, noseconeRadius); - bodytube = new BodyTube(bodytubeLength, bodytubeRadius, bodytubeThickness); - - finset = new TrapezoidFinSet(finCount, finRootChord, finTipChord, finSweep, finHeight); - - - // Stage construction - rocket.addChild(stage); - - - // Component construction - stage.addChild(nosecone); - stage.addChild(bodytube); - - bodytube.addChild(finset); - - Material material = Application.getPreferences().getDefaultComponentMaterial(null, Material.Type.BULK); - nosecone.setMaterial(material); - bodytube.setMaterial(material); - finset.setMaterial(material); - - String id = rocket.newMotorConfigurationID(); - bodytube.setMotorMount(true); - - Motor m = Application.getMotorSetDatabase().findMotors(null, null, "B4", Double.NaN, Double.NaN).get(0); - bodytube.setMotor(id, m); - bodytube.setMotorOverhang(0.005); - rocket.getDefaultConfiguration().setMotorConfigurationID(id); - - rocket.getDefaultConfiguration().setAllStages(); - - - return rocket; - } - - - public static Rocket makeBigBlue() { - Rocket rocket; - Stage stage; - NoseCone nosecone; - BodyTube bodytube; - FreeformFinSet finset; - MassComponent mcomp; - - rocket = new Rocket(); - stage = new Stage(); - stage.setName("Stage1"); - - nosecone = new NoseCone(Transition.Shape.ELLIPSOID, 0.105, 0.033); - nosecone.setThickness(0.001); - bodytube = new BodyTube(0.69, 0.033, 0.001); - - finset = new FreeformFinSet(); - try { - finset.setPoints(new Coordinate[] { - new Coordinate(0, 0), - new Coordinate(0.115, 0.072), - new Coordinate(0.255, 0.072), - new Coordinate(0.255, 0.037), - new Coordinate(0.150, 0) - }); - } catch (IllegalFinPointException e) { - e.printStackTrace(); - } - finset.setThickness(0.003); - finset.setFinCount(4); - - finset.setCantAngle(0 * Math.PI / 180); - System.err.println("Fin cant angle: " + (finset.getCantAngle() * 180 / Math.PI)); - - mcomp = new MassComponent(0.2, 0.03, 0.045 + 0.060); - mcomp.setRelativePosition(Position.TOP); - mcomp.setPositionValue(0); - - // Stage construction - rocket.addChild(stage); - rocket.setPerfectFinish(false); - - - // Component construction - stage.addChild(nosecone); - stage.addChild(bodytube); - - bodytube.addChild(finset); - - bodytube.addChild(mcomp); - - // Material material = new Material("Test material", 500); - // nosecone.setMaterial(material); - // bodytube.setMaterial(material); - // finset.setMaterial(material); - - String id = rocket.newMotorConfigurationID(); - bodytube.setMotorMount(true); - - // Motor m = Application.getMotorSetDatabase().findMotors(null, null, "F12J", Double.NaN, Double.NaN).get(0); - // bodytube.setMotor(id, m); - // bodytube.setMotorOverhang(0.005); - rocket.getDefaultConfiguration().setMotorConfigurationID(id); - - rocket.getDefaultConfiguration().setAllStages(); - - - return rocket; - } - - - - public static Rocket makeIsoHaisu() { - Rocket rocket; - Stage stage; - NoseCone nosecone; - BodyTube tube1, tube2, tube3; - TrapezoidFinSet finset; - TrapezoidFinSet auxfinset; - MassComponent mcomp; - - final double R = 0.07; - - rocket = new Rocket(); - stage = new Stage(); - stage.setName("Stage1"); - - nosecone = new NoseCone(Transition.Shape.OGIVE, 0.53, R); - nosecone.setThickness(0.005); - nosecone.setMassOverridden(true); - nosecone.setOverrideMass(0.588); - stage.addChild(nosecone); - - tube1 = new BodyTube(0.505, R, 0.005); - tube1.setMassOverridden(true); - tube1.setOverrideMass(0.366); - stage.addChild(tube1); - - tube2 = new BodyTube(0.605, R, 0.005); - tube2.setMassOverridden(true); - tube2.setOverrideMass(0.427); - stage.addChild(tube2); - - tube3 = new BodyTube(1.065, R, 0.005); - tube3.setMassOverridden(true); - tube3.setOverrideMass(0.730); - stage.addChild(tube3); - - - LaunchLug lug = new LaunchLug(); - tube1.addChild(lug); - - TubeCoupler coupler = new TubeCoupler(); - coupler.setOuterRadiusAutomatic(true); - coupler.setThickness(0.005); - coupler.setLength(0.28); - coupler.setMassOverridden(true); - coupler.setOverrideMass(0.360); - coupler.setRelativePosition(Position.BOTTOM); - coupler.setPositionValue(-0.14); - tube1.addChild(coupler); - - - // Parachute - MassComponent mass = new MassComponent(0.05, 0.05, 0.280); - mass.setRelativePosition(Position.TOP); - mass.setPositionValue(0.2); - tube1.addChild(mass); - - // Cord - mass = new MassComponent(0.05, 0.05, 0.125); - mass.setRelativePosition(Position.TOP); - mass.setPositionValue(0.2); - tube1.addChild(mass); - - // Payload - mass = new MassComponent(0.40, R, 1.500); - mass.setRelativePosition(Position.TOP); - mass.setPositionValue(0.25); - tube1.addChild(mass); - - - auxfinset = new TrapezoidFinSet(); - auxfinset.setName("CONTROL"); - auxfinset.setFinCount(2); - auxfinset.setRootChord(0.05); - auxfinset.setTipChord(0.05); - auxfinset.setHeight(0.10); - auxfinset.setSweep(0); - auxfinset.setThickness(0.008); - auxfinset.setCrossSection(CrossSection.AIRFOIL); - auxfinset.setRelativePosition(Position.TOP); - auxfinset.setPositionValue(0.28); - auxfinset.setBaseRotation(Math.PI / 2); - tube1.addChild(auxfinset); - - - - - coupler = new TubeCoupler(); - coupler.setOuterRadiusAutomatic(true); - coupler.setLength(0.28); - coupler.setRelativePosition(Position.TOP); - coupler.setPositionValue(0.47); - coupler.setMassOverridden(true); - coupler.setOverrideMass(0.360); - tube2.addChild(coupler); - - - - // Parachute - mass = new MassComponent(0.1, 0.05, 0.028); - mass.setRelativePosition(Position.TOP); - mass.setPositionValue(0.14); - tube2.addChild(mass); - - Bulkhead bulk = new Bulkhead(); - bulk.setOuterRadiusAutomatic(true); - bulk.setMassOverridden(true); - bulk.setOverrideMass(0.050); - bulk.setRelativePosition(Position.TOP); - bulk.setPositionValue(0.27); - tube2.addChild(bulk); - - // Chord - mass = new MassComponent(0.1, 0.05, 0.125); - mass.setRelativePosition(Position.TOP); - mass.setPositionValue(0.19); - tube2.addChild(mass); - - - - InnerTube inner = new InnerTube(); - inner.setOuterRadius(0.08 / 2); - inner.setInnerRadius(0.0762 / 2); - inner.setLength(0.86); - inner.setMassOverridden(true); - inner.setOverrideMass(0.388); - tube3.addChild(inner); - - - CenteringRing center = new CenteringRing(); - center.setInnerRadiusAutomatic(true); - center.setOuterRadiusAutomatic(true); - center.setLength(0.005); - center.setMassOverridden(true); - center.setOverrideMass(0.038); - center.setRelativePosition(Position.BOTTOM); - center.setPositionValue(0); - tube3.addChild(center); - - - center = new CenteringRing(); - center.setInnerRadiusAutomatic(true); - center.setOuterRadiusAutomatic(true); - center.setLength(0.005); - center.setMassOverridden(true); - center.setOverrideMass(0.038); - center.setRelativePosition(Position.TOP); - center.setPositionValue(0.28); - tube3.addChild(center); - - - center = new CenteringRing(); - center.setInnerRadiusAutomatic(true); - center.setOuterRadiusAutomatic(true); - center.setLength(0.005); - center.setMassOverridden(true); - center.setOverrideMass(0.038); - center.setRelativePosition(Position.TOP); - center.setPositionValue(0.83); - tube3.addChild(center); - - - - - - finset = new TrapezoidFinSet(); - finset.setRootChord(0.495); - finset.setTipChord(0.1); - finset.setHeight(0.185); - finset.setThickness(0.005); - finset.setSweep(0.3); - finset.setRelativePosition(Position.BOTTOM); - finset.setPositionValue(-0.03); - finset.setBaseRotation(Math.PI / 2); - tube3.addChild(finset); - - - finset.setCantAngle(0 * Math.PI / 180); - System.err.println("Fin cant angle: " + (finset.getCantAngle() * 180 / Math.PI)); - - - // Stage construction - rocket.addChild(stage); - rocket.setPerfectFinish(false); - - - - String id = rocket.newMotorConfigurationID(); - tube3.setMotorMount(true); - - // Motor m = Application.getMotorSetDatabase().findMotors(null, null, "L540", Double.NaN, Double.NaN).get(0); - // tube3.setMotor(id, m); - // tube3.setMotorOverhang(0.02); - rocket.getDefaultConfiguration().setMotorConfigurationID(id); - - // tube3.setIgnitionEvent(MotorMount.IgnitionEvent.NEVER); - - rocket.getDefaultConfiguration().setAllStages(); - - - return rocket; - } - - - -} diff --git a/core/src/net/sf/openrocket/util/TextUtil.java b/core/src/net/sf/openrocket/util/TextUtil.java deleted file mode 100644 index 0b86876d..00000000 --- a/core/src/net/sf/openrocket/util/TextUtil.java +++ /dev/null @@ -1,200 +0,0 @@ -package net.sf.openrocket.util; - -import java.nio.ByteBuffer; -import java.nio.charset.Charset; - - -public class TextUtil { - - - private static final char[] HEX = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' - }; - - /** - * Return the byte array for the string in the given charset. - * - * This function is implemented because Froyo (Android API 8) does not support - * String.getBytes(Charset) - * - * @param string - * @param charSet - * @return - */ - public static byte[] convertStringToBytes( String string, Charset charSet ) { - ByteBuffer encoded = charSet.encode(string); - return encoded.array(); - } - - - /** - * Return the bytes formatted as a hexadecimal string. The length of the - * string will be twice the number of bytes, with no spacing between the bytes - * and lowercase letters utilized. - * - * @param bytes the bytes to convert. - * @return the bytes in hexadecimal notation. - */ - public static final String hexString(byte[] bytes) { - StringBuilder sb = new StringBuilder(bytes.length * 2); - for (byte b : bytes) { - sb.append(HEX[(b >>> 4) & 0xF]); - sb.append(HEX[b & 0xF]); - } - return sb.toString(); - } - - /** - * Return a string of the double value with suitable precision (5 digits). - * The string is the shortest representation of the value including the - * required precision. - * - * @param d the value to present. - * @return a representation with suitable precision. - */ - public static final String doubleToString(double d) { - - // Check for special cases - if (MathUtil.equals(d, 0)) - return "0"; - - if (Double.isNaN(d)) - return "NaN"; - - if (Double.isInfinite(d)) { - if (d < 0) - return "-Inf"; - else - return "Inf"; - } - - - final String sign = (d < 0) ? "-" : ""; - double abs = Math.abs(d); - - // Small and large values always in exponential notation - if (abs < 0.001 || abs >= 100000000) { - return sign + exponentialFormat(abs); - } - - // Check whether decimal or exponential notation is shorter - - String exp = exponentialFormat(abs); - String dec = decimalFormat(abs); - - if (dec.length() <= exp.length()) - return sign + dec; - else - return sign + exp; - } - - - /* - * value must be positive and not zero! - */ - private static String exponentialFormat(double value) { - int exp; - - exp = 0; - while (value < 1.0) { - value *= 10; - exp--; - } - while (value >= 10.0) { - value /= 10; - exp++; - } - - return shortDecimal(value, 4) + "e" + exp; - } - - - /* - * value must be positive and not zero! - */ - private static String decimalFormat(double value) { - if (value >= 10000) - return "" + (int) (value + 0.5); - - int decimals = 1; - double v = value; - while (v < 1000) { - v *= 10; - decimals++; - } - - return shortDecimal(value, decimals); - } - - - - - /* - * value must be positive! - */ - private static String shortDecimal(double value, int decimals) { - - // Calculate rounding and limit values (rounding slightly smaller) - int rounding = 1; - double limit = 0.5; - for (int i = 0; i < decimals; i++) { - rounding *= 10; - limit /= 10; - } - - // Round value - value = (Math.rint(value * rounding) + 0.1) / rounding; - - - int whole = (int) value; - value -= whole; - - - if (value < limit) - return "" + whole; - limit *= 10; - - StringBuilder sb = new StringBuilder(); - sb.append("" + whole); - sb.append('.'); - - - for (int i = 0; i < decimals; i++) { - - value *= 10; - whole = (int) value; - value -= whole; - sb.append((char) ('0' + whole)); - - if (value < limit) - return sb.toString(); - limit *= 10; - - } - - return sb.toString(); - } - - - public static String htmlEncode(String s) { - s = s.replace("&", "&"); - s = s.replace("\"", """); - s = s.replace("<", "<"); - s = s.replace(">", ">"); - return s; - } - - /* - * Returns a word-wrapped version of given input string using HTML syntax, wrapped to len characters. - */ - public static String wrap(String in,int len) { - in=in.trim(); - if(in.length()<len) return in; - if(in.substring(0, len).contains("\n")) - return in.substring(0, in.indexOf("\n")).trim() + "\n\n" + wrap(in.substring(in.indexOf("\n") + 1), len); - int place=Math.max(Math.max(in.lastIndexOf(" ",len),in.lastIndexOf("\t",len)),in.lastIndexOf("-",len)); - return "<html>"+in.substring(0,place).trim()+"<br>"+wrap(in.substring(place),len); - } - -} diff --git a/core/src/net/sf/openrocket/util/Transformation.java b/core/src/net/sf/openrocket/util/Transformation.java deleted file mode 100644 index 8656a4f2..00000000 --- a/core/src/net/sf/openrocket/util/Transformation.java +++ /dev/null @@ -1,260 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -/** - * Defines an affine transformation of the form A*x+c, where x and c are Coordinates and - * A is a 3x3 matrix. - * - * The Transformations are immutable. All modification methods return a new transformation. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ - -public class Transformation implements java.io.Serializable { - - - public static final Transformation IDENTITY = - new Transformation(); - - public static final Transformation PROJECT_XY = - new Transformation(new double[][]{{1,0,0},{0,1,0},{0,0,0}}); - public static final Transformation PROJECT_YZ = - new Transformation(new double[][]{{0,0,0},{0,1,0},{0,0,1}}); - public static final Transformation PROJECT_XZ = - new Transformation(new double[][]{{1,0,0},{0,0,0},{0,0,1}}); - - private static final int X = 0; - private static final int Y = 1; - private static final int Z = 2; - - private final Coordinate translate; - private final double[][] rotation = new double[3][3]; - - /** - * Create identity transformation. - */ - public Transformation() { - translate = new Coordinate(0,0,0); - rotation[X][X]=1; - rotation[Y][Y]=1; - rotation[Z][Z]=1; - } - - /** - * Create transformation with only translation. - * @param x Translation in x-axis. - * @param y Translation in y-axis. - * @param z Translation in z-axis. - */ - public Transformation(double x,double y,double z) { - translate = new Coordinate(x,y,z); - rotation[X][X]=1; - rotation[Y][Y]=1; - rotation[Z][Z]=1; - } - - /** - * Create transformation with only translation. - * @param translation The translation term. - */ - public Transformation(Coordinate translation) { - this.translate = translation; - rotation[X][X]=1; - rotation[Y][Y]=1; - rotation[Z][Z]=1; - } - - /** - * Create transformation with given rotation matrix and translation. - * @param rotation - * @param translation - */ - public Transformation(double[][] rotation, Coordinate translation) { - for (int i=0; i<3; i++) - for (int j=0; j<3; j++) - this.rotation[i][j] = rotation[i][j]; - this.translate = translation; - } - - - /** - * Create transformation with given rotation matrix and translation. - * @param rotation - * @param translation - */ - public Transformation(double[][] rotation) { - for (int i=0; i<3; i++) - for (int j=0; j<3; j++) - this.rotation[i][j] = rotation[i][j]; - this.translate = Coordinate.NUL; - } - - - - - - /** - * Transform a coordinate according to this transformation. - * - * @param orig the coordinate to transform. - * @return the result. - */ - public Coordinate transform(Coordinate orig) { - final double x,y,z; - - x = rotation[X][X]*orig.x + rotation[X][Y]*orig.y + rotation[X][Z]*orig.z + translate.x; - y = rotation[Y][X]*orig.x + rotation[Y][Y]*orig.y + rotation[Y][Z]*orig.z + translate.y; - z = rotation[Z][X]*orig.x + rotation[Z][Y]*orig.y + rotation[Z][Z]*orig.z + translate.z; - - return new Coordinate(x,y,z,orig.weight); - } - - - /** - * Transform an array of coordinates. The transformed coordinates are stored - * in the same array, and the array is returned. - * - * @param orig the coordinates to transform. - * @return <code>orig</code>, with the coordinates transformed. - */ - public Coordinate[] transform(Coordinate[] orig) { - for (int i=0; i < orig.length; i++) { - orig[i] = transform(orig[i]); - } - return orig; - } - - /** - * Transforms all coordinates in a Collection. The original coordinate elements are - * removed from the set and replaced with the transformed ones. The Collection given - * must implement the .clear() and .addAll() methods. - * - * @param set Collection of coordinates to transform. - */ - public void transform(Collection<Coordinate> set) { - ArrayList<Coordinate> temp = new ArrayList<Coordinate>(set.size()); - Iterator<Coordinate> iter = set.iterator(); - while (iter.hasNext()) - temp.add(this.transform(iter.next())); - set.clear(); - set.addAll(temp); - } - - /** - * Applies only the linear transformation A*x - * @param orig Coordinate to transform. - */ - public Coordinate linearTransform(Coordinate orig) { - final double x,y,z; - - x = rotation[X][X]*orig.x + rotation[X][Y]*orig.y + rotation[X][Z]*orig.z; - y = rotation[Y][X]*orig.x + rotation[Y][Y]*orig.y + rotation[Y][Z]*orig.z; - z = rotation[Z][X]*orig.x + rotation[Z][Y]*orig.y + rotation[Z][Z]*orig.z; - - return new Coordinate(x,y,z,orig.weight); - } - - /** - * Applies the given transformation before this tranformation. The resulting - * transformation result.transform(c) will equal this.transform(other.transform(c)). - * - * @param other Transformation to apply - * @return The new transformation - */ - public Transformation applyTransformation(Transformation other) { - // other = Ax+b - // this = Cx+d - // C(Ax+b)+d = CAx + Cb+d - - // Translational portion - Transformation combined = new Transformation( - this.linearTransform(other.translate).add(this.translate) - ); - - // Linear portion - for (int i=0; i<3; i++) { - final double x,y,z; - x = rotation[i][X]; - y = rotation[i][Y]; - z = rotation[i][Z]; - combined.rotation[i][X] = - x*other.rotation[X][X] + y*other.rotation[Y][X] + z*other.rotation[Z][X]; - combined.rotation[i][Y] = - x*other.rotation[X][Y] + y*other.rotation[Y][Y] + z*other.rotation[Z][Y]; - combined.rotation[i][Z] = - x*other.rotation[X][Z] + y*other.rotation[Y][Z] + z*other.rotation[Z][Z]; - } - return combined; - } - - - /** - * Rotate around x-axis a given angle. - * @param theta The angle to rotate in radians. - * @return The transformation. - */ - public static Transformation rotate_x(double theta) { - return new Transformation(new double[][]{ - {1,0,0}, - {0,Math.cos(theta),-Math.sin(theta)}, - {0,Math.sin(theta),Math.cos(theta)}}); - } - - /** - * Rotate around y-axis a given angle. - * @param theta The angle to rotate in radians. - * @return The transformation. - */ - public static Transformation rotate_y(double theta) { - return new Transformation(new double[][]{ - {Math.cos(theta),0,Math.sin(theta)}, - {0,1,0}, - {-Math.sin(theta),0,Math.cos(theta)}}); - } - - /** - * Rotate around z-axis a given angle. - * @param theta The angle to rotate in radians. - * @return The transformation. - */ - public static Transformation rotate_z(double theta) { - return new Transformation(new double[][]{ - {Math.cos(theta),-Math.sin(theta),0}, - {Math.sin(theta),Math.cos(theta),0}, - {0,0,1}}); - } - - - - public void print(String... str) { - for (String s: str) { - System.out.println(s); - } - System.out.printf("[%3.2f %3.2f %3.2f] [%3.2f]\n", - rotation[X][X],rotation[X][Y],rotation[X][Z],translate.x); - System.out.printf("[%3.2f %3.2f %3.2f] + [%3.2f]\n", - rotation[Y][X],rotation[Y][Y],rotation[Y][Z],translate.y); - System.out.printf("[%3.2f %3.2f %3.2f] [%3.2f]\n", - rotation[Z][X],rotation[Z][Y],rotation[Z][Z],translate.z); - System.out.println(); - } - - - @Override - public boolean equals(Object other) { - if (!(other instanceof Transformation)) - return false; - Transformation o = (Transformation)other; - for (int i=0; i<3; i++) { - for (int j=0; j<3; j++) { - if (!MathUtil.equals(this.rotation[i][j], o.rotation[i][j])) - return false; - } - } - return this.translate.equals(o.translate); - } - -} diff --git a/core/src/net/sf/openrocket/util/UncloseableInputStream.java b/core/src/net/sf/openrocket/util/UncloseableInputStream.java deleted file mode 100644 index ca0779fc..00000000 --- a/core/src/net/sf/openrocket/util/UncloseableInputStream.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.sf.openrocket.util; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * An InputStream filter that prevents closing the source stream. The - * {@link #close()} method is overridden to do nothing. - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class UncloseableInputStream extends FilterInputStream { - - public UncloseableInputStream(InputStream in) { - super(in); - } - - @Override - public void close() throws IOException { - // No-op - } -} diff --git a/core/src/net/sf/openrocket/util/UniqueID.java b/core/src/net/sf/openrocket/util/UniqueID.java deleted file mode 100644 index f9987c76..00000000 --- a/core/src/net/sf/openrocket/util/UniqueID.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; - -public class UniqueID { - - private static AtomicInteger nextId = new AtomicInteger(1); - - /** - * Return a positive integer ID unique during this program execution. - * <p> - * The following is guaranteed of the returned ID values: - * <ul> - * <li>The value is unique during this program execution - * <li>The value is positive - * <li>The values are monotonically increasing - * </ul> - * <p> - * This method is thread-safe and fast. - * - * @return a positive integer ID unique in this program execution. - */ - public static int next() { - return nextId.getAndIncrement(); - } - - - /** - * Return a new universally unique ID string. - * - * @return a unique identifier string. - */ - public static String uuid() { - return UUID.randomUUID().toString(); - } - -} diff --git a/core/src/net/sf/openrocket/util/Utils.java b/core/src/net/sf/openrocket/util/Utils.java deleted file mode 100644 index 93d320ef..00000000 --- a/core/src/net/sf/openrocket/util/Utils.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.sf.openrocket.util; - -public class Utils { - - /** - * Null-safe equals method. - * - * @param first the first object to compare - * @param second the second object to compare - * @return whether the two objects are both equal or both <code>null</code> - */ - public static boolean equals(Object first, Object second) { - if (first == null) { - return second == null; - } else { - return first.equals(second); - } - } - - - /** - * Check whether an array contains a specified object. - * - * @param array the array to search - * @param search the object to search for - * @return whether the object was in the array - */ - public static boolean contains(Object[] array, Object search) { - for (Object o : array) { - if (equals(o, search)) { - return true; - } - } - return false; - } - -} diff --git a/core/src/net/sf/openrocket/util/WorldCoordinate.java b/core/src/net/sf/openrocket/util/WorldCoordinate.java deleted file mode 100644 index 762b0295..00000000 --- a/core/src/net/sf/openrocket/util/WorldCoordinate.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.util; - -/** - * A WorldCoordinate contains the latitude, longitude and altitude position of a rocket. - */ -public class WorldCoordinate { - - /** Mean Earth radius */ - public static final double REARTH = 6371000.0; - /** Sidearial Earth rotation rate */ - public static final double EROT = 7.2921150e-5; - - - private final double lat, lon, alt; - - /** - * Constructs a new WorldCoordinate - * - * @param lat latitude in degrees north. From -90 to 90, values outside are clamped. - * @param lon longitude in degrees east. From -180 to 180, values outside are reduced to the range. - * @param alt altitude in meters. Unbounded. - */ - public WorldCoordinate(double lat, double lon, double alt) { - this.lat = MathUtil.clamp(Math.toRadians(lat), -Math.PI / 2, Math.PI / 2); - this.lon = MathUtil.reduce180(Math.toRadians(lon)); - this.alt = alt; - } - - - /** - * Returns the altitude. - */ - public double getAltitude() { - return this.alt; - } - - /** - * Returns Longitude in radians - */ - public double getLongitudeRad() { - return this.lon; - } - - /** - * Returns Longitude in degrees - */ - public double getLongitudeDeg() { - return Math.toDegrees(this.lon); - } - - /** - * Returns latitude in radians - */ - public double getLatitudeRad() { - return this.lat; - } - - /** - * Returns latitude in degrees - */ - public double getLatitudeDeg() { - return Math.toDegrees(this.lat); - } - - - - @Override - public String toString() { - return "WorldCoordinate[lat=" + getLatitudeDeg() + ", lon=" + getLongitudeDeg() + ", alt=" + getAltitude() + "]"; - } - - - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof WorldCoordinate)) { - return false; - } - WorldCoordinate other = (WorldCoordinate) obj; - return (MathUtil.equals(this.lat, other.lat) && - MathUtil.equals(this.lon, other.lon) && MathUtil.equals(this.alt, other.alt)); - } - - @Override - public int hashCode() { - return ((int) (1000 * (lat + lon + alt))); - } - -} diff --git a/core/src/net/sf/openrocket/util/enums/EnumConversion.java b/core/src/net/sf/openrocket/util/enums/EnumConversion.java deleted file mode 100644 index 4b8624f6..00000000 --- a/core/src/net/sf/openrocket/util/enums/EnumConversion.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.sf.openrocket.util.enums; - -public interface EnumConversion { - - public String convert(Enum<?> e); - -} diff --git a/core/src/net/sf/openrocket/util/enums/EnumName.java b/core/src/net/sf/openrocket/util/enums/EnumName.java deleted file mode 100644 index 78210612..00000000 --- a/core/src/net/sf/openrocket/util/enums/EnumName.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.sf.openrocket.util.enums; - -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -import net.sf.openrocket.util.BugException; - -public class EnumName<E extends Enum<E>> { - - public static final EnumConversion NAME = new EnumConversion() { - @Override - public String convert(Enum<?> e) { - return e.name(); - } - }; - - - private final Class<E> type; - private final Map<E, String> map; - private final Map<String, E> reverse; - - public EnumName(Class<E> type) { - this(type, NAME); - } - - public EnumName(Class<E> type, EnumConversion conversion) { - this.type = type; - map = new EnumMap<E, String>(type); - reverse = new HashMap<String, E>(); - - E[] keys = type.getEnumConstants(); - if (keys == null) { - throw new IllegalArgumentException("Type " + type + " is not of enum type"); - } - for (E key : keys) { - String value = conversion.convert(key); - if (reverse.containsKey(value)) { - throw new BugException("Two enum constants were converted to have the name value: " + reverse.get(value) - + " and " + key + " both convert to '" + value + "'"); - } - map.put(key, value); - reverse.put(value, key); - - } - } - - - - public String getName(E key) { - String name = map.get(key); - if (name == null) { - throw new IllegalArgumentException("No name found for enum " + key + " from map of type " + type); - } - return name; - } - - public E getEnum(String name) { - return reverse.get(name); - } - - -} diff --git a/core/src/net/sf/openrocket/utils/GraphicalMotorSelector.java b/core/src/net/sf/openrocket/utils/GraphicalMotorSelector.java deleted file mode 100644 index 1087c5df..00000000 --- a/core/src/net/sf/openrocket/utils/GraphicalMotorSelector.java +++ /dev/null @@ -1,145 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.Pair; - -public class GraphicalMotorSelector { - - public static void main(String[] args) throws IOException { - - if (args.length == 0) { - System.err.println("MotorPlot <files>"); - System.exit(1); - } - - // Load files - Map<String, List<Pair<String, ThrustCurveMotor>>> map = - new LinkedHashMap<String, List<Pair<String, ThrustCurveMotor>>>(); - - GeneralMotorLoader loader = new GeneralMotorLoader(); - for (String file : args) { - - for (Motor motor : loader.load(new FileInputStream(file), file)) { - ThrustCurveMotor m = (ThrustCurveMotor) motor; - System.out.println("Loaded " + m + " from file " + file); - - Pair<String, ThrustCurveMotor> pair = new Pair<String, ThrustCurveMotor>(file, m); - String key = m.getManufacturer() + ":" + m.getDesignation(); - - List<Pair<String, ThrustCurveMotor>> list = map.get(key); - if (list == null) { - list = new ArrayList<Pair<String, ThrustCurveMotor>>(); - map.put(key, list); - } - - list.add(pair); - } - } - - - // Go through different motors - int count = 0; - for (String key : map.keySet()) { - count++; - List<Pair<String, ThrustCurveMotor>> list = map.get(key); - - - // Select best one of identical motors - List<String> filenames = new ArrayList<String>(); - List<ThrustCurveMotor> motors = new ArrayList<ThrustCurveMotor>(); - for (Pair<String, ThrustCurveMotor> pair : list) { - String file = pair.getU(); - ThrustCurveMotor m = pair.getV(); - - int index = indexOf(motors, m); - if (index >= 0) { - // Replace previous if this has more delays, a known type or longer comment - ThrustCurveMotor m2 = motors.get(index); - if (m.getStandardDelays().length > m2.getStandardDelays().length || - (m2.getMotorType() == Motor.Type.UNKNOWN && - m.getMotorType() != Motor.Type.UNKNOWN) || - (m.getDescription().trim().length() > - m2.getDescription().trim().length())) { - - filenames.set(index, file); - motors.set(index, m); - - } - } else { - filenames.add(file); - motors.add(m); - } - } - - if (filenames.size() == 0) { - - System.out.println("ERROR selecting from " + list); - System.exit(1); - - } else if (filenames.size() == 1) { - - select(filenames.get(0), list, false); - - } else { - - System.out.println("Choosing from " + filenames + - " (" + count + "/" + map.size() + ")"); - MotorPlot plot = new MotorPlot(filenames, motors); - plot.setVisible(true); - plot.dispose(); - int n = plot.getSelected(); - if (n < 0) { - System.out.println("NONE SELECTED from " + filenames); - } else { - select(filenames.get(n), list, true); - } - - } - - } - - } - - private static void select(String selected, List<Pair<String, ThrustCurveMotor>> list, boolean manual) { - System.out.print("SELECT " + selected + " "); - if (manual) { - System.out.println("(manual)"); - } else if (list.size() == 1) { - System.out.println("(only)"); - } else { - System.out.println("(identical)"); - } - - for (Pair<String, ThrustCurveMotor> pair : list) { - String file = pair.getU(); - if (!file.equals(selected)) { - System.out.println("IGNORE " + file); - } - } - } - - - private static int indexOf(List<ThrustCurveMotor> motors, ThrustCurveMotor motor) { - for (int i = 0; i < motors.size(); i++) { - ThrustCurveMotor m = motors.get(i); - // TODO: Similar? - if (m.equals(motor)) { - if (m.getStandardDelays().length == 0 || motor.getStandardDelays().length == 0 || - Arrays.equals(m.getStandardDelays(), motor.getStandardDelays())) { - return i; - } - } - } - return -1; - } -} diff --git a/core/src/net/sf/openrocket/utils/L10NGenerator.java b/core/src/net/sf/openrocket/utils/L10NGenerator.java deleted file mode 100644 index de64a101..00000000 --- a/core/src/net/sf/openrocket/utils/L10NGenerator.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.utils; - -import java.text.Normalizer; - -import net.sf.openrocket.util.Chars; - -/** - * This class is used to generate the map used in L10N class - * due to the fact that Android does not support java.text.Normalizer. - */ -public class L10NGenerator { - - public static void main(String[] args) throws Exception { - - // Latin chars - for (char ch = 128; ch < 0x250; ch++) { - output(ch); - } - // Superscript numbers - for (char ch = 0x2070; ch <= 0x2079; ch++) { - output(ch); - } - // Subscript numbers - for (char ch = 0x2080; ch <= 0x2089; ch++) { - output(ch); - } - output(Chars.FRACTION); - print(Chars.ZWSP, " "); - print(Chars.NBSP, " "); - } - - private static void output(char ch) { - String text = "" + ch; - StringBuilder sb = new StringBuilder(text.length()); - // s = normalize(s); - text = Normalizer.normalize(text, Normalizer.Form.NFKD); - - for (char c : text.toCharArray()) { - if (c < 128) { - sb.append(c); - } else if (c == Chars.FRACTION) { - sb.append('/'); - } - } - - text = sb.toString().trim(); - - if (text.length() > 0) { - print(ch, text); - } - } - - private static void print(char ch, String text) { - System.out.printf("m.put('\\u%04x', \"%s\");\n", (int) ch, text); - } -} diff --git a/core/src/net/sf/openrocket/utils/LogSpeedTest.java b/core/src/net/sf/openrocket/utils/LogSpeedTest.java deleted file mode 100644 index 4ca2f9a4..00000000 --- a/core/src/net/sf/openrocket/utils/LogSpeedTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.sf.openrocket.utils; - -import net.sf.openrocket.logging.DelegatorLogger; -import net.sf.openrocket.logging.LogHelper; -import net.sf.openrocket.logging.LogLevel; - -public class LogSpeedTest { - private static LogHelper log; - - private static final int COUNT = 1000000; - - public static void main(String[] args) { - - System.setProperty("openrocket.log.tracelevel", "user"); - log = new DelegatorLogger(); - - for (LogLevel l : LogLevel.values()) { - for (int i = 0; i < 3; i++) { - long t0 = System.currentTimeMillis(); - test(l); - long t1 = System.currentTimeMillis(); - System.out.println("Level " + l + ": " + (t1 - t0) + " ms for " + COUNT + " lines"); - } - } - - } - - - private static void test(LogLevel level) { - for (int i = 0; i < COUNT; i++) { - log.log(level, "Message " + i); - } - } - -} diff --git a/core/src/net/sf/openrocket/utils/MotorCheck.java b/core/src/net/sf/openrocket/utils/MotorCheck.java deleted file mode 100644 index 5710486d..00000000 --- a/core/src/net/sf/openrocket/utils/MotorCheck.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.file.motor.MotorLoader; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; - -public class MotorCheck { - - // Warn if less that this many points - public static final int WARN_POINTS = 6; - - - public static void main(String[] args) { - MotorLoader loader = new GeneralMotorLoader(); - - // Load files - for (String file : args) { - System.out.print("Checking " + file + "... "); - System.out.flush(); - - boolean ok = true; - - List<Motor> motors = null; - try { - InputStream stream = new FileInputStream(file); - motors = loader.load(stream, file); - stream.close(); - } catch (IOException e) { - System.out.println("ERROR: " + e.getMessage()); - e.printStackTrace(System.out); - ok = false; - } - - String base = file.split("_")[0]; - Manufacturer mfg = Manufacturer.getManufacturer(base); - - if (motors != null) { - if (motors.size() == 0) { - System.out.println("ERROR: File contained no motors"); - ok = false; - } else { - for (Motor motor : motors) { - ThrustCurveMotor m = (ThrustCurveMotor) motor; - double sum = 0; - sum += m.getAverageThrustEstimate(); - sum += m.getBurnTimeEstimate(); - sum += m.getTotalImpulseEstimate(); - // sum += m.getTotalTime(); - sum += m.getDiameter(); - sum += m.getLength(); - sum += m.getEmptyCG().weight; - sum += m.getEmptyCG().x; - sum += m.getLaunchCG().weight; - sum += m.getLaunchCG().x; - sum += m.getMaxThrustEstimate(); - if (Double.isInfinite(sum) || Double.isNaN(sum)) { - System.out.println("ERROR: Invalid motor values"); - ok = false; - } - - if (m.getManufacturer() != mfg) { - System.out.println("ERROR: Inconsistent manufacturer " + - m.getManufacturer() + " (file name indicates " + mfg - + ")"); - ok = false; - } - - int points = ((ThrustCurveMotor) m).getTimePoints().length; - if (points < WARN_POINTS) { - System.out.println("WARNING: Only " + points + " data points"); - ok = false; - } - } - } - } - - if (ok) { - System.out.println("OK"); - } - } - } -} diff --git a/core/src/net/sf/openrocket/utils/MotorCompare.java b/core/src/net/sf/openrocket/utils/MotorCompare.java deleted file mode 100644 index dcb16aeb..00000000 --- a/core/src/net/sf/openrocket/utils/MotorCompare.java +++ /dev/null @@ -1,336 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.file.motor.MotorLoader; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; - -public class MotorCompare { - - /** Maximum allowed difference in maximum thrust */ - private static final double MAX_THRUST_MARGIN = 0.30; - /** Maximum allowed difference in total impulse */ - private static final double TOTAL_IMPULSE_MARGIN = 0.20; - /** Maximum allowed difference in mass values */ - private static final double MASS_MARGIN = 0.20; - - /** Number of time points in thrust curve to compare */ - private static final int DIVISIONS = 100; - /** Maximum difference in thrust for a time point to be considered invalid */ - private static final double THRUST_MARGIN = 0.20; - /** Number of invalid time points allowed */ - private static final int ALLOWED_INVALID_POINTS = 20; - - /** Minimum number of thrust curve points allowed (incl. start and end points) */ - private static final int MIN_POINTS = 7; - - - public static void main(String[] args) throws IOException { - final double maxThrust; - final double maxTime; - int maxDelays; - int maxPoints; - int maxCommentLen; - - double min, max; - double diff; - - int[] goodness; - - boolean bad = false; - List<String> cause = new ArrayList<String>(); - - MotorLoader loader = new GeneralMotorLoader(); - List<ThrustCurveMotor> motors = new ArrayList<ThrustCurveMotor>(); - List<String> files = new ArrayList<String>(); - - // Load files - System.out.printf("Files :"); - for (String file : args) { - System.out.printf("\t%s", file); - List<Motor> m = null; - try { - InputStream stream = new FileInputStream(file); - m = loader.load(stream, file); - stream.close(); - } catch (IOException e) { - e.printStackTrace(); - System.out.print("(ERR:" + e.getMessage() + ")"); - } - if (m != null) { - motors.addAll((List) m); - for (int i = 0; i < m.size(); i++) - files.add(file); - } - } - System.out.println(); - - compare(motors, files); - } - - - - - - public static void compare(List<ThrustCurveMotor> motors, List<String> files) { - final double maxThrust; - final double maxTime; - int maxDelays; - int maxPoints; - int maxCommentLen; - - double min, max; - double diff; - - int[] goodness; - - boolean bad = false; - List<String> cause = new ArrayList<String>(); - - - if (motors.size() == 0) { - System.err.println("No motors loaded."); - System.out.println("ERROR: No motors loaded.\n"); - return; - - } - - if (motors.size() == 1) { - System.out.println("Best (ONLY): " + files.get(0)); - System.out.println(); - return; - } - - final int n = motors.size(); - goodness = new int[n]; - - - for (String s : files) { - System.out.print("\t" + s); - } - System.out.println(); - - - // Designations - System.out.printf("Designation:"); - String des = motors.get(0).getDesignation(); - for (Motor m : motors) { - System.out.printf("\t%s", m.getDesignation()); - if (!m.getDesignation().equals(des)) { - cause.add("Designation"); - bad = true; - } - } - System.out.println(); - - // Manufacturers - System.out.printf("Manufacture:"); - Manufacturer mfg = motors.get(0).getManufacturer(); - for (ThrustCurveMotor m : motors) { - System.out.printf("\t%s", m.getManufacturer()); - if (m.getManufacturer() != mfg) { - cause.add("Manufacturer"); - bad = true; - } - } - System.out.println(); - - - // Max. thrust - max = 0; - min = Double.MAX_VALUE; - System.out.printf("Max.thrust :"); - for (Motor m : motors) { - double f = m.getMaxThrustEstimate(); - System.out.printf("\t%.2f", f); - max = Math.max(max, f); - min = Math.min(min, f); - } - diff = (max - min) / min; - if (diff > MAX_THRUST_MARGIN) { - bad = true; - cause.add("Max thrust"); - } - System.out.printf("\t(discrepancy %.1f%%)\n", 100.0 * diff); - maxThrust = (min + max) / 2; - - - // Total time - max = 0; - min = Double.MAX_VALUE; - System.out.printf("Burn time :"); - for (Motor m : motors) { - double t = m.getBurnTimeEstimate(); - System.out.printf("\t%.2f", t); - max = Math.max(max, t); - min = Math.min(min, t); - } - diff = (max - min) / min; - System.out.printf("\t(discrepancy %.1f%%)\n", 100.0 * diff); - maxTime = max; - - - // Total impulse - max = 0; - min = Double.MAX_VALUE; - System.out.printf("Impulse :"); - for (Motor m : motors) { - double f = m.getTotalImpulseEstimate(); - System.out.printf("\t%.2f", f); - max = Math.max(max, f); - min = Math.min(min, f); - } - diff = (max - min) / min; - if (diff > TOTAL_IMPULSE_MARGIN) { - bad = true; - cause.add("Total impulse"); - } - System.out.printf("\t(discrepancy %.1f%%)\n", 100.0 * diff); - - - // Initial mass - max = 0; - min = Double.MAX_VALUE; - System.out.printf("Init mass :"); - for (Motor m : motors) { - double f = m.getLaunchCG().weight; - System.out.printf("\t%.2f", f * 1000); - max = Math.max(max, f); - min = Math.min(min, f); - } - diff = (max - min) / min; - if (diff > MASS_MARGIN) { - bad = true; - cause.add("Initial mass"); - } - System.out.printf("\t(discrepancy %.1f%%)\n", 100.0 * diff); - - - // Empty mass - max = 0; - min = Double.MAX_VALUE; - System.out.printf("Empty mass :"); - for (Motor m : motors) { - double f = m.getEmptyCG().weight; - System.out.printf("\t%.2f", f * 1000); - max = Math.max(max, f); - min = Math.min(min, f); - } - diff = (max - min) / min; - if (diff > MASS_MARGIN) { - bad = true; - cause.add("Empty mass"); - } - System.out.printf("\t(discrepancy %.1f%%)\n", 100.0 * diff); - - - // Delays - maxDelays = 0; - System.out.printf("Delays :"); - for (ThrustCurveMotor m : motors) { - System.out.printf("\t%d", m.getStandardDelays().length); - maxDelays = Math.max(maxDelays, m.getStandardDelays().length); - } - System.out.println(); - - - // Data points - maxPoints = 0; - System.out.printf("Points :"); - for (Motor m : motors) { - System.out.printf("\t%d", ((ThrustCurveMotor) m).getTimePoints().length); - maxPoints = Math.max(maxPoints, ((ThrustCurveMotor) m).getTimePoints().length); - } - System.out.println(); - - - // Comment length - maxCommentLen = 0; - System.out.printf("Comment len:"); - for (Motor m : motors) { - System.out.printf("\t%d", m.getDescription().length()); - maxCommentLen = Math.max(maxCommentLen, m.getDescription().length()); - } - System.out.println(); - - - if (bad) { - String str = "ERROR: "; - for (int i = 0; i < cause.size(); i++) { - str += cause.get(i); - if (i < cause.size() - 1) - str += ", "; - } - str += " differs"; - System.out.println(str); - System.out.println(); - return; - } - - // Check consistency - // TODO: Does not check consistency - // int invalidPoints = 0; - // for (int i = 0; i < DIVISIONS; i++) { - // double t = maxTime * i / (DIVISIONS - 1); - // min = Double.MAX_VALUE; - // max = 0; - // // System.out.printf("%.2f:", t); - // for (Motor m : motors) { - // double f = m.getThrust(t); - // // System.out.printf("\t%.2f", f); - // min = Math.min(min, f); - // max = Math.max(max, f); - // } - // diff = (max - min) / maxThrust; - // // System.out.printf("\t(diff %.1f%%)\n", diff*100); - // if (diff > THRUST_MARGIN) - // invalidPoints++; - // } - // - // if (invalidPoints > ALLOWED_INVALID_POINTS) { - // System.out.println("ERROR: " + invalidPoints + "/" + DIVISIONS - // + " points have thrust differing over " + (THRUST_MARGIN * 100) + "%"); - // System.out.println(); - // return; - // } - - - // Check goodness - for (int i = 0; i < n; i++) { - ThrustCurveMotor m = motors.get(i); - if (m.getStandardDelays().length == maxDelays) - goodness[i] += 1000; - if (((ThrustCurveMotor) m).getTimePoints().length == maxPoints) - goodness[i] += 100; - if (m.getDescription().length() == maxCommentLen) - goodness[i] += 10; - if (files.get(i).matches(".*\\.[rR][sS][eE]$")) - goodness[i] += 1; - } - int best = 0; - for (int i = 1; i < n; i++) { - if (goodness[i] > goodness[best]) - best = i; - } - - - // Verify enough points - int pts = ((ThrustCurveMotor) motors.get(best)).getTimePoints().length; - if (pts < MIN_POINTS) { - System.out.println("WARNING: Best has only " + pts + " data points"); - } - - System.out.println("Best (" + goodness[best] + "): " + files.get(best)); - System.out.println(); - - - } - -} diff --git a/core/src/net/sf/openrocket/utils/MotorCompareAll.java b/core/src/net/sf/openrocket/utils/MotorCompareAll.java deleted file mode 100644 index f3a6f8a7..00000000 --- a/core/src/net/sf/openrocket/utils/MotorCompareAll.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.text.Collator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.file.motor.MotorLoader; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.Pair; - -public class MotorCompareAll { - - /* - * Usage: - * - * java MotorCompareAll *.eng *.rse - */ - public static void main(String[] args) throws IOException { - - Map<String, Pair<List<ThrustCurveMotor>, List<String>>> map = - new HashMap<String, Pair<List<ThrustCurveMotor>, List<String>>>(); - - MotorLoader loader = new GeneralMotorLoader(); - - for (String filename : args) { - - List<ThrustCurveMotor> motors = (List) loader.load(new FileInputStream(filename), filename); - - for (ThrustCurveMotor m : motors) { - String key = m.getManufacturer() + ":" + m.getDesignation(); - Pair<List<ThrustCurveMotor>, List<String>> pair = map.get(key); - if (pair == null) { - pair = new Pair<List<ThrustCurveMotor>, List<String>> - (new ArrayList<ThrustCurveMotor>(), new ArrayList<String>()); - map.put(key, pair); - } - pair.getU().add(m); - pair.getV().add(filename); - } - } - - Collator collator = Collator.getInstance(); - - List<String> keys = new ArrayList<String>(map.keySet()); - Collections.sort(keys, collator); - for (String basename : keys) { - Pair<List<ThrustCurveMotor>, List<String>> pair = map.get(basename); - System.err.println(basename + ": " + pair.getV()); - MotorCompare.compare(pair.getU(), pair.getV()); - } - } - -} diff --git a/core/src/net/sf/openrocket/utils/MotorCorrelation.java b/core/src/net/sf/openrocket/utils/MotorCorrelation.java deleted file mode 100644 index e978b0cf..00000000 --- a/core/src/net/sf/openrocket/utils/MotorCorrelation.java +++ /dev/null @@ -1,145 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.file.motor.MotorLoader; -import net.sf.openrocket.logging.LogLevel; -import net.sf.openrocket.models.atmosphere.AtmosphericConditions; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorDigest; -import net.sf.openrocket.motor.MotorInstance; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.BugException; -import net.sf.openrocket.util.MathUtil; - -public class MotorCorrelation { - - /** - * Return a measure of motor similarity. The measure is a value between 0.0 and 1.0. - * The larger the value, the more similar the motor thrust curves are, for value 1.0 they - * are identical. - * <p> - * This method takes into account the thrust curve shape, average thrust, burn time and - * total impulse of the motor. The similarity is the minimum of all of these. - * - * @param motor1 the first motor - * @param motor2 the second motor - * @return the similarity of the two motors - */ - public static double similarity(Motor motor1, Motor motor2) { - double d; - - d = crossCorrelation(motor1, motor2); - d = Math.min(d, diff(motor1.getAverageThrustEstimate(), motor2.getAverageThrustEstimate())); - d = Math.min(d, 2 * diff(motor1.getBurnTimeEstimate(), motor2.getBurnTimeEstimate())); - d = Math.min(d, diff(motor1.getTotalImpulseEstimate(), motor2.getTotalImpulseEstimate())); - - return d; - } - - - private static double diff(double a, double b) { - double min = Math.min(a, b); - double max = Math.max(a, b); - - if (MathUtil.equals(max, 0)) - return 1.0; - return min / max; - } - - - /** - * Compute the cross-correlation of the thrust curves of the two motors. The result is - * a double between 0 and 1 (inclusive). The closer the return value is to one the more - * similar the thrust curves are. - * - * @param motor1 the first motor. - * @param motor2 the second motor. - * @return the scaled cross-correlation of the two thrust curves. - */ - public static double crossCorrelation(Motor motor1, Motor motor2) { - MotorInstance m1 = motor1.getInstance(); - MotorInstance m2 = motor2.getInstance(); - - AtmosphericConditions cond = new AtmosphericConditions(); - - double t; - double auto1 = 0; - double auto2 = 0; - double cross = 0; - for (t = 0; t < 1000; t += 0.01) { - m1.step(t, 0, cond); - m2.step(t, 0, cond); - - double t1 = m1.getThrust(); - double t2 = m2.getThrust(); - - if (t1 < 0 || t2 < 0) { - throw new BugException("Negative thrust, t1=" + t1 + " t2=" + t2); - } - - auto1 += t1 * t1; - auto2 += t2 * t2; - cross += t1 * t2; - } - - double auto = Math.max(auto1, auto2); - - if (MathUtil.equals(auto, 0)) { - return 1.0; - } - - return cross / auto; - } - - - - - public static void main(String[] args) { - Application.setLogOutputLevel(LogLevel.WARN); - - MotorLoader loader = new GeneralMotorLoader(); - List<Motor> motors = new ArrayList<Motor>(); - List<String> files = new ArrayList<String>(); - - // Load files - for (String file : args) { - List<Motor> m = null; - try { - InputStream stream = new FileInputStream(file); - m = loader.load(stream, file); - stream.close(); - } catch (IOException e) { - e.printStackTrace(); - System.exit(1); - } - if (m != null) { - motors.addAll(m); - for (int i = 0; i < m.size(); i++) - files.add(file); - } - } - - // Output motor digests - final int count = motors.size(); - for (int i = 0; i < count; i++) { - System.out.println(files.get(i) + ": " + ((ThrustCurveMotor) motors.get(i)).getDigest()); - } - - // Cross-correlate every pair - for (int i = 0; i < count; i++) { - for (int j = i + 1; j < count; j++) { - System.out.println(files.get(i) + " " + files.get(j) + " : " + - crossCorrelation(motors.get(i), motors.get(j))); - } - } - - } - -} \ No newline at end of file diff --git a/core/src/net/sf/openrocket/utils/MotorDigester.java b/core/src/net/sf/openrocket/utils/MotorDigester.java deleted file mode 100644 index 27b6d23f..00000000 --- a/core/src/net/sf/openrocket/utils/MotorDigester.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.file.motor.MotorLoader; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorDigest; -import net.sf.openrocket.motor.ThrustCurveMotor; - -public class MotorDigester { - - public static void main(String[] args) { - final MotorLoader loader = new GeneralMotorLoader(); - final boolean printFileNames; - - if (args.length == 0) { - System.err.println("Usage: MotorDigester <files>"); - printFileNames = false; - System.exit(1); - } else if (args.length == 1) { - printFileNames = false; - } else { - printFileNames = true; - } - - - for (String file : args) { - - List<Motor> motors = null; - try { - InputStream stream = new FileInputStream(file); - motors = loader.load(stream, file); - stream.close(); - } catch (IOException e) { - System.err.println("ERROR: " + e.getMessage()); - e.printStackTrace(); - continue; - } - - for (Motor m : motors) { - if (!(m instanceof ThrustCurveMotor)) { - System.err.println(file + ": Not ThrustCurveMotor: " + m); - continue; - } - - String digest = ((ThrustCurveMotor) m).getDigest(); - if (printFileNames) { - System.out.print(file + ": "); - } - System.out.println(digest); - } - } - - } - -} diff --git a/core/src/net/sf/openrocket/utils/MotorPlot.java b/core/src/net/sf/openrocket/utils/MotorPlot.java deleted file mode 100644 index f3b74310..00000000 --- a/core/src/net/sf/openrocket/utils/MotorPlot.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.sf.openrocket.utils; - -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.JTextArea; -import javax.swing.SwingUtilities; - -import net.miginfocom.swing.MigLayout; -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.gui.util.GUIUtil; -import net.sf.openrocket.l10n.Translator; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.startup.Application; - -import org.jfree.chart.ChartFactory; -import org.jfree.chart.ChartPanel; -import org.jfree.chart.JFreeChart; -import org.jfree.chart.plot.PlotOrientation; -import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; -import org.jfree.data.xy.XYSeries; -import org.jfree.data.xy.XYSeriesCollection; - -public class MotorPlot extends JDialog { - - private int selected = -1; - private static final Translator trans = Application.getTranslator(); - - public MotorPlot(List<String> filenames, List<ThrustCurveMotor> motors) { - //// Motor plot - super((JFrame) null, trans.get("MotorPlot.title.Motorplot"), true); - - JTabbedPane tabs = new JTabbedPane(); - for (int i = 0; i < filenames.size(); i++) { - JPanel pane = createPlotPanel((ThrustCurveMotor) motors.get(i)); - - //// Select button - JButton button = new JButton(trans.get("MotorPlot.but.Select")); - final int number = i; - button.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - selected = number; - MotorPlot.this.setVisible(false); - } - }); - pane.add(button, "wrap", 0); - - tabs.addTab(filenames.get(i), pane); - } - - this.add(tabs); - - this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - this.setLocationByPlatform(true); - this.validate(); - this.pack(); - } - - - private JPanel createPlotPanel(ThrustCurveMotor motor) { - JPanel panel = new JPanel(new MigLayout()); - - - XYSeries series = new XYSeries("", false, true); - double[] time = motor.getTimePoints(); - double[] thrust = motor.getThrustPoints(); - - for (int i = 0; i < time.length; i++) { - series.add(time[i], thrust[i]); - } - - // Create the chart using the factory to get all default settings - JFreeChart chart = ChartFactory.createXYLineChart( - //// Motor thrust curve - trans.get("MotorPlot.Chart.Motorthrustcurve"), - //// Time / s - trans.get("MotorPlot.Chart.Time"), - //// Thrust / N - trans.get("MotorPlot.Chart.Thrust"), - new XYSeriesCollection(series), - PlotOrientation.VERTICAL, - true, - true, - false - ); - - ((XYLineAndShapeRenderer) chart.getXYPlot().getRenderer()).setShapesVisible(true); - - ChartPanel chartPanel = new ChartPanel(chart, - false, // properties - true, // save - false, // print - true, // zoom - true); // tooltips - chartPanel.setMouseWheelEnabled(true); - chartPanel.setEnforceFileExtensions(true); - chartPanel.setInitialDelay(500); - - chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1)); - - panel.add(chartPanel, "grow, wrap para"); - - - JTextArea area = new JTextArea(5, 40); - StringBuilder sb = new StringBuilder(); - //// Designation: - sb.append("MotorPlot.txt.Designation" + " ").append(motor.getDesignation()).append(" "); - //// Manufacturer: - sb.append("MotorPlot.txt.Manufacturer" + " ").append(motor.getManufacturer()).append(" "); - //// Type: - sb.append("MotorPlot.txt.Type" + " ").append(motor.getMotorType()).append('\n'); - //// Delays: - sb.append("MotorPlot.txt.Delays" +" ").append(Arrays.toString(motor.getStandardDelays())).append('\n'); - //// Comment:\n - sb.append("MotorPlot.txt.Comment" + " ").append(motor.getDescription()); - area.setText(sb.toString()); - panel.add(area, "grow, wrap"); - - - return panel; - } - - - - public int getSelected() { - return selected; - } - - - public static void main(String[] args) throws IOException { - if (args.length == 0) { - System.err.println("MotorPlot <files>"); - System.exit(1); - } - - final List<String> filenames = new ArrayList<String>(); - final List<ThrustCurveMotor> motors = new ArrayList<ThrustCurveMotor>(); - - GeneralMotorLoader loader = new GeneralMotorLoader(); - for (String file : args) { - for (Motor m : loader.load(new FileInputStream(file), file)) { - filenames.add(file); - motors.add((ThrustCurveMotor) m); - } - } - - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - GUIUtil.setBestLAF(); - - MotorPlot plot = new MotorPlot(filenames, motors); - plot.setVisible(true); - } - - }); - - } - - - - -} diff --git a/core/src/net/sf/openrocket/utils/MotorPrinter.java b/core/src/net/sf/openrocket/utils/MotorPrinter.java deleted file mode 100644 index 0f6b7b78..00000000 --- a/core/src/net/sf/openrocket/utils/MotorPrinter.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.List; - -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.file.motor.MotorLoader; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.MotorDigest; -import net.sf.openrocket.motor.ThrustCurveMotor; - -public class MotorPrinter { - - public static void main(String[] args) throws IOException { - - MotorLoader loader = new GeneralMotorLoader(); - - System.out.println(); - for (String arg : args) { - InputStream stream = new FileInputStream(arg); - - List<Motor> motors = loader.load(stream, arg); - - System.out.println("*** " + arg + " ***"); - System.out.println(); - for (Motor motor : motors) { - ThrustCurveMotor m = (ThrustCurveMotor) motor; - System.out.println(" Manufacturer: " + m.getManufacturer()); - System.out.println(" Designation: " + m.getDesignation()); - System.out.println(" Delays: " + - Arrays.toString(m.getStandardDelays())); - System.out.printf(" Nominal time: %.2f s\n", m.getBurnTimeEstimate()); - // System.out.printf(" Total time: %.2f s\n", m.getTotalTime()); - System.out.printf(" Avg. thrust: %.2f N\n", m.getAverageThrustEstimate()); - System.out.printf(" Max. thrust: %.2f N\n", m.getMaxThrustEstimate()); - System.out.printf(" Total impulse: %.2f Ns\n", m.getTotalImpulseEstimate()); - System.out.println(" Diameter: " + m.getDiameter() * 1000 + " mm"); - System.out.println(" Length: " + m.getLength() * 1000 + " mm"); - System.out.println(" Digest: " + m.getDigest()); - - if (m instanceof ThrustCurveMotor) { - ThrustCurveMotor tc = (ThrustCurveMotor) m; - System.out.println(" Data points: " + tc.getTimePoints().length); - for (int i = 0; i < m.getTimePoints().length; i++) { - double time = m.getTimePoints()[i]; - double thrust = m.getThrustPoints()[i]; - System.out.printf(" t=%.3f F=%.3f\n", time, thrust); - } - } - - System.out.println(" Comment:"); - System.out.println(m.getDescription()); - System.out.println(); - } - } - } -} diff --git a/core/src/net/sf/openrocket/utils/RocksimConverter.java b/core/src/net/sf/openrocket/utils/RocksimConverter.java deleted file mode 100644 index 49b91de6..00000000 --- a/core/src/net/sf/openrocket/utils/RocksimConverter.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.sf.openrocket.utils; - -import java.io.File; -import java.io.IOException; -import java.util.Locale; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.StorageOptions; -import net.sf.openrocket.file.DatabaseMotorFinder; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.file.RocketLoader; -import net.sf.openrocket.file.RocketSaver; -import net.sf.openrocket.file.openrocket.OpenRocketSaver; -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.logging.LogLevel; -import net.sf.openrocket.startup.Application; - -/** - * Utility that loads Rocksim file formats and saves them in ORK format. - * File is saved with the .rkt extension replaced with .ork. - * - * Usage: - * java -cp OpenRocket.jar net.sf.openrocket.utils.RocksimConverter <files...> - * - * @author Sampo Niskanen <sampo.niskanen@iki.fi> - */ -public class RocksimConverter { - - - public static void main(String[] args) { - - setup(); - - RocketLoader loader = new net.sf.openrocket.file.rocksim.importt.RocksimLoader(); - RocketSaver saver = new OpenRocketSaver(); - - for (String inputFile : args) { - System.out.println("Converting " + inputFile + "..."); - - if (!inputFile.matches(".*\\.[rR][kK][tT]$")) { - System.err.println("ERROR: File '" + inputFile + "' does not end in .rkt, skipping."); - continue; - } - - String outputFile = inputFile.replaceAll("\\.[rR][kK][tT]$", ".ork"); - - File input = new File(inputFile); - File output = new File(outputFile); - - if (!input.isFile()) { - System.err.println("ERROR: File '" + inputFile + "' does not exist, skipping."); - continue; - } - if (output.exists()) { - System.err.println("ERROR: File '" + outputFile + "' already exists, skipping."); - continue; - } - - try { - StorageOptions opts = new StorageOptions(); - opts.setCompressionEnabled(true); - opts.setSimulationTimeSkip(StorageOptions.SIMULATION_DATA_NONE); - opts.setExplicitlySet(true); - - OpenRocketDocument document = loader.load(input, new DatabaseMotorFinder()); - saver.save(output, document, opts); - - } catch (RocketLoadException e) { - System.err.println("ERROR: Error loading '" + inputFile + "': " + e.getMessage()); - } catch (IOException e) { - System.err.println("ERROR: Error saving '" + outputFile + "': " + e.getMessage()); - } - - } - - } - - private static void setup() { - Locale.setDefault(Locale.US); - Application.setBaseTranslator(new ResourceBundleTranslator("l10n.messages")); - - Application.setLogOutputLevel(LogLevel.WARN); - Application.setPreferences(new SwingPreferences()); - } -} diff --git a/core/src/net/sf/openrocket/utils/TestFunctionOptimizer.java b/core/src/net/sf/openrocket/utils/TestFunctionOptimizer.java deleted file mode 100644 index e5f9da71..00000000 --- a/core/src/net/sf/openrocket/utils/TestFunctionOptimizer.java +++ /dev/null @@ -1,119 +0,0 @@ -package net.sf.openrocket.utils; - -import net.sf.openrocket.optimization.general.Function; -import net.sf.openrocket.optimization.general.FunctionOptimizer; -import net.sf.openrocket.optimization.general.OptimizationController; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.ParallelExecutorCache; -import net.sf.openrocket.optimization.general.ParallelFunctionCache; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.optimization.general.multidim.MultidirectionalSearchOptimizer; - - - - -public class TestFunctionOptimizer { - - private static final int LOOP_COUNT = 1000000; - - private volatile int evaluations = 0; - private volatile int aborted = 0; - private volatile int stepCount = 0; - - - - private void go(final ParallelFunctionCache functionCache, - final FunctionOptimizer optimizer, final Point optimum, final int maxSteps) throws OptimizationException { - - Function function = new Function() { - @Override - public double evaluate(Point p) throws InterruptedException { - if (loop(LOOP_COUNT)) { - evaluations++; - return p.sub(optimum).length2(); - } else { - aborted++; - return Double.NaN; - } - } - }; - - OptimizationController control = new OptimizationController() { - - @Override - public boolean stepTaken(Point oldPoint, double oldValue, Point newPoint, double newValue, double stepSize) { - stepCount++; - // System.out.println("CSV " + count + ", " + evaluations + ", " + newPoint.sub(optimum).length()); - // System.out.println("Steps: " + count + " Function evaluations: " + evaluations); - // System.out.println("Distance: " + newPoint.sub(optimum).length() + " " + newPoint + " value=" + newValue); - return stepCount < maxSteps; - } - }; - ; - - functionCache.setFunction(function); - optimizer.setFunctionCache(functionCache); - optimizer.optimize(new Point(optimum.dim(), 0.5), control); - System.err.println("Result: " + optimizer.getOptimumPoint() + " value=" + optimizer.getOptimumValue()); - System.err.println("Steps: " + stepCount + " Evaluations: " + evaluations); - } - - - public static double counter; - - private static boolean loop(int count) { - counter = 1.0; - for (int i = 0; i < count; i++) { - counter += Math.sin(counter); - if (i % 1024 == 0) { - if (Thread.interrupted()) { - return false; - } - } - } - return true; - } - - - public static void main(String[] args) throws InterruptedException, OptimizationException { - - System.err.println("Number of processors: " + Runtime.getRuntime().availableProcessors()); - - for (int i = 0; i < 20; i++) { - long t0 = System.currentTimeMillis(); - loop(LOOP_COUNT); - long t1 = System.currentTimeMillis(); - System.err.println("Loop delay at startup: " + (t1 - t0) + "ms"); - } - System.err.println(); - - for (int threadCount = 1; threadCount <= 10; threadCount++) { - - System.err.println("THREAD COUNT: " + threadCount); - TestFunctionOptimizer test = new TestFunctionOptimizer(); - - ParallelExecutorCache executor = new ParallelExecutorCache(threadCount); - MultidirectionalSearchOptimizer optimizer = new MultidirectionalSearchOptimizer(); - long t0 = System.currentTimeMillis(); - test.go(executor, optimizer, new Point(0.2, 0.3, 0.85), 30); - long t1 = System.currentTimeMillis(); - - System.err.println("Optimization took " + (t1 - t0) + "ms"); - System.err.println("" + test.stepCount + " steps, " + test.evaluations + - " function evaluations, " + test.aborted + " aborted evaluations"); - System.err.println("Statistics: " + optimizer.getStatistics()); - - executor.getExecutor().shutdownNow(); - Thread.sleep(1000); - - t0 = System.currentTimeMillis(); - loop(LOOP_COUNT); - t1 = System.currentTimeMillis(); - System.err.println("Loop delay afterwards: " + (t1 - t0) + "ms"); - System.err.println(); - } - } - - - -} diff --git a/core/src/net/sf/openrocket/utils/TestFunctionOptimizerLoop.java b/core/src/net/sf/openrocket/utils/TestFunctionOptimizerLoop.java deleted file mode 100644 index e09a0ee8..00000000 --- a/core/src/net/sf/openrocket/utils/TestFunctionOptimizerLoop.java +++ /dev/null @@ -1,101 +0,0 @@ -package net.sf.openrocket.utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import net.sf.openrocket.optimization.general.Function; -import net.sf.openrocket.optimization.general.FunctionOptimizer; -import net.sf.openrocket.optimization.general.OptimizationController; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.ParallelExecutorCache; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.optimization.general.multidim.MultidirectionalSearchOptimizer; -import net.sf.openrocket.util.MathUtil; - - -public class TestFunctionOptimizerLoop { - - private static final double PRECISION = 0.01; - - private Point optimum; - private int stepCount = 0; - private int evaluations = 0; - - - - private void go(final FunctionOptimizer optimizer, final Point optimum, final int maxSteps, ExecutorService executor) throws OptimizationException { - - Function function = new Function() { - @Override - public double evaluate(Point p) throws InterruptedException { - evaluations++; - return p.sub(optimum).length2(); - } - }; - - OptimizationController control = new OptimizationController() { - - @Override - public boolean stepTaken(Point oldPoint, double oldValue, Point newPoint, double newValue, double stepSize) { - stepCount++; - if (stepCount % 1000 == 0) { - System.err.println("WARNING: Over " + stepCount + " steps required for optimum=" + optimum + - " position=" + newPoint); - } - double distance = newPoint.sub(optimum).length(); - return distance >= PRECISION; - } - }; - ; - - ParallelExecutorCache cache = new ParallelExecutorCache(executor); - cache.setFunction(function); - optimizer.setFunctionCache(cache); - optimizer.optimize(new Point(optimum.dim(), 0.5), control); - } - - - public static void main(String[] args) throws OptimizationException { - - System.err.println("PRECISION = " + PRECISION); - - ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)); - - for (int dim = 1; dim <= 10; dim++) { - - List<Integer> stepCount = new ArrayList<Integer>(); - List<Integer> functionCount = new ArrayList<Integer>(); - - MultidirectionalSearchOptimizer optimizer = new MultidirectionalSearchOptimizer(); - for (int count = 0; count < 200; count++) { - TestFunctionOptimizerLoop test = new TestFunctionOptimizerLoop(); - double[] point = new double[dim]; - for (int i = 0; i < dim; i++) { - point[i] = Math.random(); - } - // point[0] = 0.7; - test.go(optimizer, new Point(point), 20, executor); - stepCount.add(test.stepCount); - functionCount.add(test.evaluations); - } - - // System.err.println("StepCount = " + stepCount); - - System.out.printf("dim=%d Steps avg=%5.2f dev=%5.2f median=%.1f " + - "Evaluations avg=%5.2f dev=%5.2f median=%.1f\n", - dim, MathUtil.average(stepCount), MathUtil.stddev(stepCount), MathUtil.median(stepCount), - MathUtil.average(functionCount), MathUtil.stddev(functionCount), MathUtil.median(functionCount)); - System.out.println("stat: " + optimizer.getStatistics()); - - } - - executor.shutdownNow(); - } - - - -} diff --git a/core/test/net/sf/openrocket/Estes_A8.rse b/core/test/net/sf/openrocket/Estes_A8.rse deleted file mode 100644 index 1098ffe1..00000000 --- a/core/test/net/sf/openrocket/Estes_A8.rse +++ /dev/null @@ -1,40 +0,0 @@ -<engine-database> - <engine-list> -<engine FDiv="10" FFix="1" FStep="-1." Isp="71.7" Itot="2.32" Type="single-use" auto-calc-cg="1" auto-calc-mass="1" avgThrust="3.178" burn-time="0.73" cgDiv="10" cgFix="1" cgStep="-1." code="A8" delays="3,5" dia="18." exitDia="0." initWt="16.35" len="70." mDiv="10" mFix="1" mStep="-1." massFrac="20.18" mfg="Estes" peakThrust="9.73" propWt="3.3" tDiv="10" tFix="1" tStep="-1." throatDia="0."> -<comments>Estes A8 RASP.ENG file made from NAR published data -File produced October 3, 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. -</comments> -<data> -<eng-data cg="35." f="0." m="3.3" t="0."/> -<eng-data cg="35." f="0.512" m="3.28507" t="0.041"/> -<eng-data cg="35." f="2.115" m="3.20474" t="0.084"/> -<eng-data cg="35." f="4.358" m="3.0068" t="0.127"/> -<eng-data cg="35." f="6.794" m="2.6975" t="0.166"/> -<eng-data cg="35." f="8.588" m="2.41309" t="0.192"/> -<eng-data cg="35." f="9.294" m="2.23506" t="0.206"/> -<eng-data cg="35." f="9.73" m="1.96448" t="0.226"/> -<eng-data cg="35." f="8.845" m="1.83238" t="0.236"/> -<eng-data cg="35." f="7.179" m="1.70703" t="0.247"/> -<eng-data cg="35." f="5.063" m="1.58515" t="0.261"/> -<eng-data cg="35." f="3.717" m="1.48525" t="0.277"/> -<eng-data cg="35." f="3.205" m="1.3425" t="0.306"/> -<eng-data cg="35." f="2.884" m="1.14764" t="0.351"/> -<eng-data cg="35." f="2.499" m="0.94092" t="0.405"/> -<eng-data cg="35." f="2.371" m="0.726196" t="0.467"/> -<eng-data cg="35." f="2.307" m="0.509957" t="0.532"/> -<eng-data cg="35." f="2.371" m="0.320333" t="0.589"/> -<eng-data cg="35." f="2.371" m="0.175326" t="0.632"/> -<eng-data cg="35." f="2.243" m="0.109701" t="0.652"/> -<eng-data cg="35." f="1.794" m="0.0637665" t="0.668"/> -<eng-data cg="35." f="1.153" m="0.0302344" t="0.684"/> -<eng-data cg="35." f="0.448" m="0.00860204" t="0.703"/> -<eng-data cg="35." f="0." m="0." t="0.73"/> -</data> -</engine> - </engine-list> -</engine-database> diff --git a/core/test/net/sf/openrocket/IntegrationTest.java b/core/test/net/sf/openrocket/IntegrationTest.java deleted file mode 100644 index b06a6c34..00000000 --- a/core/test/net/sf/openrocket/IntegrationTest.java +++ /dev/null @@ -1,322 +0,0 @@ -package net.sf.openrocket; - -import static org.junit.Assert.*; - -import java.awt.event.ActionEvent; -import java.io.IOException; -import java.io.InputStream; - -import javax.swing.Action; - -import net.sf.openrocket.aerodynamics.AerodynamicCalculator; -import net.sf.openrocket.aerodynamics.BarrowmanCalculator; -import net.sf.openrocket.aerodynamics.FlightConditions; -import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.file.DatabaseMotorFinder; -import net.sf.openrocket.file.GeneralRocketLoader; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.file.motor.GeneralMotorLoader; -import net.sf.openrocket.gui.main.UndoRedoAction; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.masscalc.BasicMassCalculator; -import net.sf.openrocket.masscalc.MassCalculator; -import net.sf.openrocket.masscalc.MassCalculator.MassCalcType; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.rocketcomponent.Configuration; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.exception.SimulationException; -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * This class contains various integration tests that simulate user actions that - * might be performed. - */ -public class IntegrationTest extends BaseTestCase { - - private OpenRocketDocument document; - private Action undoAction, redoAction; - - private AerodynamicCalculator aeroCalc = new BarrowmanCalculator(); - private MassCalculator massCalc = new BasicMassCalculator(); - private Configuration config; - private FlightConditions conditions; - - - @BeforeClass - public static void initialize() { - ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(false) { - @Override - protected void loadMotors() { - GeneralMotorLoader loader = new GeneralMotorLoader(); - InputStream is = this.getClass().getResourceAsStream("Estes_A8.rse"); - assertNotNull("Problem in unit test, cannot find Estes_A8.rse", is); - try { - for (Motor m : loader.load(is, "Estes_A8.rse")) { - addMotor((ThrustCurveMotor) m); - } - is.close(); - } catch (IOException e) { - e.printStackTrace(); - fail("IOException: " + e); - } - } - }; - db.startLoading(); - assertEquals(1, db.getMotorSets().size()); - Application.setMotorSetDatabase(db); - Application.setBaseTranslator(new ResourceBundleTranslator("l10n.messages")); - } - - /** - * Tests loading a rocket design, modifying it, simulating it and the undo/redo - * mechanism in various combinations. - */ - @Test - public void test1() throws RocketLoadException, IOException, SimulationException { - System.setProperty("openrocket.unittest", "true"); - - // Load the rocket - GeneralRocketLoader loader = new GeneralRocketLoader(); - InputStream is = this.getClass().getResourceAsStream("simplerocket.ork"); - assertNotNull("Problem in unit test, cannot find simplerocket.ork", is); - document = loader.load(is, new DatabaseMotorFinder()); - is.close(); - - undoAction = UndoRedoAction.newUndoAction(document); - redoAction = UndoRedoAction.newRedoAction(document); - config = document.getSimulation(0).getConfiguration(); - conditions = new FlightConditions(config); - - - // Test undo state - checkUndoState(null, null); - - - // Compute cg+cp + altitude - checkCgCp(0.248, 0.0645, 0.320, 12.0); - checkAlt(48.2); - - - // Mass modification - document.addUndoPosition("Modify mass"); - checkUndoState(null, null); - massComponent().setComponentMass(0.01); - checkUndoState("Modify mass", null); - - - // Check cg+cp + altitude - checkCgCp(0.230, 0.0745, 0.320, 12.0); - checkAlt(37.2); - - - // Non-change - document.addUndoPosition("No change"); - checkUndoState("Modify mass", null); - - - // Non-funcitonal change - document.addUndoPosition("Name change"); - checkUndoState("Modify mass", null); - massComponent().setName("Foobar component"); - checkUndoState("Name change", null); - - - // Check cg+cp - checkCgCp(0.230, 0.0745, 0.320, 12.0); - - - // Aerodynamic modification - document.addUndoPosition("Remove component"); - checkUndoState("Name change", null); - document.getRocket().getChild(0).removeChild(0); - checkUndoState("Remove component", null); - - - // Check cg+cp + altitude - checkCgCp(0.163, 0.0613, 0.275, 9.95); - checkAlt(45.0); - - - // Undo "Remove component" change - undoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertTrue(document.getRocket().getChild(0).getChild(0) instanceof NoseCone); - checkUndoState("Name change", "Remove component"); - - - // Check cg+cp + altitude - checkCgCp(0.230, 0.0745, 0.320, 12.0); - checkAlt(37.2); - - - // Undo "Name change" change - undoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertEquals("Extra mass", massComponent().getName()); - checkUndoState("Modify mass", "Name change"); - - - // Check cg+cp - checkCgCp(0.230, 0.0745, 0.320, 12.0); - - - // Undo "Modify mass" change - undoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertEquals(0, massComponent().getComponentMass(), 0); - checkUndoState(null, "Modify mass"); - - - // Check cg+cp + altitude - checkCgCp(0.248, 0.0645, 0.320, 12.0); - checkAlt(48.2); - - - // Redo "Modify mass" change - redoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertEquals(0.010, massComponent().getComponentMass(), 0.00001); - checkUndoState("Modify mass", "Name change"); - - - // Check cg+cp + altitude - checkCgCp(0.230, 0.0745, 0.320, 12.0); - checkAlt(37.2); - - - // Mass modification - document.addUndoPosition("Modify mass2"); - checkUndoState("Modify mass", "Name change"); - massComponent().setComponentMass(0.015); - checkUndoState("Modify mass2", null); - - - // Check cg+cp + altitude - checkCgCp(0.223, 0.0795, 0.320, 12.0); - checkAlt(32.7); - - - // Perform component movement - document.startUndo("Move component"); - document.getRocket().freeze(); - RocketComponent bodytube = document.getRocket().getChild(0).getChild(1); - RocketComponent innertube = bodytube.getChild(2); - RocketComponent engineblock = innertube.getChild(0); - assertTrue(innertube.removeChild(engineblock)); - bodytube.addChild(engineblock, 0); - checkUndoState("Modify mass2", null); - document.getRocket().thaw(); - checkUndoState("Move component", null); - document.stopUndo(); - - - // Check cg+cp + altitude - checkCgCp(0.221, 0.0797, 0.320, 12.0); - checkAlt(32.7); - - - // Modify mass without setting undo description - massComponent().setComponentMass(0.020); - checkUndoState("Modify mass2", null); - - - // Check cg+cp + altitude - checkCgCp(0.215, 0.0847, 0.320, 12.0); - checkAlt(29.0); - - - // Undo "Modify mass2" change - undoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertEquals(0.015, massComponent().getComponentMass(), 0.0000001); - checkUndoState("Move component", "Modify mass2"); - - - // Check cg+cp + altitude - checkCgCp(0.221, 0.0797, 0.320, 12.0); - checkAlt(32.7); - - - // Undo "Move component" change - undoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertTrue(document.getRocket().getChild(0).getChild(1).getChild(2).getChild(0) instanceof EngineBlock); - checkUndoState("Modify mass2", "Move component"); - - - // Check cg+cp + altitude - checkCgCp(0.223, 0.0795, 0.320, 12.0); - checkAlt(32.7); - - - // Redo "Move component" change - redoAction.actionPerformed(new ActionEvent(this, 0, "foo")); - assertTrue(document.getRocket().getChild(0).getChild(1).getChild(0) instanceof EngineBlock); - checkUndoState("Move component", "Modify mass2"); - - - // Check cg+cp + altitude - checkCgCp(0.221, 0.0797, 0.320, 12.0); - checkAlt(32.7); - - - } - - private String massComponentID = null; - - private MassComponent massComponent() { - if (massComponentID == null) { - massComponentID = document.getRocket().getChild(0).getChild(1).getChild(0).getID(); - } - return (MassComponent) document.getRocket().findComponent(massComponentID); - } - - - private void checkUndoState(String undoDesc, String redoDesc) { - if (undoDesc == null) { - assertEquals("Undo", undoAction.getValue(Action.NAME)); - assertFalse(undoAction.isEnabled()); - } else { - assertEquals("Undo (" + undoDesc + ")", undoAction.getValue(Action.NAME)); - assertTrue(undoAction.isEnabled()); - } - if (redoDesc == null) { - assertEquals("Redo", redoAction.getValue(Action.NAME)); - assertFalse(redoAction.isEnabled()); - } else { - assertEquals("Redo (" + redoDesc + ")", redoAction.getValue(Action.NAME)); - assertTrue(redoAction.isEnabled()); - } - } - - - private void checkCgCp(double cgx, double mass, double cpx, double cna) { - Coordinate cg, cp; - - cg = massCalc.getCG(config, MassCalcType.LAUNCH_MASS); - assertEquals(cgx, cg.x, 0.001); - assertEquals(mass, cg.weight, 0.0005); - - cp = aeroCalc.getWorstCP(config, conditions, null); - assertEquals(cpx, cp.x, 0.001); - assertEquals(cna, cp.weight, 0.1); - } - - - private void checkAlt(double expected) throws SimulationException { - Simulation simulation = document.getSimulation(0); - double actual; - - // Simulate + check altitude - simulation.simulate(); - actual = simulation.getSimulatedData().getBranch(0).getMaximum(FlightDataType.TYPE_ALTITUDE); - assertEquals(expected, actual, 0.5); - } - -} diff --git a/core/test/net/sf/openrocket/arch/TestSystemInfo.java b/core/test/net/sf/openrocket/arch/TestSystemInfo.java deleted file mode 100644 index 80c65584..00000000 --- a/core/test/net/sf/openrocket/arch/TestSystemInfo.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.sf.openrocket.arch; - -import static org.junit.Assert.assertEquals; - -import java.io.File; - -import org.junit.Test; - -/* - * Note: These tests have not been tested on Windows, they might fail there - * due to a different directory separator character. - */ -public class TestSystemInfo { - - private String osname; - private String userhome; - - - public void setup() { - this.osname = System.getProperty("os.name"); - this.userhome = System.getProperty("user.home"); - } - - public void tearDown() { - System.setProperty("os.name", this.osname); - System.setProperty("user.home", this.userhome); - } - - @Test - public void testWindows() { - setup(); - - System.setProperty("os.name", "Windows Me"); - System.setProperty("user.home", "C:/Users/my user"); - assertEquals(SystemInfo.Platform.WINDOWS, SystemInfo.getPlatform()); - if (System.getenv("APPDATA") != null) { - assertEquals(new File(System.getenv("APPDATA") + "/OpenRocket/"), SystemInfo.getUserApplicationDirectory()); - } else { - assertEquals(new File("C:/Users/my user/OpenRocket/"), SystemInfo.getUserApplicationDirectory()); - } - - tearDown(); - } - - @Test - public void testMacOS() { - setup(); - - System.setProperty("os.name", "Mac OS X"); - System.setProperty("user.home", "/Users/My User"); - assertEquals(SystemInfo.Platform.MAC_OS, SystemInfo.getPlatform()); - assertEquals(new File("/Users/My User/Library/Application Support/OpenRocket/"), - SystemInfo.getUserApplicationDirectory()); - - tearDown(); - } - - @Test - public void testUnix() { - setup(); - - System.setProperty("user.home", "/home/myuser"); - for (String os : new String[] { "Linux", "Solaris", "Foobar" }) { - System.setProperty("os.name", os); - - assertEquals(SystemInfo.Platform.UNIX, SystemInfo.getPlatform()); - assertEquals(new File("/home/myuser/.openrocket"), SystemInfo.getUserApplicationDirectory()); - } - - tearDown(); - } - -} diff --git a/core/test/net/sf/openrocket/communication/BugReportTest.java b/core/test/net/sf/openrocket/communication/BugReportTest.java deleted file mode 100644 index e178ec7f..00000000 --- a/core/test/net/sf/openrocket/communication/BugReportTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.sf.openrocket.communication; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import net.sf.openrocket.util.BuildProperties; - -import org.junit.Test; - - -public class BugReportTest { - - private HttpURLConnectionMock setup() { - HttpURLConnectionMock connection = new HttpURLConnectionMock(); - Communicator.setConnectionSource(new ConnectionSourceStub(connection)); - - connection.setUseCaches(true); - return connection; - } - - private void check(HttpURLConnectionMock connection) { - assertEquals(Communicator.BUG_REPORT_URL, connection.getTrueUrl()); - assertTrue(connection.getConnectTimeout() > 0); - assertEquals(BuildProperties.getVersion(), connection.getRequestProperty("X-OpenRocket-Version")); - assertTrue(connection.getInstanceFollowRedirects()); - assertEquals("POST", connection.getRequestMethod()); - assertFalse(connection.getUseCaches()); - } - - - @Test - public void testBugReportSuccess() throws IOException { - HttpURLConnectionMock connection = setup(); - connection.setResponseCode(Communicator.BUG_REPORT_RESPONSE_CODE); - - String message = - "MyMessage\n"+ - "is important\n"+ - "h\u00e4h?"; - - BugReporter.sendBugReport(message); - - check(connection); - - String msg = connection.getOutputStreamString(); - assertTrue(msg.indexOf("version=" + BuildProperties.getVersion()) >= 0); - assertTrue(msg.indexOf(Communicator.encode(message)) >= 0); - } - - - @Test - public void testBugReportFailure() throws IOException { - HttpURLConnectionMock connection = setup(); - connection.setResponseCode(200); - - String message = - "MyMessage\n"+ - "is important\n"+ - "h\u00e4h?"; - - try { - BugReporter.sendBugReport(message); - fail("Exception did not occur"); - } catch (IOException e) { - // Success - } - - check(connection); - } - -} diff --git a/core/test/net/sf/openrocket/communication/ConnectionSourceStub.java b/core/test/net/sf/openrocket/communication/ConnectionSourceStub.java deleted file mode 100644 index 4cd5470b..00000000 --- a/core/test/net/sf/openrocket/communication/ConnectionSourceStub.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.communication; - -import java.io.IOException; -import java.net.HttpURLConnection; - -public class ConnectionSourceStub implements ConnectionSource { - - private final HttpURLConnection connection; - - public ConnectionSourceStub(HttpURLConnection connection) { - this.connection = connection; - } - - @Override - public HttpURLConnection getConnection(String url) throws IOException { - if (connection instanceof HttpURLConnectionMock) { - ((HttpURLConnectionMock)connection).setTrueUrl(url); - } - return connection; - } - -} diff --git a/core/test/net/sf/openrocket/communication/HttpURLConnectionMock.java b/core/test/net/sf/openrocket/communication/HttpURLConnectionMock.java deleted file mode 100644 index 57f5d520..00000000 --- a/core/test/net/sf/openrocket/communication/HttpURLConnectionMock.java +++ /dev/null @@ -1,535 +0,0 @@ -package net.sf.openrocket.communication; - - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URL; -import java.security.Permission; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import net.sf.openrocket.util.BugException; - -public class HttpURLConnectionMock extends HttpURLConnection { - - private static final URL MOCK_URL; - static { - try { - MOCK_URL = new URL("http://localhost/"); - } catch (MalformedURLException e) { - throw new BugException(e); - } - } - - private volatile boolean instanceFollowRedirects = false; - private volatile String requestMethod = ""; - private volatile int responseCode; - private Map<String, String> requestProperties = new HashMap<String, String>(); - private volatile int connectTimeout = -1; - private volatile String contentEncoding = ""; - - private volatile boolean doInput = false; - private volatile boolean doOutput = false; - - private volatile byte[] content = null; - private volatile String contentType = null; - private volatile boolean useCaches = false; - - - private volatile InputStream inputStream = null; - private volatile ByteArrayOutputStream outputStream = null; - - private volatile String trueUrl = null; - - - private volatile boolean connected = false; - private volatile int connectionDelay = 0; - - private volatile boolean failed = false; - - - - - public HttpURLConnectionMock() { - super(MOCK_URL); - } - - public HttpURLConnectionMock(URL u) { - super(u); - } - - - - public String getTrueUrl() { - return trueUrl; - } - - public void setTrueUrl(String url) { - assertNull(this.trueUrl); - this.trueUrl = url; - } - - - public boolean hasFailed() { - return failed; - } - - - public void setConnectionDelay(int delay) { - this.connectionDelay = delay; - } - - - - @Override - public void connect() { - if (!connected) { - try { - Thread.sleep(connectionDelay); - } catch (InterruptedException e) { - } - connected = true; - } - } - - @Override - public void disconnect() { - - } - - @Override - public boolean usingProxy() { - return false; - } - - - - - @Override - public boolean getInstanceFollowRedirects() { - return this.instanceFollowRedirects; - } - - @Override - public void setInstanceFollowRedirects(boolean followRedirects) { - assertFalse(connected); - this.instanceFollowRedirects = followRedirects; - } - - @Override - public String getRequestMethod() { - return this.requestMethod; - } - - @Override - public void setRequestMethod(String method) throws ProtocolException { - assertFalse(connected); - this.requestMethod = method; - } - - @Override - public int getResponseCode() throws IOException { - connect(); - return this.responseCode; - } - - public void setResponseCode(int code) { - this.responseCode = code; - } - - - @Override - public void addRequestProperty(String key, String value) { - assertFalse(connected); - assertFalse(this.requestProperties.containsKey(key.toLowerCase(Locale.ENGLISH))); - this.requestProperties.put(key.toLowerCase(Locale.ENGLISH), value); - } - - - @Override - public void setRequestProperty(String key, String value) { - assertFalse(connected); - this.requestProperties.put(key.toLowerCase(Locale.ENGLISH), value); - } - - - @Override - public String getRequestProperty(String key) { - return this.requestProperties.get(key.toLowerCase(Locale.ENGLISH)); - } - - - @Override - public int getConnectTimeout() { - return this.connectTimeout; - } - - @Override - public void setConnectTimeout(int timeout) { - assertFalse(connected); - this.connectTimeout = timeout; - } - - - - @Override - public String getContentEncoding() { - connect(); - return this.contentEncoding; - } - - public void setContentEncoding(String encoding) { - this.contentEncoding = encoding; - } - - - - @Override - public int getContentLength() { - connect(); - if (content == null) - return 0; - return content.length; - } - - public void setContent(byte[] content) { - this.content = content; - } - - public void setContent(String content) { - try { - this.content = content.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - fail("UTF-8"); - } - } - - - @Override - public String getContentType() { - connect(); - return this.contentType; - } - - public void setContentType(String type) { - this.contentType = type; - } - - - - @Override - public boolean getDoInput() { - return this.doInput; - } - - - @Override - public void setDoInput(boolean doinput) { - assertFalse(connected); - this.doInput = doinput; - } - - - @Override - public boolean getDoOutput() { - return this.doOutput; - } - - - @Override - public void setDoOutput(boolean dooutput) { - assertFalse(connected); - this.doOutput = dooutput; - } - - - @Override - public InputStream getInputStream() throws IOException { - assertTrue(doInput); - assertNull(inputStream); - assertNotNull(content); - - connect(); - inputStream = new ByteArrayInputStream(content); - return inputStream; - } - - - @Override - public OutputStream getOutputStream() throws IOException { - assertTrue(doOutput); - assertNull(outputStream); - outputStream = new ByteArrayOutputStream(); - return outputStream; - } - - public byte[] getOutputStreamData() { - return outputStream.toByteArray(); - } - - public String getOutputStreamString() { - try { - return outputStream.toString("UTF-8"); - } catch (UnsupportedEncodingException e) { - fail("UTF-8"); - return null; - } - } - - - - @Override - public void setUseCaches(boolean usecaches) { - assertFalse(connected); - this.useCaches = usecaches; - } - - - - @Override - public boolean getUseCaches() { - return this.useCaches; - } - - - - - - private void assertNull(Object o) { - try { - org.junit.Assert.assertNull(o); - } catch (AssertionError e) { - failed = true; - throw e; - } - } - - private void assertNotNull(Object o) { - try { - org.junit.Assert.assertNotNull(o); - } catch (AssertionError e) { - failed = true; - throw e; - } - } - - private void assertTrue(boolean o) { - try { - org.junit.Assert.assertTrue(o); - } catch (AssertionError e) { - failed = true; - throw e; - } - } - - private void assertFalse(boolean o) { - try { - org.junit.Assert.assertFalse(o); - } catch (AssertionError e) { - failed = true; - throw e; - } - } - - private void fail(String msg) { - failed = true; - org.junit.Assert.fail(msg); - } - - - - - - @Override - public InputStream getErrorStream() { - throw new UnsupportedOperationException(); - } - - - - @Override - public String getHeaderField(int n) { - throw new UnsupportedOperationException(); - } - - - - @Override - public long getHeaderFieldDate(String name, long Default) { - throw new UnsupportedOperationException(); - } - - - - @Override - public String getHeaderFieldKey(int n) { - throw new UnsupportedOperationException(); - } - - - @Override - public Permission getPermission() throws IOException { - throw new UnsupportedOperationException(); - } - - - @Override - public String getResponseMessage() throws IOException { - throw new UnsupportedOperationException(); - } - - - - @Override - public void setChunkedStreamingMode(int chunklen) { - throw new UnsupportedOperationException(); - } - - - - @Override - public void setFixedLengthStreamingMode(int contentLength) { - throw new UnsupportedOperationException(); - } - - - - - - @Override - public boolean getAllowUserInteraction() { - throw new UnsupportedOperationException(); - } - - - - @Override - public Object getContent() throws IOException { - throw new UnsupportedOperationException(); - } - - - - @SuppressWarnings("unchecked") - @Override - public Object getContent(Class[] classes) throws IOException { - throw new UnsupportedOperationException(); - } - - - @Override - public long getDate() { - throw new UnsupportedOperationException(); - } - - - - @Override - public boolean getDefaultUseCaches() { - throw new UnsupportedOperationException(); - } - - - @Override - public long getExpiration() { - throw new UnsupportedOperationException(); - } - - - - @Override - public String getHeaderField(String name) { - throw new UnsupportedOperationException(); - } - - - - @Override - public int getHeaderFieldInt(String name, int Default) { - throw new UnsupportedOperationException(); - } - - - - @Override - public Map<String, List<String>> getHeaderFields() { - throw new UnsupportedOperationException(); - } - - - - @Override - public long getIfModifiedSince() { - throw new UnsupportedOperationException(); - } - - - @Override - public long getLastModified() { - throw new UnsupportedOperationException(); - } - - @Override - public int getReadTimeout() { - throw new UnsupportedOperationException(); - } - - - - @Override - public Map<String, List<String>> getRequestProperties() { - throw new UnsupportedOperationException(); - } - - - @Override - public URL getURL() { - throw new UnsupportedOperationException(); - } - - - - @Override - public void setAllowUserInteraction(boolean allowuserinteraction) { - throw new UnsupportedOperationException(); - } - - @Override - public void setDefaultUseCaches(boolean defaultusecaches) { - throw new UnsupportedOperationException(); - } - - - @Override - public void setIfModifiedSince(long ifmodifiedsince) { - throw new UnsupportedOperationException(); - } - - - @Override - public void setReadTimeout(int timeout) { - throw new UnsupportedOperationException(); - } - - - - - - @Override - public String toString() { - throw new UnsupportedOperationException(); - } - - - - -} diff --git a/core/test/net/sf/openrocket/communication/UpdateInfoTest.java b/core/test/net/sf/openrocket/communication/UpdateInfoTest.java deleted file mode 100644 index d09db759..00000000 --- a/core/test/net/sf/openrocket/communication/UpdateInfoTest.java +++ /dev/null @@ -1,236 +0,0 @@ -package net.sf.openrocket.communication; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -import net.sf.openrocket.util.BuildProperties; -import net.sf.openrocket.util.ComparablePair; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -public class UpdateInfoTest extends BaseTestCase { - - /** The connection delay */ - private static final int DELAY = 100; - - /** How much long does the test allow it to take */ - private static final int ALLOWANCE = 2000; - - - private HttpURLConnectionMock setup() { - HttpURLConnectionMock connection = new HttpURLConnectionMock(); - Communicator.setConnectionSource(new ConnectionSourceStub(connection)); - - connection.setConnectionDelay(DELAY); - connection.setUseCaches(true); - connection.setContentType("text/plain"); - return connection; - } - - private void check(HttpURLConnectionMock connection) { - assertEquals(Communicator.UPDATE_INFO_URL + "?version=" + BuildProperties.getVersion(), - connection.getTrueUrl()); - assertTrue(connection.getConnectTimeout() > 0); - assertEquals(BuildProperties.getVersion() + "+" + BuildProperties.getBuildSource(), - connection.getRequestProperty("X-OpenRocket-Version")); - assertNotNull(connection.getRequestProperty("X-OpenRocket-Country")); - assertNotNull(connection.getRequestProperty("X-OpenRocket-ID")); - assertNotNull(connection.getRequestProperty("X-OpenRocket-OS")); - assertNotNull(connection.getRequestProperty("X-OpenRocket-Java")); - assertTrue(connection.getInstanceFollowRedirects()); - assertEquals("GET", connection.getRequestMethod()); - assertFalse(connection.getUseCaches()); - } - - - @Test - public void testUpdateAvailable() throws IOException { - HttpURLConnectionMock connection = setup(); - connection.setResponseCode(Communicator.UPDATE_INFO_UPDATE_AVAILABLE); - - String content = - "Version: 6.6.6pre A \n" + - "Extra: information\n" + - "100:hundred\n" + - "50: m\u00e4 \n\n" + - "1: one\n" + - "-2: none"; - connection.setContent(content); - - UpdateInfoRetriever retriever = new UpdateInfoRetriever(); - retriever.start(); - - // Info is null while processing - assertNull(retriever.getUpdateInfo()); - - waitfor(retriever); - assertFalse(connection.hasFailed()); - - UpdateInfo info = retriever.getUpdateInfo(); - assertNotNull(info); - - check(connection); - - assertEquals("6.6.6pre A", info.getLatestVersion()); - - List<ComparablePair<Integer, String>> updates = info.getUpdates(); - assertEquals(3, updates.size()); - Collections.sort(updates); - assertEquals(1, (int)updates.get(0).getU()); - assertEquals("one", updates.get(0).getV()); - assertEquals(50, (int)updates.get(1).getU()); - assertEquals("m\u00e4", updates.get(1).getV()); - assertEquals(100, (int)updates.get(2).getU()); - assertEquals("hundred", updates.get(2).getV()); - } - - - - - @Test - public void testUpdateNotAvailable() throws IOException { - HttpURLConnectionMock connection = setup(); - connection.setResponseCode(Communicator.UPDATE_INFO_NO_UPDATE_CODE); - - String content = - "Version: 6.6.6pre A \n" + - "Extra: information\n" + - "100:hundred\n" + - "50: m\u00e4 \n\n" + - "1: one\n" + - "-2: none"; - connection.setContent(content); - - UpdateInfoRetriever retriever = new UpdateInfoRetriever(); - retriever.start(); - - // Info is null while processing - assertNull(retriever.getUpdateInfo()); - - waitfor(retriever); - assertFalse(connection.hasFailed()); - - UpdateInfo info = retriever.getUpdateInfo(); - assertNotNull(info); - - check(connection); - - assertEquals(BuildProperties.getVersion(), info.getLatestVersion()); - assertEquals(0, info.getUpdates().size()); - } - - - - @Test - public void testInvalidResponses() { - HttpURLConnectionMock connection = setup(); - connection.setResponseCode(404); - connection.setContent("Version: 1.2.3"); - - UpdateInfoRetriever retriever = new UpdateInfoRetriever(); - retriever.start(); - assertNull(retriever.getUpdateInfo()); - waitfor(retriever); - assertFalse(connection.hasFailed()); - assertNull(retriever.getUpdateInfo()); - check(connection); - - - connection = setup(); - connection.setResponseCode(Communicator.UPDATE_INFO_UPDATE_AVAILABLE); - connection.setContentType("text/xml"); - - retriever = new UpdateInfoRetriever(); - retriever.start(); - assertNull(retriever.getUpdateInfo()); - waitfor(retriever); - assertFalse(connection.hasFailed()); - assertNull(retriever.getUpdateInfo()); - check(connection); - - - - connection = setup(); - connection.setResponseCode(Communicator.UPDATE_INFO_UPDATE_AVAILABLE); - String content = - "100:hundred\n" + - "50: m\u00e4 \n\n" + - "1: one\n"; - connection.setContent(content); - - retriever = new UpdateInfoRetriever(); - retriever.start(); - assertNull(retriever.getUpdateInfo()); - waitfor(retriever); - assertFalse(connection.hasFailed()); - assertNull(retriever.getUpdateInfo()); - check(connection); - - - connection = setup(); - connection.setResponseCode(Communicator.UPDATE_INFO_UPDATE_AVAILABLE); - connection.setContent(new byte[0]); - - retriever = new UpdateInfoRetriever(); - retriever.start(); - assertNull(retriever.getUpdateInfo()); - waitfor(retriever); - assertFalse(connection.hasFailed()); - assertNull(retriever.getUpdateInfo()); - check(connection); - - } - - @Test - public void testRandomInputData() { - - Random rnd = new Random(); - for (int i=0; i<10; i++) { - int size = (int) ((1 + 0.3 * rnd.nextGaussian()) * Math.pow(i, 6)); - byte[] buf = new byte[size]; - rnd.nextBytes(buf); - - HttpURLConnectionMock connection = setup(); - connection.setResponseCode(Communicator.UPDATE_INFO_UPDATE_AVAILABLE); - connection.setContent(buf); - - UpdateInfoRetriever retriever = new UpdateInfoRetriever(); - retriever.start(); - assertNull(retriever.getUpdateInfo()); - waitfor(retriever); - assertFalse(connection.hasFailed()); - assertNull(retriever.getUpdateInfo()); - check(connection); - } - - } - - - - private void waitfor(UpdateInfoRetriever retriever) { - long t = System.currentTimeMillis(); - - while (retriever.isRunning()) { - if (System.currentTimeMillis() >= t+ALLOWANCE) { - fail("retriever took too long to respond"); - } - - try { - Thread.sleep(10); - } catch (InterruptedException e) { } - } - - System.out.println("Waiting took " + (System.currentTimeMillis()-t) + " ms"); - } - -} diff --git a/core/test/net/sf/openrocket/database/MotorSetDatabaseTest.java b/core/test/net/sf/openrocket/database/MotorSetDatabaseTest.java deleted file mode 100644 index 06e8d835..00000000 --- a/core/test/net/sf/openrocket/database/MotorSetDatabaseTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.database; - -import static org.junit.Assert.*; - -import java.util.List; - -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.Coordinate; - -import org.junit.Test; - - -public class MotorSetDatabaseTest { - - @Test - public void testMotorLoading() { - - ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(true) { - @Override - protected void loadMotors() { - try { - Thread.sleep(200); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - this.addMotor(new ThrustCurveMotor(Manufacturer.getManufacturer("A"), - "Foo", "Desc", Motor.Type.SINGLE, new double[] { 0 }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 1, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestA")); - this.addMotor(new ThrustCurveMotor(Manufacturer.getManufacturer("A"), - "Bar", "Desc", Motor.Type.SINGLE, new double[] { 0 }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 1, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestB")); - this.addMotor(new ThrustCurveMotor(Manufacturer.getManufacturer("A"), - "Foo", "Desc", Motor.Type.UNKNOWN, new double[] { 0 }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 1, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestA")); - } - }; - - assertFalse(db.isLoaded()); - db.startLoading(); - assertFalse(db.isLoaded()); - List<ThrustCurveMotorSet> list = db.getMotorSets(); - assertTrue(db.isLoaded()); - - assertEquals(2, list.size()); - assertEquals(1, list.get(0).getMotors().size()); - assertEquals(1, list.get(1).getMotors().size()); - assertEquals("Bar", list.get(0).getMotors().get(0).getDesignation()); - assertEquals("Foo", list.get(1).getMotors().get(0).getDesignation()); - } - -} diff --git a/core/test/net/sf/openrocket/database/ThrustCurveMotorSetTest.java b/core/test/net/sf/openrocket/database/ThrustCurveMotorSetTest.java deleted file mode 100644 index 2432f279..00000000 --- a/core/test/net/sf/openrocket/database/ThrustCurveMotorSetTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package net.sf.openrocket.database; - -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.Collections; - -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; -import net.sf.openrocket.util.Coordinate; - -import org.junit.Test; - -public class ThrustCurveMotorSetTest { - - - private static final ThrustCurveMotor motor1 = new ThrustCurveMotor( - Manufacturer.getManufacturer("A"), - "F12X", "Desc", Motor.Type.UNKNOWN, new double[] { }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 1, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestA"); - - private static final ThrustCurveMotor motor2 = new ThrustCurveMotor( - Manufacturer.getManufacturer("A"), - "F12H", "Desc", Motor.Type.SINGLE, new double[] { 5 }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 1, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestB"); - - private static final ThrustCurveMotor motor3 = new ThrustCurveMotor( - Manufacturer.getManufacturer("A"), - "F12", "Desc", Motor.Type.UNKNOWN, new double[] { 0, Motor.PLUGGED }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 2, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestC"); - - private static final ThrustCurveMotor motor4 = new ThrustCurveMotor( - Manufacturer.getManufacturer("A"), - "F12", "Desc", Motor.Type.HYBRID, new double[] { 0 }, - 0.024, 0.07, new double[] { 0, 1, 2 }, new double[] {0, 2, 0}, - new Coordinate[] {Coordinate.NUL, Coordinate.NUL, Coordinate.NUL}, "digestD"); - - - @Test - public void testSimplifyDesignation() { - assertEquals("J115", ThrustCurveMotorSet.simplifyDesignation("J115")); - assertEquals("J115", ThrustCurveMotorSet.simplifyDesignation(" J115 ")); - assertEquals("H115", ThrustCurveMotorSet.simplifyDesignation("241H115-KS")); - assertEquals("J115", ThrustCurveMotorSet.simplifyDesignation("384 J115")); - assertEquals("J115", ThrustCurveMotorSet.simplifyDesignation("384-J115")); - assertEquals("A2", ThrustCurveMotorSet.simplifyDesignation("A2T")); - assertEquals("1/2A2T", ThrustCurveMotorSet.simplifyDesignation("1/2A2T")); - assertEquals("Micro Maxx II", ThrustCurveMotorSet.simplifyDesignation("Micro Maxx II")); - } - - @Test - public void testAdding() { - ThrustCurveMotorSet set = new ThrustCurveMotorSet(); - - // Test empty set - assertNull(set.getManufacturer()); - assertEquals(0, set.getMotors().size()); - - // Add motor1 - assertTrue(set.matches(motor1)); - set.addMotor(motor1); - assertEquals(motor1.getManufacturer(), set.getManufacturer()); - assertEquals(motor1.getDesignation(), set.getDesignation()); - assertEquals(Motor.Type.UNKNOWN, set.getType()); - assertEquals(motor1.getDiameter(), set.getDiameter(), 0.00001); - assertEquals(motor1.getLength(), set.getLength(), 0.00001); - assertEquals(1, set.getMotors().size()); - assertEquals(motor1, set.getMotors().get(0)); - assertEquals(Collections.emptyList(), set.getDelays()); - - // Add motor1 again - assertTrue(set.matches(motor1)); - set.addMotor(motor1); - assertEquals(motor1.getManufacturer(), set.getManufacturer()); - assertEquals(motor1.getDesignation(), set.getDesignation()); - assertEquals(Motor.Type.UNKNOWN, set.getType()); - assertEquals(motor1.getDiameter(), set.getDiameter(), 0.00001); - assertEquals(motor1.getLength(), set.getLength(), 0.00001); - assertEquals(1, set.getMotors().size()); - assertEquals(motor1, set.getMotors().get(0)); - assertEquals(Collections.emptyList(), set.getDelays()); - - // Add motor2 - assertTrue(set.matches(motor2)); - set.addMotor(motor2); - assertEquals(motor1.getManufacturer(), set.getManufacturer()); - assertEquals(motor3.getDesignation(), set.getDesignation()); - assertEquals(Motor.Type.SINGLE, set.getType()); - assertEquals(motor1.getDiameter(), set.getDiameter(), 0.00001); - assertEquals(motor1.getLength(), set.getLength(), 0.00001); - assertEquals(2, set.getMotors().size()); - assertEquals(motor2, set.getMotors().get(0)); - assertEquals(motor1, set.getMotors().get(1)); - assertEquals(Arrays.asList(5.0), set.getDelays()); - - // Add motor3 - assertTrue(set.matches(motor3)); - set.addMotor(motor3); - assertEquals(motor1.getManufacturer(), set.getManufacturer()); - assertEquals(motor3.getDesignation(), set.getDesignation()); - assertEquals(Motor.Type.SINGLE, set.getType()); - assertEquals(motor1.getDiameter(), set.getDiameter(), 0.00001); - assertEquals(motor1.getLength(), set.getLength(), 0.00001); - assertEquals(3, set.getMotors().size()); - assertEquals(motor3, set.getMotors().get(0)); - assertEquals(motor2, set.getMotors().get(1)); - assertEquals(motor1, set.getMotors().get(2)); - assertEquals(Arrays.asList(0.0, 5.0, Motor.PLUGGED), set.getDelays()); - - // Test that adding motor4 fails - assertFalse(set.matches(motor4)); - try { - set.addMotor(motor4); - fail("Did not throw exception"); - } catch (IllegalArgumentException e) { - } - } - -} diff --git a/core/test/net/sf/openrocket/file/iterator/TestDirectoryIterator.java b/core/test/net/sf/openrocket/file/iterator/TestDirectoryIterator.java deleted file mode 100644 index dce14861..00000000 --- a/core/test/net/sf/openrocket/file/iterator/TestDirectoryIterator.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.sf.openrocket.file.iterator; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; - -import org.junit.Test; - -public class TestDirectoryIterator { - - @Test - public void testDirectoryIterator() throws IOException { - DirectoryIterator iterator = new DirectoryIterator(new File("test/net/sf/openrocket/file"), new FileFilter() { - @Override - public boolean accept(File pathname) { - return pathname.getName().matches("^Test(Directory|File)Iterator.java"); - } - }, true); - - while (iterator.hasNext()) { - System.out.println("" + iterator.next()); - } - - } -} diff --git a/core/test/net/sf/openrocket/file/iterator/TestFileIterator.java b/core/test/net/sf/openrocket/file/iterator/TestFileIterator.java deleted file mode 100644 index c3e424ee..00000000 --- a/core/test/net/sf/openrocket/file/iterator/TestFileIterator.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.sf.openrocket.file.iterator; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import net.sf.openrocket.util.Pair; - -import org.junit.Test; - -public class TestFileIterator { - - @Test - public void testFileIterator() { - final Pair<String, InputStream> one = new Pair<String, InputStream>("one", new ByteArrayInputStream(new byte[] { 1 })); - final Pair<String, InputStream> two = new Pair<String, InputStream>("two", new ByteArrayInputStream(new byte[] { 2 })); - - FileIterator iterator = new FileIterator() { - private int count = 0; - - @Override - protected Pair<String, InputStream> findNext() { - count++; - switch (count) { - case 1: - return one; - case 2: - return two; - default: - return null; - } - } - }; - - assertTrue(iterator.hasNext()); - assertEquals(one, iterator.next()); - assertEquals(two, iterator.next()); - assertFalse(iterator.hasNext()); - } -} diff --git a/core/test/net/sf/openrocket/file/motor/TestMotorLoader.java b/core/test/net/sf/openrocket/file/motor/TestMotorLoader.java deleted file mode 100644 index dbc23e74..00000000 --- a/core/test/net/sf/openrocket/file/motor/TestMotorLoader.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.sf.openrocket.file.motor; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.List; - -import net.sf.openrocket.motor.Motor; -import net.sf.openrocket.motor.ThrustCurveMotor; - -import org.junit.Test; - -public class TestMotorLoader { - - private static final String DIGEST1 = "e523030bc96d5e63313b5723aaea267d"; - private static final String DIGEST2 = "6a41f0f10b7283793eb0e6b389753729"; - - - @Test - public void testGeneralMotorLoader() throws IOException { - MotorLoader loader = new GeneralMotorLoader(); - - test(loader, "test1.eng", DIGEST1); - test(loader, "test2.rse", DIGEST2); - test(loader, "test.zip", DIGEST2, DIGEST1); - - } - - @Test - public void testRASPMotorLoader() throws IOException { - test(new RASPMotorLoader(), "test1.eng", DIGEST1); - } - - @Test - public void testRocksimMotorLoader() throws IOException { - test(new RockSimMotorLoader(), "test2.rse", DIGEST2); - } - - @Test - public void testZipMotorLoader() throws IOException { - test(new ZipFileMotorLoader(), "test.zip", DIGEST2, DIGEST1); - } - - - private void test(MotorLoader loader, String file, String... digests) throws IOException { - List<Motor> motors; - - InputStream is = this.getClass().getResourceAsStream(file); - assertNotNull("File " + file + " not found", is); - motors = loader.load(is, file); - is.close(); - assertEquals(digests.length, motors.size()); - - String[] d = new String[digests.length]; - for (int i = 0; i < motors.size(); i++) { - d[i] = ((ThrustCurveMotor) motors.get(i)).getDigest(); - } - - Arrays.sort(digests); - Arrays.sort(d); - assertTrue("d = " + Arrays.toString(d) + " digests = " + Arrays.toString(digests), Arrays.equals(d, digests)); - } - -} diff --git a/core/test/net/sf/openrocket/file/motor/test.txt b/core/test/net/sf/openrocket/file/motor/test.txt deleted file mode 100644 index 4b43be8f..00000000 --- a/core/test/net/sf/openrocket/file/motor/test.txt +++ /dev/null @@ -1 +0,0 @@ -boo bah diff --git a/core/test/net/sf/openrocket/file/motor/test.zip b/core/test/net/sf/openrocket/file/motor/test.zip deleted file mode 100644 index eeb5ef7c..00000000 Binary files a/core/test/net/sf/openrocket/file/motor/test.zip and /dev/null differ diff --git a/core/test/net/sf/openrocket/file/motor/test1.eng b/core/test/net/sf/openrocket/file/motor/test1.eng deleted file mode 100644 index 06dc100e..00000000 --- a/core/test/net/sf/openrocket/file/motor/test1.eng +++ /dev/null @@ -1,24 +0,0 @@ -D10 18 70 7 0.009800000000000001 0.0259 AT - 0.0070 23.0 - 0.018 25.0 - 0.027 20.25 - 0.066 20.25 - 0.073 18.5 - 0.094 20.25 - 0.112 20.75 - 0.137 19.75 - 0.163 21.5 - 0.202 20.75 - 0.231 20.75 - 0.254 22.75 - 0.27 20.75 - 0.504 20.0 - 0.536 18.25 - 0.607 17.0 - 0.687 14.75 - 0.751 14.25 - 0.84 11.25 - 0.998 8.25 - 1.024 8.25 - 1.248 2.5 - 1.385 0.0 diff --git a/core/test/net/sf/openrocket/file/motor/test2.rse b/core/test/net/sf/openrocket/file/motor/test2.rse deleted file mode 100644 index a77408f8..00000000 --- a/core/test/net/sf/openrocket/file/motor/test2.rse +++ /dev/null @@ -1,52 +0,0 @@ -<engine-database> - <engine-list> - <engine mfg="Cesaroni Technology Inc." code="G115-13A" Type="reloadable" dia="38." -len="127." initWt="195." propWt="61.8" delays="13" auto-calc-mass="1" -auto-calc-cg="1" avgThrust="113.512" peakThrust="131.895" throatDia="0." -exitDia="0." Itot="140.755" burn-time="1.24" massFrac="31.69" Isp="232.25" -tDiv="10" tStep="-1." tFix="1" FDiv="10" FStep="-1." FFix="1" mDiv="10" -mStep="-1." mFix="1" cgDiv="10" cgStep="-1." cgFix="1"> - <data> - <eng-data t="0." f="0." m="61.8" cg="63.5"/> - <eng-data t="0.00787402" f="10.3447" m="61.7821" cg="63.5"/> - <eng-data t="0.0183727" f="117.671" m="61.4871" cg="63.5"/> - <eng-data t="0.0209974" f="128.447" m="61.3453" cg="63.5"/> - <eng-data t="0.0446194" f="131.895" m="59.9952" cg="63.5"/> - <eng-data t="0.0577428" f="125.861" m="59.2526" cg="63.5"/> - <eng-data t="0.0629921" f="119.395" m="58.97" cg="63.5"/> - <eng-data t="0.0787402" f="113.792" m="58.1638" cg="63.5"/> - <eng-data t="0.107612" f="115.947" m="56.7077" cg="63.5"/> - <eng-data t="0.149606" f="118.964" m="54.542" cg="63.5"/> - <eng-data t="0.188976" f="119.395" m="52.4819" cg="63.5"/> - <eng-data t="0.233596" f="121.981" m="50.1176" cg="63.5"/> - <eng-data t="0.278215" f="122.412" m="47.7237" cg="63.5"/> - <eng-data t="0.322835" f="122.843" m="45.3213" cg="63.5"/> - <eng-data t="0.380577" f="123.274" m="42.2014" cg="63.5"/> - <eng-data t="0.440945" f="122.843" m="38.9398" cg="63.5"/> - <eng-data t="0.480315" f="123.274" m="36.8126" cg="63.5"/> - <eng-data t="0.540682" f="122.843" m="33.5509" cg="63.5"/> - <eng-data t="0.590551" f="122.412" m="30.866" cg="63.5"/> - <eng-data t="0.622047" f="120.688" m="29.1851" cg="63.5"/> - <eng-data t="0.67979" f="120.257" m="26.1308" cg="63.5"/> - <eng-data t="0.734908" f="119.395" m="23.231" cg="63.5"/> - <eng-data t="0.790026" f="117.671" m="20.3625" cg="63.5"/> - <eng-data t="0.845144" f="116.809" m="17.5253" cg="63.5"/> - <eng-data t="0.88189" f="116.378" m="15.6442" cg="63.5"/> - <eng-data t="0.929134" f="113.361" m="13.2615" cg="63.5"/> - <eng-data t="0.979003" f="113.361" m="10.7794" cg="63.5"/> - <eng-data t="1.0315" f="111.206" m="8.19152" cg="63.5"/> - <eng-data t="1.07087" f="108.188" m="6.29532" cg="63.5"/> - <eng-data t="1.11286" f="108.188" m="4.30052" cg="63.5"/> - <eng-data t="1.16535" f="106.033" m="1.83186" cg="63.5"/> - <eng-data t="1.18373" f="112.499" m="0.95044" cg="63.5"/> - <eng-data t="1.18635" f="96.5506" m="0.829987" cg="63.5"/> - <eng-data t="1.19685" f="81.0335" m="0.420696" cg="63.5"/> - <eng-data t="1.2021" f="51.7235" m="0.267708" cg="63.5"/> - <eng-data t="1.2126" f="30.172" m="0.0789575" cg="63.5"/> - <eng-data t="1.21522" f="16.8101" m="0.0518866" cg="63.5"/> - <eng-data t="1.21785" f="7.75853" m="0.0377303" cg="63.5"/> - <eng-data t="1.24" f="0." m="0." cg="63.5"/> - </data> - </engine> -</engine-list> -</engine-database> diff --git a/core/test/net/sf/openrocket/file/rocksim/export/RocksimDocumentDTOTest.java b/core/test/net/sf/openrocket/file/rocksim/export/RocksimDocumentDTOTest.java deleted file mode 100644 index 7feb8d23..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/export/RocksimDocumentDTOTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.sf.openrocket.file.rocksim.export; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.rocksim.importt.RocksimLoader; -import net.sf.openrocket.file.rocksim.importt.RocksimLoaderTest; -import net.sf.openrocket.file.rocksim.importt.RocksimTestBase; -import org.junit.Assert; -import org.junit.Test; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import java.io.File; -import java.io.FileWriter; -import java.io.StringWriter; - -/** - */ -public class RocksimDocumentDTOTest extends RocksimTestBase { - - @Test - public void testDTO() throws Exception { - JAXBContext binder = JAXBContext.newInstance(RocksimDocumentDTO.class); - Marshaller marshaller = binder.createMarshaller(); - marshaller.setProperty("jaxb.fragment", Boolean.TRUE); - - NoseConeDTO noseCone = new NoseConeDTO(); - noseCone.setBaseDia(10d); - noseCone.setCalcCG(1.3d); - - StageDTO stage1 = new StageDTO(); - stage1.addExternalPart(noseCone); - - RocketDesignDTO design2 = new RocketDesignDTO(); - design2.setName("Test"); - design2.setStage3(stage1); - - RocksimDesignDTO design = new RocksimDesignDTO(); - design.setDesign(design2); - RocksimDocumentDTO message = new RocksimDocumentDTO(); - message.setDesign(design); - - - StringWriter stringWriter = new StringWriter(); - marshaller.marshal(message, stringWriter); - - String response = stringWriter.toString(); - - System.err.println(response); - } - - @Test - public void testRoundTrip() throws Exception { - OpenRocketDocument ord = RocksimLoaderTest.loadRocksimRocket3(new RocksimLoader()); - - Assert.assertNotNull(ord); - String result = new RocksimSaver().marshalToRocksim(ord); - -// System.err.println(result); - - File output = new File("rt.rkt"); - FileWriter fw = new FileWriter(output); - fw.write(result); - fw.flush(); - fw.close(); - } -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/BodyTubeHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/BodyTubeHandlerTest.java deleted file mode 100644 index 8b8bc3b6..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/BodyTubeHandlerTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * BodyTubeHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; - -/** - * BodyTubeHandler Tester. - * - */ -public class BodyTubeHandlerTest extends RocksimTestBase { - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testConstructor() throws Exception { - - try { - new BodyTubeHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - Stage stage = new Stage(); - BodyTubeHandler handler = new BodyTubeHandler(stage, new WarningSet()); - BodyTube component = (BodyTube) getField(handler, "bodyTube"); - assertContains(component, stage.getChildren()); - } - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new BodyTubeHandler(new Stage(), new WarningSet()).openElement(null, null, null)); - Assert.assertNotNull(new BodyTubeHandler(new Stage(), new WarningSet()).openElement("AttachedParts", null, null)); - } - - /** - * - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testCloseElement() throws Exception { - Stage stage = new Stage(); - BodyTubeHandler handler = new BodyTubeHandler(stage, new WarningSet()); - BodyTube component = (BodyTube) getField(handler, "bodyTube"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("OD", attributes, "0", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("OD", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getInnerRadius(), 0.001); - handler.closeElement("OD", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ID", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "0", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("IsMotorMount", attributes, "1", warnings); - Assert.assertTrue(component.isMotorMount()); - handler.closeElement("IsMotorMount", attributes, "0", warnings); - Assert.assertFalse(component.isMotorMount()); - handler.closeElement("IsMotorMount", attributes, "foo", warnings); - Assert.assertFalse(component.isMotorMount()); - - handler.closeElement("EngineOverhang", attributes, "-1", warnings); - Assert.assertEquals(-1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getMotorOverhang(), 0.001); - handler.closeElement("EngineOverhang", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getMotorOverhang(), 0.001); - handler.closeElement("EngineOverhang", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getMotorOverhang(), 0.001); - handler.closeElement("EngineOverhang", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("FinishCode", attributes, "-1", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "100", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new BodyTubeHandler(new Stage(), new WarningSet()).getComponent() instanceof BodyTube); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.BULK, new BodyTubeHandler(new Stage(), new WarningSet()).getMaterialType()); - } - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/FinSetHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/FinSetHandlerTest.java deleted file mode 100644 index 503654bc..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/FinSetHandlerTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * FinSetHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import junit.framework.TestCase; -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.EllipticalFinSet; -import net.sf.openrocket.rocketcomponent.FinSet; -import net.sf.openrocket.rocketcomponent.TrapezoidFinSet; -import net.sf.openrocket.util.Coordinate; - -import java.lang.reflect.Method; -import java.util.HashMap; - -/** - * FinSetHandler Tester. - * - */ -public class FinSetHandlerTest extends TestCase { - - /** - * Method: asOpenRocket(WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testAsOpenRocket() throws Exception { - - FinSetHandler dto = new FinSetHandler(new BodyTube()); - - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - dto.closeElement("Name", attributes, "The name", warnings); - dto.closeElement("ShapeCode", attributes, "0", warnings); - dto.closeElement("Xb", attributes, "2", warnings); - dto.closeElement("FinCount", attributes, "4", warnings); - dto.closeElement("RootChord", attributes, "10", warnings); - dto.closeElement("TipChord", attributes, "11", warnings); - dto.closeElement("SemiSpan", attributes, "12", warnings); - dto.closeElement("MidChordLen", attributes, "13", warnings); - dto.closeElement("SweepDistance", attributes, "14", warnings); - dto.closeElement("Thickness", attributes, "200", warnings); - dto.closeElement("TipShapeCode", attributes, "1", warnings); - dto.closeElement("TabLength", attributes, "400", warnings); - dto.closeElement("TabDepth", attributes, "500", warnings); - dto.closeElement("TabOffset", attributes, "30", warnings); - dto.closeElement("RadialAngle", attributes, ".123", warnings); - dto.closeElement("PointList", attributes, "20,0|2,2|0,0", warnings); - dto.closeElement("LocationMode", attributes, "0", warnings); - - WarningSet set = new WarningSet(); - FinSet fins = dto.asOpenRocket(set); - assertNotNull(fins); - assertEquals(0, set.size()); - - assertEquals("The name", fins.getName()); - assertTrue(fins instanceof TrapezoidFinSet); - assertEquals(4, fins.getFinCount()); - - assertEquals(0.012d, ((TrapezoidFinSet) fins).getHeight()); - assertEquals(0.012d, fins.getSpan()); - - assertEquals(0.2d, fins.getThickness()); - assertEquals(0.4d, fins.getTabLength()); - assertEquals(0.5d, fins.getTabHeight()); - assertEquals(0.03d, fins.getTabShift()); - assertEquals(.123d, fins.getBaseRotation()); - - dto.closeElement("ShapeCode", attributes, "1", warnings); - fins = dto.asOpenRocket(set); - assertNotNull(fins); - assertEquals(0, set.size()); - - assertEquals("The name", fins.getName()); - assertTrue(fins instanceof EllipticalFinSet); - assertEquals(4, fins.getFinCount()); - - assertEquals(0.2d, fins.getThickness()); - assertEquals(0.4d, fins.getTabLength()); - assertEquals(0.5d, fins.getTabHeight()); - assertEquals(0.03d, fins.getTabShift()); - assertEquals(.123d, fins.getBaseRotation()); - } - - - /** - * Method: toCoordinates(String pointList) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testToCoordinates() throws Exception { - FinSetHandler holder = new FinSetHandler(new BodyTube()); - Method method = FinSetHandler.class.getDeclaredMethod("toCoordinates", String.class, WarningSet.class); - method.setAccessible(true); - - WarningSet warnings = new WarningSet(); - //Null finlist - String finlist = null; - Coordinate[] result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(0 == result.length); - - //Empty string finlist - finlist = ""; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(0 == result.length); - - //Invalid finlist (only x coordinate) - finlist = "10.0"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(0 == result.length); - assertEquals(1, warnings.size()); - warnings.clear(); - - //Invalid finlist (non-numeric character) - finlist = "10.0,asdf"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(0 == result.length); - assertEquals(1, warnings.size()); - warnings.clear(); - - //Invalid finlist (all delimiters) - finlist = "||||||"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(0 == result.length); - assertEquals(0, warnings.size()); - warnings.clear(); - - //One point finlist - from a parsing view it's valid; from a practical view it may not be, but that's outside - //the scope of this test case - finlist = "10.0,5.0"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(1 == result.length); - assertEquals(0, warnings.size()); - warnings.clear(); - - //Two point finlist - from a parsing view it's valid; from a practical view it may not be, but that's outside - //the scope of this test case - finlist = "10.0,5.0|3.3,4.4"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(2 == result.length); - assertEquals(0, warnings.size()); - warnings.clear(); - - //Normal four point finlist. - finlist = "518.16,0|517.494,37.2145|1.31261,6.77283|0,0|"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(4 == result.length); - assertEquals(new Coordinate(0,0), result[0]); - assertEquals(0, warnings.size()); - warnings.clear(); - - //Normal four point finlist with spaces. - finlist = "518.16 , 0 | 517.494 , 37.2145 | 1.31261,6.77283|0,0|"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(4 == result.length); - assertEquals(new Coordinate(0,0), result[0]); - assertEquals(new Coordinate(.51816,0), result[3]); - assertEquals(0, warnings.size()); - warnings.clear(); - - //Reversed Normal four point finlist. - finlist = "0,0|1.31261,6.77283|517.494,37.2145|518.16,0|"; - result = (Coordinate[])method.invoke(holder, finlist, warnings); - assertNotNull(result); - assertTrue(4 == result.length); - assertEquals(new Coordinate(0,0), result[0]); - assertEquals(new Coordinate(.51816,0), result[3]); - assertEquals(0, warnings.size()); - warnings.clear(); - - } -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/InnerBodyTubeHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/InnerBodyTubeHandlerTest.java deleted file mode 100644 index f2533c35..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/InnerBodyTubeHandlerTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * InnerBodyTubeHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.InnerTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.junit.Assert; - -import java.util.HashMap; - -/** - * InnerBodyTubeHandler Tester. - * - */ -public class InnerBodyTubeHandlerTest extends RocksimTestBase { - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testConstructor() throws Exception { - - try { - new InnerBodyTubeHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - BodyTube tube = new BodyTube(); - InnerBodyTubeHandler handler = new InnerBodyTubeHandler(tube, new WarningSet()); - InnerTube component = (InnerTube) getField(handler, "bodyTube"); - assertContains(component, tube.getChildren()); - } - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new InnerBodyTubeHandler(new BodyTube(), new WarningSet()).openElement(null, null, null)); - Assert.assertNotNull(new InnerBodyTubeHandler(new BodyTube(), new WarningSet()).openElement("AttachedParts", null, null)); - } - - /** - * - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testCloseElement() throws Exception { - BodyTube tube = new BodyTube(); - InnerBodyTubeHandler handler = new InnerBodyTubeHandler(tube, new WarningSet()); - InnerTube component = (InnerTube) getField(handler, "bodyTube"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("OD", attributes, "0", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("OD", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getInnerRadius(), 0.001); - handler.closeElement("OD", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ID", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "0", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("IsMotorMount", attributes, "1", warnings); - Assert.assertTrue(component.isMotorMount()); - handler.closeElement("IsMotorMount", attributes, "0", warnings); - Assert.assertFalse(component.isMotorMount()); - handler.closeElement("IsMotorMount", attributes, "foo", warnings); - Assert.assertFalse(component.isMotorMount()); - - handler.closeElement("EngineOverhang", attributes, "-1", warnings); - Assert.assertEquals(-1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getMotorOverhang(), 0.001); - handler.closeElement("EngineOverhang", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getMotorOverhang(), 0.001); - handler.closeElement("EngineOverhang", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getMotorOverhang(), 0.001); - handler.closeElement("EngineOverhang", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - } - - /** - * Method: setRelativePosition(RocketComponent.Position position) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testSetRelativePosition() throws Exception { - BodyTube tube = new BodyTube(); - InnerBodyTubeHandler handler = new InnerBodyTubeHandler(tube, new WarningSet()); - InnerTube component = (InnerTube) getField(handler, "bodyTube"); - handler.setRelativePosition(RocketComponent.Position.ABSOLUTE); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new InnerBodyTubeHandler(new BodyTube(), new WarningSet()).getComponent() instanceof InnerTube); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.BULK, new InnerBodyTubeHandler(new BodyTube(), new WarningSet()).getMaterialType()); - } - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/LaunchLugHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/LaunchLugHandlerTest.java deleted file mode 100644 index 937c8cbc..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/LaunchLugHandlerTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * LaunchLugHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.junit.Assert; - -import java.util.HashMap; - -/** - * LaunchLugHandler Tester. - * - */ -public class LaunchLugHandlerTest extends RocksimTestBase { - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testConstructor() throws Exception { - - try { - new LaunchLugHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - BodyTube tube = new BodyTube(); - LaunchLugHandler handler = new LaunchLugHandler(tube, new WarningSet()); - LaunchLug component = (LaunchLug) getField(handler, "lug"); - assertContains(component, tube.getChildren()); - } - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new LaunchLugHandler(new BodyTube(), new WarningSet()).openElement(null, null, null)); - } - - /** - * - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testCloseElement() throws Exception { - BodyTube tube = new BodyTube(); - LaunchLugHandler handler = new LaunchLugHandler(tube, new WarningSet()); - LaunchLug component = (LaunchLug) getField(handler, "lug"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getOuterRadius(), 0.001); - handler.closeElement("OD", attributes, "0", warnings); - Assert.assertEquals(0d, component.getOuterRadius(), 0.001); - handler.closeElement("OD", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getOuterRadius(), 0.001); - handler.closeElement("OD", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ID", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "0", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("FinishCode", attributes, "-1", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "100", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - } - - /** - * Method: setRelativePosition(RocketComponent.Position position) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testSetRelativePosition() throws Exception { - BodyTube tube = new BodyTube(); - LaunchLugHandler handler = new LaunchLugHandler(tube, new WarningSet()); - LaunchLug component = (LaunchLug) getField(handler, "lug"); - handler.setRelativePosition(RocketComponent.Position.ABSOLUTE); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new LaunchLugHandler(new BodyTube(), new WarningSet()).getComponent() instanceof LaunchLug); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.BULK, new LaunchLugHandler(new BodyTube(), new WarningSet()).getMaterialType()); - } - - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/MassObjectHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/MassObjectHandlerTest.java deleted file mode 100644 index 89cf327a..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/MassObjectHandlerTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * MassObjectHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.MassComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.junit.Assert; - -import java.util.HashMap; - -/** - * MassObjectHandler Tester. - * - */ -public class MassObjectHandlerTest extends RocksimTestBase { - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testConstructor() throws Exception { - - try { - new MassObjectHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - BodyTube tube = new BodyTube(); - MassObjectHandler handler = new MassObjectHandler(tube, new WarningSet()); - MassComponent mass = (MassComponent) getField(handler, "mass"); - MassComponent current = (MassComponent) getField(handler, "current"); - Assert.assertEquals(mass, current); - } - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new MassObjectHandler(new BodyTube(), new WarningSet()).openElement(null, null, null)); - } - - /** - * - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testCloseElement() throws Exception { - BodyTube tube = new BodyTube(); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - MassObjectHandler handler = new MassObjectHandler(tube, new WarningSet()); - MassComponent component = (MassComponent) getField(handler, "mass"); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(0.01 - , component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(0.01 - , component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("KnownMass", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getComponentMass(), 0.001); - handler.closeElement("KnownMass", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_MASS, component.getComponentMass(), 0.001); - handler.closeElement("KnownMass", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - } - - /** - * Method: setRelativePosition(RocketComponent.Position position) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testSetRelativePosition() throws Exception { - BodyTube tube = new BodyTube(); - MassObjectHandler handler = new MassObjectHandler(tube, new WarningSet()); - MassComponent component = (MassComponent) getField(handler, "mass"); - handler.setRelativePosition(RocketComponent.Position.ABSOLUTE); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new MassObjectHandler(new BodyTube(), new WarningSet()).getComponent() instanceof MassComponent); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.LINE, new MassObjectHandler(new BodyTube(), new WarningSet()).getMaterialType()); - } -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/NoseConeHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/NoseConeHandlerTest.java deleted file mode 100644 index 03943d8b..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/NoseConeHandlerTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * NoseConeHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimNoseConeCode; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Transition; -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; - -/** - * NoseConeHandler Tester. - * - */ -public class NoseConeHandlerTest extends RocksimTestBase { - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testConstructor() throws Exception { - - try { - new NoseConeHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - Stage stage = new Stage(); - NoseConeHandler handler = new NoseConeHandler(stage, new WarningSet()); - NoseCone component = (NoseCone) getField(handler, "noseCone"); - assertContains(component, stage.getChildren()); - } - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new NoseConeHandler(new Stage(), new WarningSet()).openElement(null, null, null)); - Assert.assertNotNull(new NoseConeHandler(new Stage(), new WarningSet()).openElement("AttachedParts", null, null)); - } - - /** - * - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testCloseElement() throws Exception { - - Stage stage = new Stage(); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - NoseConeHandler handler = new NoseConeHandler(stage, warnings); - NoseCone component = (NoseCone) getField(handler, "noseCone"); - - handler.closeElement("ShapeCode", attributes, "0", warnings); - Assert.assertEquals(Transition.Shape.CONICAL, component.getType()); - handler.closeElement("ShapeCode", attributes, "1", warnings); - Assert.assertEquals(Transition.Shape.OGIVE, component.getType()); - handler.closeElement("ShapeCode", attributes, "17", warnings); - Assert.assertEquals(RocksimNoseConeCode.PARABOLIC.asOpenRocket(), component.getType()); //test of default - handler.closeElement("ShapeCode", attributes, "foo", warnings); - Assert.assertNotNull(component.getType()); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("BaseDia", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getAftRadius(), 0.001); - handler.closeElement("BaseDia", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getAftRadius(), 0.001); - handler.closeElement("BaseDia", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - - final double aft = 100d; - component.setAftRadius(aft); - - handler.closeElement("ConstructionType", attributes, "0", warnings); - component.setAftShoulderRadius(1.1d); - handler.closeElement("WallThickness", attributes, "-1", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(component.getAftRadius(), component.getThickness(), 0.001); - Assert.assertEquals(component.getAftShoulderThickness(), component.getAftShoulderThickness(), 0.001); - handler.closeElement("WallThickness", attributes, "100", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(aft, component.getThickness(), 0.001); - handler.closeElement("WallThickness", attributes, "foo", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ConstructionType", attributes, "1", warnings); - component.setAftShoulderRadius(1.1d); - handler.closeElement("WallThickness", attributes, "-1", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(0d, component.getThickness(), 0.001); - Assert.assertEquals(0d, component.getAftShoulderThickness(), 0.001); - handler.closeElement("WallThickness", attributes, "1.1", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(1.1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getThickness(), 0.001); - Assert.assertEquals(1.1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getAftShoulderThickness(), 0.001); - - handler.closeElement("ShoulderLen", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getAftShoulderLength(), 0.001); - handler.closeElement("ShoulderLen", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getAftShoulderLength(), 0.001); - handler.closeElement("ShoulderLen", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getAftShoulderLength(), 0.001); - handler.closeElement("ShoulderLen", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ShoulderOD", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getAftShoulderRadius(), 0.001); - handler.closeElement("ShoulderOD", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getAftShoulderRadius(), 0.001); - handler.closeElement("ShoulderOD", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - component.setType(Transition.Shape.HAACK); - handler.closeElement("ShapeParameter", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getShapeParameter(), 0.001); - handler.closeElement("ShapeParameter", attributes, "100", warnings); - Assert.assertEquals(Transition.Shape.HAACK.maxParameter(), component.getShapeParameter(), 0.001); - handler.closeElement("ShapeParameter", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - Assert.assertEquals("Could not convert ShapeParameter value of foo. It is expected to be a number.", - warnings.iterator().next().toString()); - - warnings.clear(); - - component.setType(Transition.Shape.CONICAL); - component.setShapeParameter(0d); - handler.closeElement("ShapeParameter", attributes, "100", warnings); - Assert.assertEquals(0d, component.getShapeParameter(), 0.001); - - handler.closeElement("FinishCode", attributes, "-1", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "100", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - - handler.closeElement("Material", attributes, "Some Material", warnings); - handler.endHandler("NoseCone", attributes, null, warnings); - Assert.assertTrue(component.getMaterial().getName().contains("Some Material")); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new NoseConeHandler(new Stage(), new WarningSet()).getComponent() instanceof NoseCone); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.BULK, new NoseConeHandler(new Stage(), new WarningSet()).getMaterialType()); - } -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/ParachuteHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/ParachuteHandlerTest.java deleted file mode 100644 index 135a94fc..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/ParachuteHandlerTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * ParachuteHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import org.junit.Assert; - -import java.util.HashMap; - -/** - * ParachuteHandler Tester. - */ -public class ParachuteHandlerTest extends RocksimTestBase { - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new ParachuteHandler(new BodyTube(), new WarningSet()).openElement(null, null, null)); - } - - /** - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testCloseElement() throws Exception { - - BodyTube tube = new BodyTube(); - ParachuteHandler handler = new ParachuteHandler(tube, new WarningSet()); - Parachute component = (Parachute) getField(handler, "chute"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - - handler.closeElement("DragCoefficient", attributes, "0.94", warnings); - Assert.assertEquals(0.94d, component.getCD(), 0.001); - handler.closeElement("DragCoefficient", attributes, "-0.94", warnings); - Assert.assertEquals(-0.94d, component.getCD(), 0.001); - handler.closeElement("DragCoefficient", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Dia", attributes, "-1", warnings); - Assert.assertEquals(-1d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getDiameter(), 0.001); - handler.closeElement("Dia", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getDiameter(), 0.001); - handler.closeElement("Dia", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ShroudLineCount", attributes, "-1", warnings); - Assert.assertEquals(0, component.getLineCount()); - handler.closeElement("ShroudLineCount", attributes, "10", warnings); - Assert.assertEquals(10, component.getLineCount()); - handler.closeElement("ShroudLineCount", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ShroudLineLen", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLineLength(), 0.001); - handler.closeElement("ShroudLineLen", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLineLength(), 0.001); - handler.closeElement("ShroudLineLen", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - } - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testConstructor() throws Exception { - - try { - new ParachuteHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - BodyTube tube = new BodyTube(); - ParachuteHandler handler = new ParachuteHandler(tube, new WarningSet()); - Parachute component = (Parachute) getField(handler, "chute"); - assertContains(component, tube.getChildren()); - } - - /** - * Method: setRelativePosition(RocketComponent.Position position) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testSetRelativePosition() throws Exception { - BodyTube tube = new BodyTube(); - ParachuteHandler handler = new ParachuteHandler(tube, new WarningSet()); - Parachute component = (Parachute) getField(handler, "chute"); - handler.setRelativePosition(RocketComponent.Position.ABSOLUTE); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new ParachuteHandler(new BodyTube(), new WarningSet()).getComponent() instanceof Parachute); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.SURFACE, new ParachuteHandler(new BodyTube(), new WarningSet()).getMaterialType()); - } - - /** - * Method: endHandler() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testEndHandler() throws Exception { - BodyTube tube = new BodyTube(); - ParachuteHandler handler = new ParachuteHandler(tube, new WarningSet()); - Parachute component = (Parachute) getField(handler, "chute"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("Xb", attributes, "-10", warnings); - handler.closeElement("LocationMode", attributes, "1", warnings); - handler.endHandler("Parachute", attributes, null, warnings); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - Assert.assertEquals(component.getPositionValue(), -10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, 0.001); - - handler.closeElement("Xb", attributes, "-10", warnings); - handler.closeElement("LocationMode", attributes, "2", warnings); - handler.endHandler("Parachute", attributes, null, warnings); - Assert.assertEquals(RocketComponent.Position.BOTTOM, component.getRelativePosition()); - Assert.assertEquals(component.getPositionValue(), 10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, 0.001); - } -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/PodFins.rkt b/core/test/net/sf/openrocket/file/rocksim/importt/PodFins.rkt deleted file mode 100644 index a137008f..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/PodFins.rkt +++ /dev/null @@ -1,605 +0,0 @@ -<RockSimDocument> - <FileVersion>4</FileVersion> - <DesignInformation> - <RocketDesign> - <CalculateCD>1</CalculateCD> - <ProCalculateCD>1</ProCalculateCD> - <ProCalculateCN>1</ProCalculateCN> - <FixedCd>0.75</FixedCd> - <FixedCd2>0.8</FixedCd2> - <FixedCd3>0.81</FixedCd3> - <FixedCd2Alone>0.95</FixedCd2Alone> - <FixedCd3Alone>0.95</FixedCd3Alone> - <StageCount>1</StageCount> - <Stage3Mass>0.</Stage3Mass> - <Stage2Mass>0.</Stage2Mass> - <Stage1Mass>0.</Stage1Mass> - <Stage321CG>0.</Stage321CG> - <Stage32CG>0.</Stage32CG> - <Stage3CG>0.</Stage3CG> - <Stage2CGAlone>0.</Stage2CGAlone> - <Stage1CGAlone>0.</Stage1CGAlone> - <CPCalcFlags>1</CPCalcFlags> - <LaunchGuideLength>914.4</LaunchGuideLength> - <UseKnownMass>0</UseKnownMass> - <DefaultFinish>0</DefaultFinish> - <FinishMedium>0</FinishMedium> - <FinishCoatCount>1</FinishCoatCount> - <GlueType>0</GlueType> - <CPSimFlags>1</CPSimFlags> - <LastSerialNumber>7</LastSerialNumber> - <DisplayFlags>1</DisplayFlags> - <MetricsFlags>0</MetricsFlags> - <BarromanXN>0,567.719,0,0</BarromanXN> - <BarrowmanCNa>0,19.2193,0,0</BarrowmanCNa> - <RockSimXN>0,571.25,0,0</RockSimXN> - <RockSimCNa>0,28.2677,0,0</RockSimCNa> - <RockSimCNa90>0,0,0,0</RockSimCNa90> - <RockSimXN90>0,0,0,0</RockSimXN90> - <ViewType>0</ViewType> - <ViewStageCount>1</ViewStageCount> - <ViewTypeEdit>0</ViewTypeEdit> - <ViewStageCountEdit>1</ViewStageCountEdit> - <ZoomFactor>0.</ZoomFactor> - <ZoomFactorEdit>0.</ZoomFactorEdit> - <ScrollPosX>0</ScrollPosX> - <ScrollPosY>0</ScrollPosY> - <ScrollPosXEdit>0</ScrollPosXEdit> - <ScrollPosYEdit>0</ScrollPosYEdit> - <ThreeDFlags>0</ThreeDFlags> - <ThreeDFlagsEdit>0</ThreeDFlagsEdit> - <UseModelSprite>0</UseModelSprite> - <StaticMarginRef>0</StaticMarginRef> - <UserRefDiameter>0.</UserRefDiameter> - <SideMarkerHeight>10.</SideMarkerHeight> - <SideDimensionHeight>10.</SideDimensionHeight> - <BaseMarkerHeight>10.</BaseMarkerHeight> - <BaseDimensionHeight>10.</BaseDimensionHeight> - <ShowGlideCP>0</ShowGlideCP> - <ShowGridTypeSide>0</ShowGridTypeSide> - <ShowGridTypeBase>0</ShowGridTypeBase> - <GridSpacing>10.</GridSpacing> - <GridOpacity>0.15</GridOpacity> - <GridColor>black</GridColor> - <MaxDiaWithFins>259.588</MaxDiaWithFins> - <MaxDiaWithoutFins>56.388</MaxDiaWithoutFins> - <MaxLenWithFins>717.499</MaxLenWithFins> - <MaxLenWithoutFins>717.499</MaxLenWithoutFins> - <MinXExtent>0.</MinXExtent> - <MaxXExtent>717.499</MaxXExtent> - <CalculatedMaxStageDia>0,56.388,0,0</CalculatedMaxStageDia> - <CalculatedStageLen>0,717.499,0,0</CalculatedStageLen> - <Cd3> - <PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> - <X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> - <A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> - <B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> - <C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> - </PolyData> - </Cd3> - <Cd32> - <PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> - <X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> - <A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> - <B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> - <C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> - </PolyData> - </Cd32> - <Cd321> - <PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> - <X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> - <A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> - <B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> - <C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> - </PolyData> -</Cd321> -<Cb3> - <PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> - <X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> - <A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> - <B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> - <C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb3> -<Cb32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb32> -<Cb321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb321> -<CNa3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa3> -<CNa32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa32> -<CNa321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa321> -<CP3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP3> -<CP32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP32> -<CP321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP321> -<SimulationEventList> -</SimulationEventList> -<Stage3Parts> -<NoseCone> -<PartMfg>Apogee</PartMfg> -<KnownMass>24.0999</KnownMass> -<Density>1049.21</Density> -<Material>Polystyrene PS</Material> -<Name>Nose cone</Name> -<KnownCG>65.3999</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>94.7384</CalcMass> -<CalcCG>208.434</CalcCG> -<WettedSurface>0.0323955</WettedSurface> -<PaintedSurface>0.0323955</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>19470</PartNo> -<PartDesc>PNC-70A</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>1</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>2.</BarrowmanCNa> -<BarrowmanXN>0.126958</BarrowmanXN> -<RockSimCNa>2.</RockSimCNa> -<RockSimXN>0.126958</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>0.</Station> -<Len>272.999</Len> -<BaseDia>56.2991</BaseDia> -<FinishCode>0</FinishCode> -<ShapeCode>1</ShapeCode> -<ConstructionType>1</ConstructionType> -<ShoulderLen>58.3997</ShoulderLen> -<WallThickness>2.159</WallThickness> -<ShapeParameter>0.</ShapeParameter> -<ShoulderOD>53.1012</ShoulderOD> -<BaseExtensionLen>0.</BaseExtensionLen> -<CoreDia>0.</CoreDia> -<CoreLen>0.</CoreLen> -<AttachedParts> -</AttachedParts> -</NoseCone> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>44.4492</CalcMass> -<CalcCG>222.25</CalcCG> -<WettedSurface>0.0787423</WettedSurface> -<PaintedSurface>0.0787423</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>Estes</PartNo> -<PartDesc>BT-70</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>2</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>272.999</Station> -<OD>56.388</OD> -<ID>55.372</ID> -<Len>444.5</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<FinSet> -<PartMfg>Public Missiles</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1905.24</Density> -<Material>G10 fiberglass</Material> -<Name>Fin set</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>273.05</Xb> -<CalcMass>75.5033</CalcMass> -<CalcCG>110.067</CalcCG> -<WettedSurface>0.0167742</WettedSurface> -<PaintedSurface>0.0503225</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>FIN-A-04</PartNo> -<PartDesc>Fins</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>4</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>16.5474</BarrowmanCNa> -<BarrowmanXN>0.628599</BarrowmanXN> -<RockSimCNa>23.7789</RockSimCNa> -<RockSimXN>0.628599</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>546.049</Station> -<FinCount>3</FinCount> -<RootChord>165.1</RootChord> -<TipChord>0.</TipChord> -<SemiSpan>101.6</SemiSpan> -<MidChordLen>130.909</MidChordLen> -<SweepDistance>165.1</SweepDistance> -<Thickness>1.5748</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>1</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>1.02001</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>62.0607</RockSimRadialXNPerFin> -<RockSimCNaPerFin>13.7288</RockSimCNaPerFin> -<TaperRatio>0.</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -<BodyTube> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>107.95</Xb> -<CalcMass>1.7435</CalcMass> -<CalcCG>55.5625</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>10062</PartNo> -<PartDesc>13 mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>5</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>380.949</Station> -<OD>13.8176</OD> -<ID>13.1572</ID> -<Len>111.125</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>13.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<FinSet> -<PartMfg>Public Missiles</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1905.24</Density> -<Material>G10 fiberglass</Material> -<Name>Fin set</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>5.53666</CalcMass> -<CalcCG>44.5707</CalcCG> -<WettedSurface>0.00365927</WettedSurface> -<PaintedSurface>0.00365927</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>FIN-A-06</PartNo> -<PartDesc>Fins</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>7</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.671866</BarrowmanCNa> -<BarrowmanXN>0.380349</BarrowmanXN> -<RockSimCNa>2.4888</RockSimCNa> -<RockSimXN>0.380349</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>349.199</Station> -<FinCount>1</FinCount> -<RootChord>66.675</RootChord> -<TipChord>38.1</TipChord> -<SemiSpan>34.925</SemiSpan> -<MidChordLen>42.7843</MidChordLen> -<SweepDistance>39.0017</SweepDistance> -<Thickness>1.5875</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>0</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.366519</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>44.069</RockSimRadialXNPerFin> -<RockSimCNaPerFin>2.87382</RockSimCNaPerFin> -<TaperRatio>0.571429</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -</AttachedParts> -</BodyTube> -<ExternalPod> -<PartMfg>Custom</PartMfg> -<KnownMass>0.</KnownMass> -<Density>0.</Density> -<Name>Pod</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>76.2</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>0.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>28.194</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>6</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>349.199</Station> -<Detachable>1</Detachable> -<AutoCalcRadialDistance>1</AutoCalcRadialDistance> -<AutoCalcRadialAngle>1</AutoCalcRadialAngle> -<AttachedParts> -<FinSet> -<PartMfg>Public Missiles</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1905.24</Density> -<Material>G10 fiberglass</Material> -<Name>Fin set</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>5.53666</CalcMass> -<CalcCG>44.5707</CalcCG> -<WettedSurface>0.00365927</WettedSurface> -<PaintedSurface>0.00365927</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>FIN-A-06</PartNo> -<PartDesc>Fins</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>7</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.671866</BarrowmanCNa> -<BarrowmanXN>0.380349</BarrowmanXN> -<RockSimCNa>2.4888</RockSimCNa> -<RockSimXN>0.380349</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>349.199</Station> -<FinCount>1</FinCount> -<RootChord>66.675</RootChord> -<TipChord>38.1</TipChord> -<SemiSpan>34.925</SemiSpan> -<MidChordLen>42.7843</MidChordLen> -<SweepDistance>39.0017</SweepDistance> -<Thickness>1.5875</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>0</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.366519</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>44.069</RockSimRadialXNPerFin> -<RockSimCNaPerFin>2.87382</RockSimCNaPerFin> -<TaperRatio>0.571429</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -</AttachedParts> -</ExternalPod> -</AttachedParts> -</BodyTube> -</Stage3Parts> -<Stage2Parts> -</Stage2Parts> -<Stage1Parts> -</Stage1Parts> -<SideViewDims> -</SideViewDims> -<BaseViewDims> -</BaseViewDims> -<VertViewDims> -</VertViewDims> -</RocketDesign> -</DesignInformation> -<SimulationResultsList> -</SimulationResultsList> -</RockSimDocument> diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/RingHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/RingHandlerTest.java deleted file mode 100644 index c63dbe70..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/RingHandlerTest.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * RingHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.rocketcomponent.RingComponent; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; - -/** - * RingHandler Tester. - */ -public class RingHandlerTest extends RocksimTestBase { - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new RingHandler(new BodyTube(), new WarningSet()).openElement(null, null, null)); - } - - /** - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testCloseElement() throws Exception { - - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - CenteringRing component = (CenteringRing) getField(handler, "ring"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "0", warnings); - Assert.assertEquals(0d, component.getOuterRadius(), 0.001); - handler.closeElement("OD", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getOuterRadius(), 0.001); - handler.closeElement("OD", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ID", attributes, "0", warnings); - Assert.assertEquals(0d, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "75", warnings); - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getInnerRadius(), 0.001); - handler.closeElement("ID", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - } - - /** - * Test a bulkhead. - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testBulkhead() throws Exception { - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - CenteringRing component = (CenteringRing) getField(handler, "ring"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "75", warnings); - handler.closeElement("ID", attributes, "0", warnings); - handler.closeElement("Len", attributes, "10", warnings); - handler.closeElement("Name", attributes, "Test Name", warnings); - handler.closeElement("KnownMass", attributes, "109.9", warnings); - handler.closeElement("UsageCode", attributes, "1", warnings); - handler.closeElement("UseKnownCG", attributes, "1", warnings); - handler.endHandler("", attributes, "", warnings); - - Assert.assertEquals(1, tube.getChildren().size()); - RingComponent child = (RingComponent)tube.getChild(0); - - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getOuterRadius(), 0.001); - Assert.assertEquals(0d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getInnerRadius(), 0.001); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, child.getLength(), 0.001); - Assert.assertEquals("Test Name", child.getName()); - Assert.assertEquals(109.9/1000, child.getMass(), 0.001); - Assert.assertEquals(0, child.getPositionValue(), 0.0); - Assert.assertEquals(RocketComponent.Position.TOP, child.getRelativePosition()); - Assert.assertTrue(child instanceof Bulkhead); - - } - - /** - * Test a tube coupler. - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testTubeCoupler() throws Exception { - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "75", warnings); - handler.closeElement("ID", attributes, "70", warnings); - handler.closeElement("Len", attributes, "10", warnings); - handler.closeElement("Name", attributes, "Test Name", warnings); - handler.closeElement("KnownMass", attributes, "109.9", warnings); - handler.closeElement("UsageCode", attributes, "4", warnings); - handler.closeElement("UseKnownCG", attributes, "1", warnings); - handler.endHandler("", attributes, "", warnings); - - Assert.assertEquals(1, tube.getChildren().size()); - RingComponent child = (RingComponent)tube.getChild(0); - Assert.assertTrue(child instanceof TubeCoupler); - - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getOuterRadius(), 0.001); - Assert.assertEquals(70d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getInnerRadius(), 0.001); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, child.getLength(), 0.001); - Assert.assertEquals("Test Name", child.getName()); - Assert.assertEquals(109.9/1000, child.getMass(), 0.001); - Assert.assertEquals(0, child.getPositionValue(), 0.0); - Assert.assertEquals(RocketComponent.Position.TOP, child.getRelativePosition()); - } - - /** - * Test a engine block. - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testEngineBlock() throws Exception { - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "75", warnings); - handler.closeElement("ID", attributes, "70", warnings); - handler.closeElement("Len", attributes, "10", warnings); - handler.closeElement("Name", attributes, "Test Name", warnings); - handler.closeElement("KnownMass", attributes, "109.9", warnings); - handler.closeElement("UsageCode", attributes, "2", warnings); - handler.closeElement("KnownCG", attributes, "4", warnings); - handler.closeElement("UseKnownCG", attributes, "1", warnings); - handler.endHandler("", attributes, "", warnings); - - Assert.assertEquals(1, tube.getChildren().size()); - RingComponent child = (RingComponent)tube.getChild(0); - Assert.assertTrue(child instanceof EngineBlock); - - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getOuterRadius(), 0.001); - Assert.assertEquals(70d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getInnerRadius(), 0.001); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, child.getLength(), 0.001); - Assert.assertEquals("Test Name", child.getName()); - Assert.assertEquals(109.9/1000, child.getMass(), 0.001); - Assert.assertEquals(0, child.getPositionValue(), 0.0); - Assert.assertEquals(RocketComponent.Position.TOP, child.getRelativePosition()); - Assert.assertEquals(4d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, child.getCG().x, 0.000001); - - } - - /** - * Test a centering ring - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testRing() throws Exception { - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("OD", attributes, "75", warnings); - handler.closeElement("ID", attributes, "0", warnings); - handler.closeElement("Len", attributes, "10", warnings); - handler.closeElement("Name", attributes, "Test Name", warnings); - handler.closeElement("KnownMass", attributes, "109.9", warnings); - handler.closeElement("UsageCode", attributes, "0", warnings); - handler.closeElement("UseKnownCG", attributes, "1", warnings); - handler.endHandler("", attributes, "", warnings); - - Assert.assertEquals(1, tube.getChildren().size()); - RingComponent child = (RingComponent)tube.getChild(0); - - Assert.assertEquals(75d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getOuterRadius(), 0.001); - Assert.assertEquals(0d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, child.getInnerRadius(), 0.001); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, child.getLength(), 0.001); - Assert.assertEquals("Test Name", child.getName()); - Assert.assertEquals(109.9/1000, child.getMass(), 0.001); - Assert.assertEquals(0, child.getPositionValue(), 0.0); - Assert.assertEquals(RocketComponent.Position.TOP, child.getRelativePosition()); - Assert.assertTrue(child instanceof CenteringRing); - } - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testConstructor() throws Exception { - - try { - new RingHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - CenteringRing component = (CenteringRing) getField(handler, "ring"); - } - - /** - * Method: setRelativePosition(RocketComponent.Position position) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testSetRelativePosition() throws Exception { - BodyTube tube = new BodyTube(); - RingHandler handler = new RingHandler(tube, new WarningSet()); - CenteringRing component = (CenteringRing) getField(handler, "ring"); - handler.setRelativePosition(RocketComponent.Position.ABSOLUTE); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - } - - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new RingHandler(new BodyTube(), new WarningSet()).getComponent() instanceof CenteringRing); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.BULK, new RingHandler(new BodyTube(), new WarningSet()).getMaterialType()); - } - - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/RocksimContentHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/RocksimContentHandlerTest.java deleted file mode 100644 index 0eb1d625..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/RocksimContentHandlerTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * RocksimContentHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import org.junit.Assert; - -/** - * RocksimContentHandler Tester. - * - */ -public class RocksimContentHandlerTest { - - /** - * - * Method: getDocument() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetDocument() throws Exception { - RocksimContentHandler handler = new RocksimContentHandler(); - Assert.assertNotNull(handler.getDocument()); - } - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/RocksimLoaderTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/RocksimLoaderTest.java deleted file mode 100644 index 48ea77af..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/RocksimLoaderTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * RocksimLoaderTest.java - * - */ -package net.sf.openrocket.file.rocksim.importt; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.DatabaseMotorFinder; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.Stage; - -import org.junit.Assert; - -/** - * RocksimLoader Tester. - */ -public class RocksimLoaderTest { - - /** - * Test a bug reported via automated bug report. I have been unable to reproduce this bug - * (hanging finset off of an inner body tube) when creating a Rocksim file using Rocksim. The bug - * is reproducible when manually modifying the Rocksim file, which is what is tested here. - */ - @org.junit.Test - public void testFinsOnInnerTube() throws Exception { - RocksimLoader loader = new RocksimLoader(); - InputStream stream = this.getClass().getResourceAsStream("PodFins.rkt"); - Assert.assertNotNull("Could not open PodFins.rkt", stream); - try { - OpenRocketDocument doc = loader.loadFromStream(new BufferedInputStream(stream), new DatabaseMotorFinder()); - Assert.assertNotNull(doc); - Rocket rocket = doc.getRocket(); - Assert.assertNotNull(rocket); - } catch (IllegalStateException ise) { - Assert.fail(ise.getMessage()); - } - Assert.assertTrue(loader.getWarnings().size() == 2); - } - - /** - * Method: loadFromStream(InputStream source) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testLoadFromStream() throws Exception { - RocksimLoader loader = new RocksimLoader(); - //Stupid single stage rocket - OpenRocketDocument doc = loadRocksimRocket(loader); - InputStream stream; - - Assert.assertNotNull(doc); - Rocket rocket = doc.getRocket(); - Assert.assertNotNull(rocket); - Assert.assertEquals("FooBar Test", doc.getRocket().getName()); - Assert.assertTrue(loader.getWarnings().isEmpty()); - - stream = this.getClass().getResourceAsStream("rocksimTestRocket2.rkt"); - Assert.assertNotNull("Could not open rocksimTestRocket2.rkt", stream); - doc = loader.loadFromStream(new BufferedInputStream(stream), new DatabaseMotorFinder()); - - Assert.assertNotNull(doc); - rocket = doc.getRocket(); - Assert.assertNotNull(rocket); - - //Do some simple asserts; the important thing here is just validating that the mass and cg were - //not overridden for each stage. - Assert.assertEquals("Three Stage Everything Included Rocket", doc.getRocket().getName()); - Assert.assertEquals(1, loader.getWarnings().size()); - Assert.assertEquals(3, rocket.getStageCount()); - Stage stage1 = (Stage) rocket.getChild(0); - Assert.assertFalse(stage1.isMassOverridden()); - Assert.assertFalse(stage1.isCGOverridden()); - Stage stage2 = (Stage) rocket.getChild(1); - Assert.assertFalse(stage2.isMassOverridden()); - Assert.assertFalse(stage2.isCGOverridden()); - Stage stage3 = (Stage) rocket.getChild(2); - Assert.assertFalse(stage3.isMassOverridden()); - Assert.assertFalse(stage3.isCGOverridden()); - - stream = this.getClass().getResourceAsStream("rocksimTestRocket3.rkt"); - Assert.assertNotNull("Could not open rocksimTestRocket3.rkt", stream); - doc = loader.loadFromStream(new BufferedInputStream(stream), new DatabaseMotorFinder()); - - Assert.assertNotNull(doc); - rocket = doc.getRocket(); - Assert.assertNotNull(rocket); - Assert.assertEquals("Three Stage Everything Included Rocket - Override Total Mass/CG", doc.getRocket().getName()); - Assert.assertEquals(3, rocket.getStageCount()); - stage1 = (Stage) rocket.getChild(0); - stage2 = (Stage) rocket.getChild(1); - stage3 = (Stage) rocket.getChild(2); - - //Do some 1st level and simple asserts; the idea here is to not do a deep validation as that - //should have been covered elsewhere. Assert that the stage overrides are correct. - Assert.assertEquals(2, stage1.getChildCount()); - Assert.assertEquals("Nose cone", stage1.getChild(0).getName()); - Assert.assertEquals("Body tube", stage1.getChild(1).getName()); - Assert.assertTrue(stage1.isMassOverridden()); - Assert.assertEquals(0.185d, stage1.getOverrideMass(), 0.001); - Assert.assertTrue(stage1.isCGOverridden()); - Assert.assertEquals(0.3d, stage1.getOverrideCG().x, 0.001); - Assert.assertEquals(4, loader.getWarnings().size()); - - Assert.assertEquals(1, stage2.getChildCount()); - Assert.assertEquals("2nd Stage Tube", stage2.getChild(0).getName()); - Assert.assertTrue(stage2.isMassOverridden()); - Assert.assertEquals(0.21d, stage2.getOverrideMass(), 0.001); - Assert.assertTrue(stage2.isCGOverridden()); - Assert.assertEquals(0.4d, stage2.getOverrideCG().x, 0.001); - - BodyTube bt = (BodyTube) stage2.getChild(0); - LaunchLug ll = (LaunchLug) bt.getChild(6); - Assert.assertEquals(1.22d, ll.getRadialDirection(), 0.001); - - Assert.assertEquals(2, stage3.getChildCount()); - Assert.assertEquals("Transition", stage3.getChild(0).getName()); - Assert.assertEquals("Body tube", stage3.getChild(1).getName()); - Assert.assertTrue(stage2.isMassOverridden()); - Assert.assertEquals(0.33d, stage3.getOverrideMass(), 0.001); - Assert.assertTrue(stage2.isCGOverridden()); - Assert.assertEquals(0.5d, stage3.getOverrideCG().x, 0.001); - } - - public static OpenRocketDocument loadRocksimRocket(RocksimLoader theLoader) throws IOException, RocketLoadException { - InputStream stream = RocksimLoaderTest.class.getResourceAsStream("rocksimTestRocket1.rkt"); - try { - Assert.assertNotNull("Could not open rocksimTestRocket1.rkt", stream); - return theLoader.loadFromStream(new BufferedInputStream(stream), new DatabaseMotorFinder()); - } finally { - stream.close(); - } - } - - public static OpenRocketDocument loadRocksimRocket3(RocksimLoader theLoader) throws IOException, RocketLoadException { - InputStream stream = RocksimLoaderTest.class.getResourceAsStream("rocksimTestRocket3.rkt"); - try { - Assert.assertNotNull("Could not open rocksimTestRocket3.rkt", stream); - return theLoader.loadFromStream(new BufferedInputStream(stream), new DatabaseMotorFinder()); - } finally { - stream.close(); - } - } - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/RocksimTestBase.java b/core/test/net/sf/openrocket/file/rocksim/importt/RocksimTestBase.java deleted file mode 100644 index 14b2494d..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/RocksimTestBase.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * BaseRocksimTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.startup.Application; -import org.junit.Assert; -import org.junit.Before; - -import java.lang.reflect.Field; -import java.util.List; - -/** - * A base class for the Rocksim tests. Includes code from the junitx.addons project. - */ -public abstract class RocksimTestBase { - - /* (non-Javadoc) - * @see junit.framework.TestCase#setUp() - */ - @Before - public void setUp() throws Exception { - Application.setPreferences( new SwingPreferences() ); - } - - - public void assertContains(RocketComponent child, List<RocketComponent> components) { - Assert.assertTrue("Components did not contain child", components.contains(child)); - } - - /** - * Returns the value of the field on the specified object. The name - * parameter is a <code>String</code> specifying the simple name of the - * desired field.<p> - * - * The object is first searched for any matching field. If no matching - * field is found, the superclasses are recursively searched. - * - * @exception NoSuchFieldException if a field with the specified name is - * not found. - */ - public static Object getField(Object object, - String name) - throws NoSuchFieldException { - if (object == null) { - throw new IllegalArgumentException("Invalid null object argument"); - } - for (Class cls = object.getClass(); cls != null; cls = cls.getSuperclass()) { - try { - Field field = cls.getDeclaredField(name); - field.setAccessible(true); - return field.get(object); - } catch (Exception ex) { - /* in case of an exception, we will throw a new - * NoSuchFieldException object */ - ; - } - } - throw new NoSuchFieldException("Could get value for field " + - object.getClass().getName() + "." + name); - } - - /** - * Returns the value of the field on the specified class. The name - * parameter is a <code>String</code> specifying the simple name of the - * desired field.<p> - * - * The class is first searched for any matching field. If no matching - * field is found, the superclasses are recursively searched. - * - * @exception NoSuchFieldException if a field with the specified name is - * not found. - */ - public static Object getField(Class cls, - String name) - throws NoSuchFieldException { - if (cls == null) { - throw new IllegalArgumentException("Invalid null cls argument"); - } - Class base = cls; - while (base != null) { - try { - Field field = base.getDeclaredField(name); - field.setAccessible(true); - return field.get(base); - } catch (Exception ex) { - /* in case of an exception, we will throw a new - * NoSuchFieldException object */ - ; - } - base = base.getSuperclass(); - } - throw new NoSuchFieldException("Could get value for static field " + - cls.getName() + "." + name); - } - - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/StreamerHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/StreamerHandlerTest.java deleted file mode 100644 index fe2b9c9c..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/StreamerHandlerTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * StreamerHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimDensityType; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.Streamer; -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; - -/** - * StreamerHandler Tester. - */ -public class StreamerHandlerTest extends RocksimTestBase { - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new StreamerHandler(new BodyTube(), new WarningSet()).openElement(null, null, null)); - } - - /** - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testCloseElement() throws Exception { - - BodyTube tube = new BodyTube(); - StreamerHandler handler = new StreamerHandler(tube, new WarningSet()); - Streamer component = (Streamer) getField(handler, "streamer"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("Width", attributes, "0", warnings); - Assert.assertEquals(0d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getStripWidth(), 0.001); - handler.closeElement("Width", attributes, "10", warnings); - Assert.assertEquals(10d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getStripWidth(), 0.001); - handler.closeElement("Width", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getStripLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getStripLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getStripLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - - handler.closeElement("DragCoefficient", attributes, "0.94", warnings); - Assert.assertEquals(0.94d, component.getCD(), 0.001); - handler.closeElement("DragCoefficient", attributes, "-0.94", warnings); - Assert.assertEquals(-0.94d, component.getCD(), 0.001); - handler.closeElement("DragCoefficient", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - } - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testConstructor() throws Exception { - - try { - new StreamerHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - BodyTube tube = new BodyTube(); - StreamerHandler handler = new StreamerHandler(tube, new WarningSet()); - Streamer component = (Streamer) getField(handler, "streamer"); - assertContains(component, tube.getChildren()); - } - - /** - * Method: setRelativePosition(RocketComponent.Position position) - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testSetRelativePosition() throws Exception { - BodyTube tube = new BodyTube(); - StreamerHandler handler = new StreamerHandler(tube, new WarningSet()); - Streamer component = (Streamer) getField(handler, "streamer"); - handler.setRelativePosition(RocketComponent.Position.ABSOLUTE); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new StreamerHandler(new BodyTube(), new WarningSet()).getComponent() instanceof Streamer); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.SURFACE, new StreamerHandler(new BodyTube(), new WarningSet()).getMaterialType()); - } - - /** - * Method: endHandler() - * - * @throws Exception thrown if something goes awry - */ - @Test - public void testEndHandler() throws Exception { - BodyTube tube = new BodyTube(); - StreamerHandler handler = new StreamerHandler(tube, new WarningSet()); - Streamer component = (Streamer) getField(handler, "streamer"); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - handler.closeElement("Xb", attributes, "-10", warnings); - handler.closeElement("LocationMode", attributes, "1", warnings); - handler.endHandler("Streamer", attributes, null, warnings); - Assert.assertEquals(RocketComponent.Position.ABSOLUTE, component.getRelativePosition()); - Assert.assertEquals(component.getPositionValue(), -10d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, 0.001); - - handler.closeElement("Xb", attributes, "-10", warnings); - handler.closeElement("LocationMode", attributes, "2", warnings); - handler.endHandler("Streamer", attributes, null, warnings); - Assert.assertEquals(RocketComponent.Position.BOTTOM, component.getRelativePosition()); - Assert.assertEquals(component.getPositionValue(), 10d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, 0.001); - - handler.closeElement("Thickness", attributes, "0.02", warnings); - Assert.assertEquals(0.01848, handler.computeDensity(RocksimDensityType.ROCKSIM_BULK, 924d), 0.001); - - //Test Density Type 0 (Bulk) - handler.closeElement("Density", attributes, "924.0", warnings); - handler.closeElement("DensityType", attributes, "0", warnings); - handler.endHandler("Streamer", attributes, null, warnings); - Assert.assertEquals(0.01848d, component.getMaterial().getDensity(), 0.001); - - //Test Density Type 1 (Surface) - handler.closeElement("Density", attributes, "0.006685", warnings); - handler.closeElement("DensityType", attributes, "1", warnings); - handler.endHandler("Streamer", attributes, null, warnings); - Assert.assertTrue(Math.abs(0.06685d - component.getMaterial().getDensity()) < 0.00001); - - //Test Density Type 2 (Line) - handler.closeElement("Density", attributes, "0.223225", warnings); - handler.closeElement("DensityType", attributes, "2", warnings); - handler.closeElement("Len", attributes, "3810.", warnings); - handler.closeElement("Width", attributes, "203.2", warnings); - handler.endHandler("Streamer", attributes, null, warnings); - - Assert.assertEquals(1.728190092, component.getMass(), 0.001); - - } - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/TransitionHandlerTest.java b/core/test/net/sf/openrocket/file/rocksim/importt/TransitionHandlerTest.java deleted file mode 100644 index 28087d17..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/TransitionHandlerTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * TransitionHandlerTest.java - */ -package net.sf.openrocket.file.rocksim.importt; - -import net.sf.openrocket.aerodynamics.WarningSet; -import net.sf.openrocket.file.rocksim.RocksimCommonConstants; -import net.sf.openrocket.file.rocksim.RocksimNoseConeCode; -import net.sf.openrocket.file.simplesax.PlainTextHandler; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.rocketcomponent.ExternalComponent; -import net.sf.openrocket.rocketcomponent.Stage; -import net.sf.openrocket.rocketcomponent.Transition; -import org.junit.Assert; - -import java.util.HashMap; - -/** - * TransitionHandler Tester. - */ -public class TransitionHandlerTest extends RocksimTestBase { - - /** - * Method: constructor - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testConstructor() throws Exception { - - try { - new TransitionHandler(null, new WarningSet()); - Assert.fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException iae) { - //success - } - - Stage stage = new Stage(); - TransitionHandler handler = new TransitionHandler(stage, new WarningSet()); - Transition component = (Transition) getField(handler, "transition"); - assertContains(component, stage.getChildren()); - } - - /** - * Method: openElement(String element, HashMap<String, String> attributes, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testOpenElement() throws Exception { - Assert.assertEquals(PlainTextHandler.INSTANCE, new TransitionHandler(new Stage(), new WarningSet()).openElement(null, null, null)); - } - - /** - * Method: closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings) - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testCloseElement() throws Exception { - - Stage stage = new Stage(); - HashMap<String, String> attributes = new HashMap<String, String>(); - WarningSet warnings = new WarningSet(); - - TransitionHandler handler = new TransitionHandler(stage, new WarningSet()); - Transition component = (Transition) getField(handler, "transition"); - - handler.closeElement("ShapeCode", attributes, "0", warnings); - Assert.assertEquals(Transition.Shape.CONICAL, component.getType()); - handler.closeElement("ShapeCode", attributes, "1", warnings); - Assert.assertEquals(Transition.Shape.OGIVE, component.getType()); - handler.closeElement("ShapeCode", attributes, "17", warnings); - Assert.assertEquals(RocksimNoseConeCode.PARABOLIC.asOpenRocket(), component.getType()); //test of default - handler.closeElement("ShapeCode", attributes, "foo", warnings); - Assert.assertNotNull(component.getType()); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Len", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getLength(), 0.001); - handler.closeElement("Len", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("FrontDia", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getForeRadius(), 0.001); - handler.closeElement("FrontDia", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getForeRadius(), 0.001); - handler.closeElement("FrontDia", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("RearDia", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getAftRadius(), 0.001); - handler.closeElement("RearDia", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getAftRadius(), 0.001); - handler.closeElement("RearDia", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - final double aft = 100d; - component.setAftRadius(aft); - - handler.closeElement("ConstructionType", attributes, "0", warnings); - component.setAftShoulderRadius(1.1d); - component.setForeShoulderRadius(1.1d); - handler.closeElement("WallThickness", attributes, "-1", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(component.getAftRadius(), component.getThickness(), 0.001); - Assert.assertEquals(component.getAftShoulderThickness(), component.getAftShoulderThickness(), 0.001); - Assert.assertEquals(component.getForeShoulderThickness(), component.getForeShoulderThickness(), 0.001); - handler.closeElement("WallThickness", attributes, "100", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(aft, component.getThickness(), 0.001); - handler.closeElement("WallThickness", attributes, "foo", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("ConstructionType", attributes, "1", warnings); - component.setAftShoulderRadius(1.1d); - component.setForeShoulderRadius(1.1d); - handler.closeElement("WallThickness", attributes, "-1", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(0d, component.getThickness(), 0.001); - Assert.assertEquals(0d, component.getAftShoulderThickness(), 0.001); - Assert.assertEquals(0d, component.getForeShoulderThickness(), 0.001); - handler.closeElement("WallThickness", attributes, "1.1", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertEquals(1.1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getThickness(), 0.001); - Assert.assertEquals(1.1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getAftShoulderThickness(), 0.001); - Assert.assertEquals(1.1d/ RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getForeShoulderThickness(), 0.001); - - - handler.closeElement("FrontShoulderLen", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getForeShoulderLength(), 0.001); - handler.closeElement("FrontShoulderLen", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getForeShoulderLength(), 0.001); - handler.closeElement("FrontShoulderLen", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getForeShoulderLength(), 0.001); - handler.closeElement("FrontShoulderLen", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("RearShoulderLen", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getAftShoulderLength(), 0.001); - handler.closeElement("RearShoulderLen", attributes, "10", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getAftShoulderLength(), 0.001); - handler.closeElement("RearShoulderLen", attributes, "10.0", warnings); - Assert.assertEquals(10d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_LENGTH, component.getAftShoulderLength(), 0.001); - handler.closeElement("RearShoulderLen", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("FrontShoulderDia", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getForeShoulderRadius(), 0.001); - handler.closeElement("FrontShoulderDia", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getForeShoulderRadius(), 0.001); - handler.closeElement("FrontShoulderDia", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("RearShoulderDia", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getAftShoulderRadius(), 0.001); - handler.closeElement("RearShoulderDia", attributes, "100", warnings); - Assert.assertEquals(100d / RocksimCommonConstants.ROCKSIM_TO_OPENROCKET_RADIUS, component.getAftShoulderRadius(), 0.001); - handler.closeElement("RearShoulderDia", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - component.setType(Transition.Shape.HAACK); - handler.closeElement("ShapeParameter", attributes, "-1", warnings); - Assert.assertEquals(0d, component.getShapeParameter(), 0.001); - handler.closeElement("ShapeParameter", attributes, "100", warnings); - Assert.assertEquals(Transition.Shape.HAACK.maxParameter(), component.getShapeParameter(), 0.001); - handler.closeElement("ShapeParameter", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - Assert.assertEquals("Could not convert ShapeParameter value of foo. It is expected to be a number.", - warnings.iterator().next().toString()); - - warnings.clear(); - - component.setType(Transition.Shape.CONICAL); - component.setShapeParameter(0d); - handler.closeElement("ShapeParameter", attributes, "100", warnings); - Assert.assertEquals(0d, component.getShapeParameter(), 0.001); - - handler.closeElement("FinishCode", attributes, "-1", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "100", warnings); - Assert.assertEquals(ExternalComponent.Finish.NORMAL, component.getFinish()); - handler.closeElement("FinishCode", attributes, "foo", warnings); - Assert.assertEquals(1, warnings.size()); - warnings.clear(); - - handler.closeElement("Name", attributes, "Test Name", warnings); - Assert.assertEquals("Test Name", component.getName()); - - handler.closeElement("Material", attributes, "Some Material", warnings); - handler.endHandler("Transition", attributes, null, warnings); - Assert.assertTrue(component.getMaterial().getName().contains("Some Material")); - } - - /** - * Method: getComponent() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetComponent() throws Exception { - Assert.assertTrue(new TransitionHandler(new Stage(), new WarningSet()).getComponent() instanceof Transition); - } - - /** - * Method: getMaterialType() - * - * @throws Exception thrown if something goes awry - */ - @org.junit.Test - public void testGetMaterialType() throws Exception { - Assert.assertEquals(Material.Type.BULK, new TransitionHandler(new Stage(), new WarningSet()).getMaterialType()); - } - - -} diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket1.rkt b/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket1.rkt deleted file mode 100644 index 79f7b003..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket1.rkt +++ /dev/null @@ -1,743 +0,0 @@ -<RockSimDocument> -<FileVersion>3</FileVersion> -<DesignInformation> -<RocketDesign> - <Name>FooBar Test</Name> -<CalculateCD>1</CalculateCD> -<ProCalculateCD>1</ProCalculateCD> -<ProCalculateCN>1</ProCalculateCN> -<FixedCd>0.75</FixedCd> -<FixedCd2>0.8</FixedCd2> -<FixedCd3>0.81</FixedCd3> -<FixedCd2Alone>0.95</FixedCd2Alone> -<FixedCd3Alone>0.95</FixedCd3Alone> -<StageCount>1</StageCount> -<Stage3Mass>0.</Stage3Mass> -<Stage2Mass>0.</Stage2Mass> -<Stage1Mass>0.</Stage1Mass> -<Stage321CG>0.</Stage321CG> -<Stage32CG>0.</Stage32CG> -<Stage3CG>0.</Stage3CG> -<Stage2CGAlone>0.</Stage2CGAlone> -<Stage1CGAlone>0.</Stage1CGAlone> -<CPCalcFlags>1</CPCalcFlags> -<LaunchGuideLength>914.4</LaunchGuideLength> -<UseKnownMass>0</UseKnownMass> -<DefaultFinish>0</DefaultFinish> -<FinishMedium>0</FinishMedium> -<FinishCoatCount>1</FinishCoatCount> -<GlueType>0</GlueType> -<CPSimFlags>1</CPSimFlags> -<LastSerialNumber>11</LastSerialNumber> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<BarromanXN>0,1215.49,0,0</BarromanXN> -<BarrowmanCNa>0,35.9506,0,0</BarrowmanCNa> -<RockSimXN>0,1226.38,0,0</RockSimXN> -<RockSimCNa>0,47.5027,0,0</RockSimCNa> -<RockSimCNa90>0,0,0,0</RockSimCNa90> -<RockSimXN90>0,0,0,0</RockSimXN90> -<ViewType>0</ViewType> -<ViewStageCount>1</ViewStageCount> -<ViewTypeEdit>0</ViewTypeEdit> -<ViewStageCountEdit>1</ViewStageCountEdit> -<ZoomFactor>0.</ZoomFactor> -<ZoomFactorEdit>0.</ZoomFactorEdit> -<ScrollPosX>0</ScrollPosX> -<ScrollPosY>0</ScrollPosY> -<ScrollPosXEdit>0</ScrollPosXEdit> -<ScrollPosYEdit>0</ScrollPosYEdit> -<ThreeDFlags>0</ThreeDFlags> -<ThreeDFlagsEdit>0</ThreeDFlagsEdit> -<UseModelSprite>0</UseModelSprite> -<StaticMarginRef>0</StaticMarginRef> -<UserRefDiameter>0.</UserRefDiameter> -<SideMarkerHeight>10.</SideMarkerHeight> -<SideDimensionHeight>10.</SideDimensionHeight> -<BaseMarkerHeight>10.</BaseMarkerHeight> -<BaseDimensionHeight>10.</BaseDimensionHeight> -<ShowGlideCP>0</ShowGlideCP> -<ShowGridTypeSide>0</ShowGridTypeSide> -<ShowGridTypeBase>0</ShowGridTypeBase> -<GridSpacing>10.</GridSpacing> -<GridOpacity>0.15</GridOpacity> -<GridColor>black</GridColor> -<MaxDiaWithFins>424.688</MaxDiaWithFins> -<MaxDiaWithoutFins>66.04</MaxDiaWithoutFins> -<MaxLenWithFins>1417.95</MaxLenWithFins> -<MaxLenWithoutFins>1332.23</MaxLenWithoutFins> -<MinXExtent>0.</MinXExtent> -<MaxXExtent>1417.95</MaxXExtent> -<CalculatedMaxStageDia>0,66.04,0,0</CalculatedMaxStageDia> -<CalculatedStageLen>0,1332.23,0,0</CalculatedStageLen> -<Cd3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd3> -<Cd32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd32> -<Cd321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd321> -<Cb3> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb3> -<Cb32> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb32> -<Cb321> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb321> -<CNa3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa3> -<CNa32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa32> -<CNa321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa321> -<CP3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP3> -<CP32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP32> -<CP321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP321> -<SimulationEventList> -</SimulationEventList> -<Stage3Parts> -<NoseCone> -<PartMfg>Apogee</PartMfg> -<KnownMass>24.1</KnownMass> -<Density>1049.21</Density> -<Material>Polystyrene PS</Material> -<Name>Nose cone</Name> -<KnownCG>65.3999</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>126.438</CalcMass> -<CalcCG>348.443</CalcCG> -<WettedSurface>0.0356487</WettedSurface> -<PaintedSurface>0.0356487</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>19470</PartNo> -<PartDesc>PNC-70A</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>2</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>2.</BarrowmanCNa> -<BarrowmanXN>0.264319</BarrowmanXN> -<RockSimCNa>2.</RockSimCNa> -<RockSimXN>0.264319</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>0.</Station> -<Len>396.875</Len> -<BaseDia>57.15</BaseDia> -<FinishCode>0</FinishCode> -<ShapeCode>0</ShapeCode> -<ConstructionType>1</ConstructionType> -<ShoulderLen>58.3997</ShoulderLen> -<WallThickness>2.159</WallThickness> -<ShapeParameter>0.</ShapeParameter> -<ShoulderOD>53.1012</ShoulderOD> -<BaseExtensionLen>66.675</BaseExtensionLen> -<CoreDia>0.</CoreDia> -<CoreLen>0.</CoreLen> -<AttachedParts> -</AttachedParts> -</NoseCone> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>10.636</CalcMass> -<CalcCG>180.34</CalcCG> -<WettedSurface>0.0748306</WettedSurface> -<PaintedSurface>0.0748306</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3090</PartNo> -<PartDesc>BT-80</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>3</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>463.55</Station> -<OD>66.04</OD> -<ID>65.786</ID> -<Len>360.68</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -<Transition> -<PartMfg>BalsaMachining.com</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Transition</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>39.355</CalcMass> -<CalcCG>37.0332</CalcCG> -<WettedSurface>0.0096001</WettedSurface> -<PaintedSurface>0.0096001</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TA7080</PartNo> -<PartDesc>Transition T70 to T80 2 in long</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>7</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>-0.92852</BarrowmanCNa> -<BarrowmanXN>0.848729</BarrowmanXN> -<RockSimCNa>-0.92852</RockSimCNa> -<RockSimXN>0.848729</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>824.23</Station> -<FrontDia>66.04</FrontDia> -<RearDia>53.34</RearDia> -<Len>50.8</Len> -<FinishCode>0</FinishCode> -<FrontShoulderLen>35.56</FrontShoulderLen> -<RearShoulderLen>35.56</RearShoulderLen> -<ConstructionType>0</ConstructionType> -<WallThickness>0.</WallThickness> -<FrontShoulderDia>55.118</FrontShoulderDia> -<RearShoulderDia>53.34</RearShoulderDia> -<CoreDia>0.</CoreDia> -<ShapeCode>0</ShapeCode> -<ShapeParameter>0.</ShapeParameter> -<EquivNoseLen>264.12</EquivNoseLen> -<EquivNoseOffset>213.32</EquivNoseOffset> -<AttachedParts> -</AttachedParts> -</Transition> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>44.449</CalcMass> -<CalcCG>222.25</CalcCG> -<WettedSurface>0.0787423</WettedSurface> -<PaintedSurface>0.0787423</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>Estes</PartNo> -<PartDesc>BT-70</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>8</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>875.03</Station> -<OD>56.388</OD> -<ID>55.372</ID> -<Len>444.5</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<FinSet> -<PartMfg>Public Missiles</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1905.24</Density> -<Material>G10 fiberglass</Material> -<Name>Fin set</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>260.35</Xb> -<CalcMass>153.85</CalcMass> -<CalcCG>155.575</CalcCG> -<WettedSurface>0.0339112</WettedSurface> -<PaintedSurface>0.101734</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>FIN-A-01</PartNo> -<PartDesc>Fins</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>9</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>34.8792</BarrowmanCNa> -<BarrowmanXN>1.26026</BarrowmanXN> -<RockSimCNa>46.4312</RockSimCNa> -<RockSimXN>1.26026</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>1135.38</Station> -<FinCount>3</FinCount> -<RootChord>184.15</RootChord> -<TipChord>0.</TipChord> -<SemiSpan>184.15</SemiSpan> -<MidChordLen>264.956</MidChordLen> -<SweepDistance>282.575</SweepDistance> -<Thickness>1.5875</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>0</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.990003</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>89.5773</RockSimRadialXNPerFin> -<RockSimCNaPerFin>26.8071</RockSimCNaPerFin> -<TaperRatio>0.</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>13.008</CalcMass> -<CalcCG>228.6</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3086</PartNo> -<PartDesc>BT-50</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>11</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>875.03</Station> -<OD>24.7904</OD> -<ID>24.13</ID> -<Len>457.2</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>24.</MotorDia> -<EngineOverhang>12.7</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -</AttachedParts> -</BodyTube> -</Stage3Parts> -<Stage2Parts> -</Stage2Parts> -<Stage1Parts> -</Stage1Parts> -<SideViewDims> -</SideViewDims> -<BaseViewDims> -</BaseViewDims> -<VertViewDims> -</VertViewDims> -</RocketDesign> -</DesignInformation> -<SimulationResultsList> -<SimulationResults> -<MaxAltitude>445.129</MaxAltitude> -<MaxVelocity>68.7587</MaxVelocity> -<MaxAcceleration>76.6476</MaxAcceleration> -<TimeToApogee>10.8263</TimeToApogee> -<OptimalDelay>4.765</OptimalDelay> -<MultiDelayCount>1</MultiDelayCount> -<VelocityAtDeplyment>33.4284</VelocityAtDeplyment> -<AltitudeAtDeployment>405.535</AltitudeAtDeployment> -<DelayTime>2</DelayTime> -<EjectTime>8.06125</EjectTime> -<FinalState>4</FinalState> -<TimeToBurnout>6.06125</TimeToBurnout> -<TimeToLanding>22.4787</TimeToLanding> -<TimeToEject>8.06125</TimeToEject> -<MinLaunchGuideLen>1.35915</MinLaunchGuideLen> -<MaxVertVelocity>65.9349</MaxVertVelocity> -<MaxHorzVelocity>1.0686</MaxHorzVelocity> -<MaxVertAcceleration>76.5426</MaxVertAcceleration> -<MaxHorzAcceleration>4.01173</MaxHorzAcceleration> -<MaxRange>172.076</MaxRange> -<LaunchStartVelocity>0.</LaunchStartVelocity> -<LaunchStartRollRate>0.</LaunchStartRollRate> -<LaunchGuideType>0</LaunchGuideType> -<LaunchGuideLen>1828.8</LaunchGuideLen> -<LaunchWindDirection>0</LaunchWindDirection> -<LaunchWindSpeed>0.</LaunchWindSpeed> -<LaunchDirection>0</LaunchDirection> -<LaunchAngle>0.0523599</LaunchAngle> -<LaunchGuideAzimuth>0.</LaunchGuideAzimuth> -<LaunchGuideElevation>0.</LaunchGuideElevation> -<LaunchBarometer>770.314</LaunchBarometer> -<LaunchLatitude>43.</LaunchLatitude> -<LaunchLongitude>0.</LaunchLongitude> -<LaunchHumidity>70.</LaunchHumidity> -<LaunchTemperature>7.22222</LaunchTemperature> -<LaunchAltitude>304.8</LaunchAltitude> -<LaunchLandingAltitude>0.</LaunchLandingAltitude> -<CompStateMask>0</CompStateMask> -<LaunchWindPreset>3</LaunchWindPreset> -<LaunchWindLowSpeed>1.34112</LaunchWindLowSpeed> -<LaunchWindHighSpeed>3.53162</LaunchWindHighSpeed> -<LaunchWindTurbulencePreset>2</LaunchWindTurbulencePreset> -<LaunchWindFrequency>0.01</LaunchWindFrequency> -<LaunchWindDeltaFrequency>0.02</LaunchWindDeltaFrequency> -<LaunchUseRandomConditions>0</LaunchUseRandomConditions> -<LaunchCloudCoverPreset>5</LaunchCloudCoverPreset> -<LaunchCCLow>0.</LaunchCCLow> -<LaunchCCHigh>0.1</LaunchCCHigh> -<LaunchThermalPosPreset>1</LaunchThermalPosPreset> -<LaunchThermalPos>0.</LaunchThermalPos> -<LaunchMultipleThermals>0</LaunchMultipleThermals> -<LaunchMaxThermals>3</LaunchMaxThermals> -<LaunchThermalDia>300.</LaunchThermalDia> -<LaunchThermalHeight>2000.</LaunchThermalHeight> -<LaunchThermalSpeedPreset>1</LaunchThermalSpeedPreset> -<LaunchThermalSpeed>5.99999</LaunchThermalSpeed> -<LaunchWindTableSize>0</LaunchWindTableSize> -<LaunchWindAltTable>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</LaunchWindAltTable> -<LaunchWindSpeedTable>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</LaunchWindSpeedTable> -<LaunchWindDirectionTable>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</LaunchWindDirectionTable> -<LaunchLossPreset>2</LaunchLossPreset> -<LaunchLossPercent>0.99</LaunchLossPercent> -<LaunchSiteDia>2000.</LaunchSiteDia> -<LaunchDriftRangeToLoss>1500.</LaunchDriftRangeToLoss> -<LaunchPayloadDamagePreset>2</LaunchPayloadDamagePreset> -<LaunchPayloadDamagePercent>0.98</LaunchPayloadDamagePercent> -<LaunchEngineMisfirePreset>1</LaunchEngineMisfirePreset> -<LaunchEngineMisfirePercent>0.</LaunchEngineMisfirePercent> -<LaunchVariableIgnitionDelay>0</LaunchVariableIgnitionDelay> -<LaunchVariableIgnitionDelaySec>0.08</LaunchVariableIgnitionDelaySec> -<LaunchRecDeviceFailurePreset>1</LaunchRecDeviceFailurePreset> -<LaunchRecDeviceFailurePercent>0.</LaunchRecDeviceFailurePercent> -<LaunchAriframeFailurePreset>1</LaunchAriframeFailurePreset> -<LaunchAirframeFailurePercent>0.</LaunchAirframeFailurePercent> -<LaunchTrackLossPreset>1</LaunchTrackLossPreset> -<LaunchTeckLossPercent>0.</LaunchTeckLossPercent> -<CNaMultiplier>1.</CNaMultiplier> -<CdMultiplier>1.</CdMultiplier> -<CPOffset>0.</CPOffset> -<SaveSimAsText>0</SaveSimAsText> -<OutputAtMaxRes>0</OutputAtMaxRes> -<MaxSimTim>3600.</MaxSimTim> -<MassUncertainty>0.</MassUncertainty> -<MOIUncertainty>0.</MOIUncertainty> -<CGUncertainty>0.</CGUncertainty> -<CdUncertainty>0.</CdUncertainty> -<CnaUncertainty>0.</CnaUncertainty> -<CPUncertainty>0.</CPUncertainty> -<FinCantUncertainty>0.</FinCantUncertainty> -<TotImpulseUncertainty>0.</TotImpulseUncertainty> -<PropellantUncertainty>0.</PropellantUncertainty> -<ThrustAxisUncertainty>0.</ThrustAxisUncertainty> -<WindDirectionUncertainty>0.</WindDirectionUncertainty> -<WindVelocityUncertainty>0.</WindVelocityUncertainty> -<LaunchGuideAzimuthUncertainty>0.</LaunchGuideAzimuthUncertainty> -<LaunchGuideElevationUncertainty>0.</LaunchGuideElevationUncertainty> -<IgnitionUncertainty>0.</IgnitionUncertainty> -<CATOUncertainty>0.</CATOUncertainty> -<DeploymentUncertainty>0.</DeploymentUncertainty> -<RecoveryDeviceUncertainty>0.</RecoveryDeviceUncertainty> -<SimulationName>[E6-2] </SimulationName> -<VelocityAtLaunchGuideEnd>15.4098</VelocityAtLaunchGuideEnd> -<WindStartAltitude>0.</WindStartAltitude> -<TimeToWindShear>0.</TimeToWindShear> -<TimeToFreeFlight>0.25875</TimeToFreeFlight> -<TimeToMaxVelocity>5.69125</TimeToMaxVelocity> -<TimeToMaxAcceleration>0.11125</TimeToMaxAcceleration> -<Nsims>10</Nsims> -<CalcResolution>1</CalcResolution> -<SamplesPerSecond>800.</SamplesPerSecond> -<SimulationType>0</SimulationType> -<LocationDataServerName>Earth</LocationDataServerName> -<LocationDataServerDisplayName>Standard earth condistions.</LocationDataServerDisplayName> -<ExecutionTime>4.078</ExecutionTime> -<RangeAtLanding>-172.076</RangeAtLanding> -<DirectionAtLanding>0.</DirectionAtLanding> -<VelocityAtLanding>56.537</VelocityAtLanding> -<XVelcoityAtLanding>-3.38254</XVelcoityAtLanding> -<YVelocityAtLanding>-56.4357</YVelocityAtLanding> -<ZVelocityAtLanding>0.</ZVelocityAtLanding> -<StageSeparationTime>0,0,8.06125,0,0</StageSeparationTime> -<StageEjectTime>-1,-1,-1,-1,-1</StageEjectTime> -<TimeToDeployment>0,0,0,0,0</TimeToDeployment> -<DeploymentType>32,32,32,32,32</DeploymentType> -<SamplesPerSecondDescent>1.</SamplesPerSecondDescent> -<CalculationFlags>1</CalculationFlags> -<Mass0>0.233111</Mass0> -<CG0>0.739954</CG0> -<LaterialMOI0>0.0208295</LaterialMOI0> -<RadialMOI0>0.000194272</RadialMOI0> -<GUID>{b33e529e-1ada-4524-9885-7382d7cf4d64}</GUID> -<Booster1Staging> -<SimulationEvent> -<PartSerialNo>0</PartSerialNo> -<Type>0</Type> -<DeployAltitude>0.</DeployAltitude> -<DeplyTime>0.</DeplyTime> -<HasDeployed>0</HasDeployed> -<DeployedAt_Altitude>0.</DeployedAt_Altitude> -<DeployedAt_Velocity>0.</DeployedAt_Velocity> -<DeployedAt_Range>0.</DeployedAt_Range> -<DeployedAt_Time>0.</DeployedAt_Time> -<DeviceID>-1</DeviceID> -<TestType>0,0,0</TestType> -<TestCondition>0,0,0</TestCondition> -<TestValueAltitude>0,0,0</TestValueAltitude> -<TestValueDegrees>0,0,0</TestValueDegrees> -<TestValuePressure>0,0,0</TestValuePressure> -<TestValueMach>0,0,0</TestValueMach> -<TestValueTime>0,0,0</TestValueTime> -<TestValueQ>0,0,0</TestValueQ> -</SimulationEvent> -</Booster1Staging> -<Booster2Staging> -<SimulationEvent> -<PartSerialNo>0</PartSerialNo> -<Type>0</Type> -<DeployAltitude>0.</DeployAltitude> -<DeplyTime>0.</DeplyTime> -<HasDeployed>0</HasDeployed> -<DeployedAt_Altitude>0.</DeployedAt_Altitude> -<DeployedAt_Velocity>0.</DeployedAt_Velocity> -<DeployedAt_Range>0.</DeployedAt_Range> -<DeployedAt_Time>0.</DeployedAt_Time> -<DeviceID>-1</DeviceID> -<TestType>0,0,0</TestType> -<TestCondition>0,0,0</TestCondition> -<TestValueAltitude>0,0,0</TestValueAltitude> -<TestValueDegrees>0,0,0</TestValueDegrees> -<TestValuePressure>0,0,0</TestValuePressure> -<TestValueMach>0,0,0</TestValueMach> -<TestValueTime>0,0,0</TestValueTime> -<TestValueQ>0,0,0</TestValueQ> -</SimulationEvent> -</Booster2Staging> -<SimulationEvents> -</SimulationEvents> -<Stage1Engines> -</Stage1Engines> -<Stage2Engines> -</Stage2Engines> -<Stage3Engines> -<EngineSet> -<EngineCount>1</EngineCount> -<EngineCode>E6</EngineCode> -<IgnitionDelay>0.</IgnitionDelay> -<EngineMfg>Apogee</EngineMfg> -<EngineOverhang>0.50038</EngineOverhang> -<CasingCG>0.</CasingCG> -<MountSerialNo>5</MountSerialNo> -<EjectionDelay>2.</EjectionDelay> -<RotateXaboutY>0.</RotateXaboutY> -<RotateEngineAxisAboutX>0.</RotateEngineAxisAboutX> -</EngineSet> -</Stage3Engines> -<DropItems> -</DropItems> -</SimulationResults> -</SimulationResultsList> -</RockSimDocument> diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket2.rkt b/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket2.rkt deleted file mode 100644 index 39b3411b..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket2.rkt +++ /dev/null @@ -1,1583 +0,0 @@ -<RockSimDocument> -<FileVersion>3</FileVersion> -<DesignInformation> -<RocketDesign> -<Name>Three Stage Everything Included Rocket</Name> -<CalculateCD>1</CalculateCD> -<ProCalculateCD>1</ProCalculateCD> -<ProCalculateCN>1</ProCalculateCN> -<FixedCd>0.75</FixedCd> -<FixedCd2>0.8</FixedCd2> -<FixedCd3>0.81</FixedCd3> -<FixedCd2Alone>0.95</FixedCd2Alone> -<FixedCd3Alone>0.95</FixedCd3Alone> -<StageCount>3</StageCount> -<Stage3Mass>0.</Stage3Mass> -<Stage2Mass>0.</Stage2Mass> -<Stage1Mass>0.</Stage1Mass> -<Stage321CG>0.</Stage321CG> -<Stage32CG>0.</Stage32CG> -<Stage3CG>0.</Stage3CG> -<Stage2CGAlone>0.</Stage2CGAlone> -<Stage1CGAlone>0.</Stage1CGAlone> -<CPCalcFlags>1</CPCalcFlags> -<LaunchGuideLength>914.4</LaunchGuideLength> -<UseKnownMass>0</UseKnownMass> -<DefaultFinish>0</DefaultFinish> -<FinishMedium>0</FinishMedium> -<FinishCoatCount>1</FinishCoatCount> -<GlueType>0</GlueType> -<CPSimFlags>1</CPSimFlags> -<LastSerialNumber>25</LastSerialNumber> -<DisplayFlags>7</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<BarromanXN>0,29.6333,326.159,887.03</BarromanXN> -<BarrowmanCNa>0,2,4.93008,33.0782</BarrowmanCNa> -<RockSimXN>0,29.6333,384.174,883.929</RockSimXN> -<RockSimCNa>0,2,6.91103,47.1184</RockSimCNa> -<RockSimCNa90>0,0,0,0</RockSimCNa90> -<RockSimXN90>0,0,0,0</RockSimXN90> -<ViewType>0</ViewType> -<ViewStageCount>3</ViewStageCount> -<ViewTypeEdit>0</ViewTypeEdit> -<ViewStageCountEdit>3</ViewStageCountEdit> -<ZoomFactor>0.</ZoomFactor> -<ZoomFactorEdit>0.</ZoomFactorEdit> -<ScrollPosX>0</ScrollPosX> -<ScrollPosY>0</ScrollPosY> -<ScrollPosXEdit>0</ScrollPosXEdit> -<ScrollPosYEdit>0</ScrollPosYEdit> -<ThreeDFlags>0</ThreeDFlags> -<ThreeDFlagsEdit>0</ThreeDFlagsEdit> -<UseModelSprite>0</UseModelSprite> -<StaticMarginRef>0</StaticMarginRef> -<UserRefDiameter>0.</UserRefDiameter> -<SideMarkerHeight>10.</SideMarkerHeight> -<SideDimensionHeight>10.</SideDimensionHeight> -<BaseMarkerHeight>10.</BaseMarkerHeight> -<BaseDimensionHeight>10.</BaseDimensionHeight> -<ShowGlideCP>0</ShowGlideCP> -<ShowGridTypeSide>0</ShowGridTypeSide> -<ShowGridTypeBase>0</ShowGridTypeBase> -<GridSpacing>10.</GridSpacing> -<GridOpacity>0.15</GridOpacity> -<GridColor>black</GridColor> -<MaxDiaWithFins>339.43</MaxDiaWithFins> -<MaxDiaWithoutFins>66.3</MaxDiaWithoutFins> -<MaxLenWithFins>2104.53</MaxLenWithFins> -<MaxLenWithoutFins>2104.53</MaxLenWithoutFins> -<MinXExtent>0.</MinXExtent> -<MaxXExtent>1150.33</MaxXExtent> -<CalculatedMaxStageDia>0,66.3,66.3,66.3</CalculatedMaxStageDia> -<CalculatedStageLen>0,296.8,954.2,2104.53</CalculatedStageLen> -<Cd3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd3> -<Cd32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd32> -<Cd321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd321> -<Cb3> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb3> -<Cb32> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb32> -<Cb321> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb321> -<CNa3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa3> -<CNa32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa32> -<CNa321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa321> -<CP3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP3> -<CP32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP32> -<CP321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP321> -<SimulationEventList> -</SimulationEventList> -<Stage3Parts> -<NoseCone> -<PartMfg>Aerospace Speciality Products</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Nose cone</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>42.0747</CalcMass> -<CalcCG>75.3029</CalcCG> -<WettedSurface>0.0152945</WettedSurface> -<PaintedSurface>0.0152945</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>BNC80S</PartNo> -<PartDesc><![CDATA[T-80H Balsa Nose Cone "S"]]></PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>1</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>2.</BarrowmanCNa> -<BarrowmanXN>0.0296333</BarrowmanXN> -<RockSimCNa>2.</RockSimCNa> -<RockSimXN>0.0296333</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>0.</Station> -<Len>88.9</Len> -<BaseDia>66.3</BaseDia> -<FinishCode>0</FinishCode> -<ShapeCode>3</ShapeCode> -<ConstructionType>0</ConstructionType> -<ShoulderLen>38.1</ShoulderLen> -<WallThickness>0.</WallThickness> -<ShapeParameter>0.</ShapeParameter> -<ShoulderOD>64.3</ShoulderOD> -<BaseExtensionLen>0.</BaseExtensionLen> -<CoreDia>0.</CoreDia> -<CoreLen>0.</CoreLen> -<AttachedParts> -<MassObject> -<PartMfg>Custom</PartMfg> -<KnownMass>20.</KnownMass> -<Density>0.</Density> -<Material>Custom</Material> -<Name>Clay</Name> -<KnownCG>17.8</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>17.8</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>0.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>2</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>17.8</Station> -<TypeCode>0</TypeCode> -<Len>0.</Len> -<AttachedParts> -</AttachedParts> -</MassObject> -<BodyTube> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Attachment Rod</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>6.1</Xb> -<CalcMass>2.47301</CalcMass> -<CalcCG>78.85</CalcCG> -<WettedSurface>0.00684683</WettedSurface> -<PaintedSurface>0.00684683</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>10062</PartNo> -<PartDesc>13 mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>3</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>6.1</Station> -<OD>13.82</OD> -<ID>13.16</ID> -<Len>157.7</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Plate</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>78.9</Xb> -<CalcMass>7.86272</CalcMass> -<CalcCG>1.585</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-(2)0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>4</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>85.</Station> -<OD>66.</OD> -<ID>13.82</ID> -<Len>3.17</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>Custom</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1400.</Density> -<Material>Carbon Fiber</Material> -<Name>Sleeve </Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>17.5527</CalcMass> -<CalcCG>13.85</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>5</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>2</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>136.1</Station> -<OD>27.7</OD> -<ID>13.82</ID> -<Len>27.7</Len> -<FinishCode>0</FinishCode> -<UsageCode>3</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Parachute> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>170.</KnownMass> -<Density>0.006685</Density> -<Material>Rip stop nylon</Material> -<Name>Nose Cone Parachute</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>142.6</Xb> -<CalcMass>15.8812</CalcMass> -<CalcCG>34.5417</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>1</DensityType> -<PartNo>LP-50</PartNo> -<PartDesc>50 In. 16 lines</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>6</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>148.7</Station> -<Dia>414.5</Dia> -<SpillHoleDia>0.</SpillHoleDia> -<SideCount>15</SideCount> -<ShroudLineCount>16</ShroudLineCount> -<Thickness>0.05</Thickness> -<ShroudLineLen>1350.</ShroudLineLen> -<ChuteCount>1</ChuteCount> -<ShroudLineMassPerMM>0.00032972</ShroudLineMassPerMM> -<ShroudLineMaterial>Carpet String (Apogee 29500)</ShroudLineMaterial> -<DragCoefficient>0.95</DragCoefficient> -<AttachedParts> -</AttachedParts> -</Parachute> -</AttachedParts> -</BodyTube> -</AttachedParts> -</NoseCone> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>15.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>100.</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>5.80486</CalcMass> -<CalcCG>100.</CalcCG> -<WettedSurface>0.0414942</WettedSurface> -<PaintedSurface>0.0414942</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3090</PartNo> -<PartDesc>BT-80</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>7</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>88.9</Station> -<OD>66.04</OD> -<ID>65.79</ID> -<Len>200.</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>190.2</Xb> -<CalcMass>7.65502</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>8</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>279.1</Station> -<OD>65.02</OD> -<ID>25.4</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>165.</Xb> -<CalcMass>7.62626</CalcMass> -<CalcCG>1.585</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-(2)0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>9</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>253.9</Station> -<OD>65.</OD> -<ID>25.4</ID> -<Len>3.17</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<BodyTube> -<PartMfg>Public Missiles Ltd.</PartMfg> -<KnownMass>0.</KnownMass> -<Density>958.705</Density> -<Material>Kraft phenolic</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>137.9</Xb> -<CalcMass>9.8818</CalcMass> -<CalcCG>35.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>KS-1.1</PartNo> -<PartDesc>KwikSwitch MMT 29mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>-1.58371</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>10</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>226.8</Station> -<OD>32.26</OD> -<ID>29.21</ID> -<Len>70.</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>29.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -</AttachedParts> -</BodyTube> -</Stage3Parts> -<Stage2Parts> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>2nd Stage Tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>10.4685</CalcMass> -<CalcCG>180.34</CalcCG> -<WettedSurface>0.0748306</WettedSurface> -<PaintedSurface>0.0748306</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3090</PartNo> -<PartDesc>BT-80</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>11</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>288.9</Station> -<OD>66.04</OD> -<ID>65.79</ID> -<Len>360.68</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>15.025</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Tube coupler</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>-10.</Xb> -<CalcMass>20.465</CalcMass> -<CalcCG>35.45</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TC-2.56</PartNo> -<PartDesc>Tube Coupler</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>12</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>278.9</Station> -<OD>65.79</OD> -<ID>63.25</ID> -<Len>70.9</Len> -<FinishCode>0</FinishCode> -<UsageCode>4</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<MassObject> -<PartMfg>Custom</PartMfg> -<KnownMass>40.</KnownMass> -<Density>0.</Density> -<Material>Custom</Material> -<Name>Electronics</Name> -<KnownCG>138.3</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>138.3</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>0.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>13</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>427.2</Station> -<TypeCode>0</TypeCode> -<Len>0.</Len> -<AttachedParts> -</AttachedParts> -</MassObject> -<FinSet> -<PartMfg>Quest</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Fin set</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>228.6</Xb> -<CalcMass>1.32269</CalcMass> -<CalcCG>19.05</CalcCG> -<WettedSurface>0.0028791</WettedSurface> -<PaintedSurface>0.0086373</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>Payloader One</PartNo> -<PartDesc>Fin</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.0830777</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>14</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>2.93008</BarrowmanCNa> -<BarrowmanXN>0.52856</BarrowmanXN> -<RockSimCNa>5.49629</RockSimCNa> -<RockSimXN>0.52856</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>517.5</Station> -<FinCount>3</FinCount> -<RootChord>38.1</RootChord> -<TipChord>24.9</TipChord> -<SemiSpan>45.7</SemiSpan> -<MidChordLen>45.7</MidChordLen> -<SweepDistance>6.6</SweepDistance> -<Thickness>2.39</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>2</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.139993</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>54.2741</RockSimRadialXNPerFin> -<RockSimCNaPerFin>2.83538</RockSimCNaPerFin> -<TaperRatio>0.653543</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>302.</Xb> -<CalcMass>7.65502</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>15</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>590.9</Station> -<OD>65.02</OD> -<ID>25.4</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>335.5</Xb> -<CalcMass>7.62626</CalcMass> -<CalcCG>1.585</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-(2)0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>16</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>624.4</Station> -<OD>65.</OD> -<ID>25.4</ID> -<Len>3.17</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<BodyTube> -<PartMfg>Public Missiles Ltd.</PartMfg> -<KnownMass>0.</KnownMass> -<Density>958.705</Density> -<Material>Kraft phenolic</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>587.4</Xb> -<CalcMass>9.8818</CalcMass> -<CalcCG>35.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>KS-1.1</PartNo> -<PartDesc>KwikSwitch MMT 29mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>-1.58371</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>17</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>1</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>587.4</Station> -<OD>32.26</OD> -<ID>29.21</ID> -<Len>70.</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>29.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>Semroc</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Engine block</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>2.69315</CalcMass> -<CalcCG>2.39</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TB-7</PartNo> -<PartDesc>Thrust Block</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>18</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>587.4</Station> -<OD>29.21</OD> -<ID>14.61</ID> -<Len>4.78</Len> -<FinishCode>0</FinishCode> -<UsageCode>2</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -</AttachedParts> -</BodyTube> -</AttachedParts> -</BodyTube> -</Stage2Parts> -<Stage1Parts> -<Transition> -<PartMfg>BalsaMachining.com</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Transition</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>8.62096</CalcMass> -<CalcCG>25.1578</CalcCG> -<WettedSurface>0.00986655</WettedSurface> -<PaintedSurface>0.00986655</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TA6080</PartNo> -<PartDesc>Transition T60 to T80 2.25 in long</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>19</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>-1.20451</BarrowmanCNa> -<BarrowmanXN>0.675971</BarrowmanXN> -<RockSimCNa>-1.20451</RockSimCNa> -<RockSimXN>0.675971</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>649.58</Station> -<FrontDia>66.04</FrontDia> -<RearDia>41.4</RearDia> -<Len>57.15</Len> -<FinishCode>0</FinishCode> -<FrontShoulderLen>20.</FrontShoulderLen> -<RearShoulderLen>38.1</RearShoulderLen> -<ConstructionType>1</ConstructionType> -<WallThickness>3.</WallThickness> -<FrontShoulderDia>64.77</FrontShoulderDia> -<RearShoulderDia>41.38</RearShoulderDia> -<CoreDia>0.</CoreDia> -<ShapeCode>0</ShapeCode> -<ShapeParameter>0.</ShapeParameter> -<EquivNoseLen>153.172</EquivNoseLen> -<EquivNoseOffset>96.022</EquivNoseOffset> -<AttachedParts> -</AttachedParts> -</Transition> -<BodyTube> -<PartMfg>LOC/Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>33.5306</CalcMass> -<CalcCG>209.2</CalcCG> -<WettedSurface>0.0604643</WettedSurface> -<PaintedSurface>0.0604643</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC BT-2.14</PartNo> -<PartDesc>Airframe tube</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>20</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>706.73</Station> -<OD>46.</OD> -<ID>45.</ID> -<Len>418.4</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<FinSet> -<PartMfg>Quest</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Elliptical Fins</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>69.7</Xb> -<CalcMass>36.2048</CalcMass> -<CalcCG>46.</CalcCG> -<WettedSurface>0.00676907</WettedSurface> -<PaintedSurface>0.0203072</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>-0.519061</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>21</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>3.64017</BarrowmanCNa> -<BarrowmanXN>0.802926</BarrowmanXN> -<RockSimCNa>6.19583</RockSimCNa> -<RockSimXN>0.802926</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>776.43</Station> -<FinCount>3</FinCount> -<RootChord>92.</RootChord> -<TipChord>46.</TipChord> -<SemiSpan>46.9</SemiSpan> -<MidChordLen>46.9</MidChordLen> -<SweepDistance>33.49</SweepDistance> -<Thickness>3.18</Thickness> -<ShapeCode>1</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>0</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.349066</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>43.8444</RockSimRadialXNPerFin> -<RockSimCNaPerFin>3.30201</RockSimCNaPerFin> -<TaperRatio>0.5</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -<CustomFinSet> -<PartMfg>Public Missiles</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1905.24</Density> -<Material>G10 fiberglass</Material> -<Name>Custom Fins</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>241.7</Xb> -<CalcMass>256.292</CalcMass> -<CalcCG>78.9922</CalcCG> -<WettedSurface>0.0355266</WettedSurface> -<PaintedSurface>0.10658</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>FIN-C-02</PartNo> -<PartDesc>Fins</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.357967</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>22</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>25.7124</BarrowmanCNa> -<BarrowmanXN>0.996591</BarrowmanXN> -<RockSimCNa>34.6308</RockSimCNa> -<RockSimXN>0.996926</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>948.43</Station> -<FinCount>3</FinCount> -<RootChord>152.4</RootChord> -<TipChord>83.83</TipChord> -<SemiSpan>146.72</SemiSpan> -<MidChordLen>146.81</MidChordLen> -<SweepDistance>39.42</SweepDistance> -<Thickness>2.38</Thickness> -<ShapeCode>2</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>2</TipShapeCode> -<TabLength>101.6</TabLength> -<TabDepth>10.6</TabDepth> -<TabOffset>35.6</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>89.2598</RockSimRadialXNPerFin> -<RockSimCNaPerFin>19.9941</RockSimCNaPerFin> -<TaperRatio>0.550066</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AverageChord>121.07</AverageChord> -<EffectiveTipChord>83.8257</EffectiveTipChord> -<PointList>152.4,0|126.202,146.715|36.455,146.715|0,0|</PointList> -<AutoCalcGridStepX>0,0,0,0,0,0,0</AutoCalcGridStepX> -<GridStepCountX>10,10,10,10,10,10,10</GridStepCountX> -<UseAbsoluteGridStepsX>0,0,0,0,0,0,0</UseAbsoluteGridStepsX> -<GridStepSizeX>0.5,10,0.5,0.5,0.00018939,0.001,1</GridStepSizeX> -<SnapToSizeX>0.25,5,0.1,0.1,0.00018939,0.001,1</SnapToSizeX> -<AutoCalcGridStepY>0,0,0,0,0,0,0</AutoCalcGridStepY> -<GridStepCountY>10,10,10,10,10,10,10</GridStepCountY> -<UseAbsoluteGridStepsY>0,0,0,0,0,0,0</UseAbsoluteGridStepsY> -<GridStepSizeY>0.5,10,0.5,0.5,0.00018939,0.001,1</GridStepSizeY> -<SnapToSizeY>0.25,5,0.1,0.1,0.00018939,0.001,1</SnapToSizeY> -<AttachedParts> -</AttachedParts> -</CustomFinSet> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>379.5</Xb> -<CalcMass>2.55395</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC FCR-1.52-1.14</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>23</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>1086.23</Station> -<OD>45.</OD> -<ID>24.79</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>272.</Xb> -<CalcMass>2.55395</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC FCR-1.52-1.14</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>24</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>978.73</Station> -<OD>45.</OD> -<ID>24.79</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>259.7</Xb> -<CalcMass>5.22902</CalcMass> -<CalcCG>91.95</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3086</PartNo> -<PartDesc>BT-50</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>25</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>966.43</Station> -<OD>24.79</OD> -<ID>24.13</ID> -<Len>183.9</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>24.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -</AttachedParts> -</BodyTube> -</Stage1Parts> -<SideViewDims> -</SideViewDims> -<BaseViewDims> -</BaseViewDims> -<VertViewDims> -</VertViewDims> -</RocketDesign> -</DesignInformation> -<SimulationResultsList> -</SimulationResultsList> -</RockSimDocument> diff --git a/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket3.rkt b/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket3.rkt deleted file mode 100644 index df1788c2..00000000 --- a/core/test/net/sf/openrocket/file/rocksim/importt/rocksimTestRocket3.rkt +++ /dev/null @@ -1,1961 +0,0 @@ -<RockSimDocument> -<FileVersion>3</FileVersion> -<DesignInformation> -<RocketDesign> -<Name>Three Stage Everything Included Rocket - Override Total Mass/CG</Name> -<CalculateCD>1</CalculateCD> -<ProCalculateCD>1</ProCalculateCD> -<ProCalculateCN>1</ProCalculateCN> -<FixedCd>0.75</FixedCd> -<FixedCd2>0.8</FixedCd2> -<FixedCd3>0.81</FixedCd3> -<FixedCd2Alone>0.95</FixedCd2Alone> -<FixedCd3Alone>0.95</FixedCd3Alone> -<StageCount>3</StageCount> -<Stage3Mass>185.</Stage3Mass> -<Stage2Mass>210.</Stage2Mass> -<Stage1Mass>330.</Stage1Mass> -<Stage321CG>0.</Stage321CG> -<Stage32CG>0.</Stage32CG> -<Stage3CG>300.</Stage3CG> -<Stage2CGAlone>400.</Stage2CGAlone> -<Stage1CGAlone>500.</Stage1CGAlone> -<CPCalcFlags>1</CPCalcFlags> -<LaunchGuideLength>914.4</LaunchGuideLength> -<UseKnownMass>0</UseKnownMass> -<DefaultFinish>0</DefaultFinish> -<FinishMedium>0</FinishMedium> -<FinishCoatCount>1</FinishCoatCount> -<GlueType>0</GlueType> -<CPSimFlags>1</CPSimFlags> -<LastSerialNumber>32</LastSerialNumber> -<DisplayFlags>7</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<BarromanXN>0,29.6333,327.236,966.855</BarromanXN> -<BarrowmanCNa>0,2,4.95647,83.562</BarrowmanCNa> -<RockSimXN>0,29.6333,385.082,953.76</RockSimXN> -<RockSimCNa>0,2,6.95476,97.0629</RockSimCNa> -<RockSimCNa90>0,0,0,0</RockSimCNa90> -<RockSimXN90>0,0,0,0</RockSimXN90> -<ViewType>0</ViewType> -<ViewStageCount>3</ViewStageCount> -<ViewTypeEdit>0</ViewTypeEdit> -<ViewStageCountEdit>3</ViewStageCountEdit> -<ZoomFactor>0.</ZoomFactor> -<ZoomFactorEdit>0.</ZoomFactorEdit> -<ScrollPosX>0</ScrollPosX> -<ScrollPosY>0</ScrollPosY> -<ScrollPosXEdit>0</ScrollPosXEdit> -<ScrollPosYEdit>0</ScrollPosYEdit> -<ThreeDFlags>0</ThreeDFlags> -<ThreeDFlagsEdit>0</ThreeDFlagsEdit> -<UseModelSprite>0</UseModelSprite> -<StaticMarginRef>0</StaticMarginRef> -<UserRefDiameter>0.</UserRefDiameter> -<SideMarkerHeight>10.</SideMarkerHeight> -<SideDimensionHeight>10.</SideDimensionHeight> -<BaseMarkerHeight>10.</BaseMarkerHeight> -<BaseDimensionHeight>10.</BaseDimensionHeight> -<ShowGlideCP>0</ShowGlideCP> -<ShowGridTypeSide>0</ShowGridTypeSide> -<ShowGridTypeBase>0</ShowGridTypeBase> -<GridSpacing>10.</GridSpacing> -<GridOpacity>0.15</GridOpacity> -<GridColor>black</GridColor> -<MaxDiaWithFins>334.83</MaxDiaWithFins> -<MaxDiaWithoutFins>66.</MaxDiaWithoutFins> -<MaxLenWithFins>2155.23</MaxLenWithFins> -<MaxLenWithoutFins>2155.23</MaxLenWithoutFins> -<MinXExtent>0.</MinXExtent> -<MaxXExtent>1150.33</MaxXExtent> -<CalculatedMaxStageDia>0,66,66,66</CalculatedMaxStageDia> -<CalculatedStageLen>0,347.5,1004.9,2155.23</CalculatedStageLen> -<Cd3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd3> -<Cd32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd32> -<Cd321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cd321> -<Cb3> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb3> -<Cb32> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb32> -<Cb321> -<PolyData useXYOnly="1" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</Cb321> -<CNa3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa3> -<CNa32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa32> -<CNa321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CNa321> -<CP3> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP3> -<CP32> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP32> -<CP321> -<PolyData useXYOnly="0" useSmoothCurveEvaluation="0" count="0"> -<X-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</X-data> -<A-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</A-data> -<B-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</B-data> -<C-data>0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0</C-data> -</PolyData> -</CP321> -<SimulationEventList> -</SimulationEventList> -<Stage3Parts> -<NoseCone> -<PartMfg>Aerospace Speciality Products</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Nose cone</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>42.6368</CalcMass> -<CalcCG>76.0242</CalcCG> -<WettedSurface>0.0152192</WettedSurface> -<PaintedSurface>0.0152192</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>BNC80S</PartNo> -<PartDesc><![CDATA[T-80H Balsa Nose Cone "S"]]></PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>1</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>2.</BarrowmanCNa> -<BarrowmanXN>0.0296333</BarrowmanXN> -<RockSimCNa>2.</RockSimCNa> -<RockSimXN>0.0296333</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>0.</Station> -<Len>88.9</Len> -<BaseDia>66.</BaseDia> -<FinishCode>0</FinishCode> -<ShapeCode>3</ShapeCode> -<ConstructionType>0</ConstructionType> -<ShoulderLen>38.1</ShoulderLen> -<WallThickness>0.</WallThickness> -<ShapeParameter>0.</ShapeParameter> -<ShoulderOD>65.9</ShoulderOD> -<BaseExtensionLen>0.</BaseExtensionLen> -<CoreDia>0.</CoreDia> -<CoreLen>0.</CoreLen> -<AttachedParts> -<MassObject> -<PartMfg>Custom</PartMfg> -<KnownMass>20.</KnownMass> -<Density>0.</Density> -<Material>Custom</Material> -<Name>Clay</Name> -<KnownCG>17.8</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>17.8</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>0.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>2</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>17.8</Station> -<TypeCode>0</TypeCode> -<Len>0.</Len> -<AttachedParts> -</AttachedParts> -</MassObject> -<BodyTube> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Attachment Rod</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>6.1</Xb> -<CalcMass>2.47301</CalcMass> -<CalcCG>78.85</CalcCG> -<WettedSurface>0.00684683</WettedSurface> -<PaintedSurface>0.00684683</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>10062</PartNo> -<PartDesc>13 mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>3</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>6.1</Station> -<OD>13.82</OD> -<ID>13.16</ID> -<Len>157.7</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Plate</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>78.9</Xb> -<CalcMass>7.86272</CalcMass> -<CalcCG>1.585</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-(2)0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>4</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>85.</Station> -<OD>66.</OD> -<ID>13.82</ID> -<Len>3.17</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>Custom</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1400.</Density> -<Material>Carbon Fiber</Material> -<Name>Sleeve </Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>17.5527</CalcMass> -<CalcCG>13.85</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>5</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>2</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>136.1</Station> -<OD>27.7</OD> -<ID>13.82</ID> -<Len>27.7</Len> -<FinishCode>0</FinishCode> -<UsageCode>3</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Parachute> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>170.</KnownMass> -<Density>0.006685</Density> -<Material>Rip stop nylon</Material> -<Name>Nose Cone Parachute</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>142.6</Xb> -<CalcMass>15.8812</CalcMass> -<CalcCG>34.5417</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>1</DensityType> -<PartNo>LP-50</PartNo> -<PartDesc>50 In. 16 lines</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>6</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>148.7</Station> -<Dia>414.5</Dia> -<SpillHoleDia>0.</SpillHoleDia> -<SideCount>15</SideCount> -<ShroudLineCount>16</ShroudLineCount> -<Thickness>0.05</Thickness> -<ShroudLineLen>1350.</ShroudLineLen> -<ChuteCount>1</ChuteCount> -<ShroudLineMassPerMM>0.00032972</ShroudLineMassPerMM> -<ShroudLineMaterial>Carpet String (Apogee 29500)</ShroudLineMaterial> -<DragCoefficient>0.95</DragCoefficient> -<AttachedParts> -</AttachedParts> -</Parachute> -</AttachedParts> -</BodyTube> -</AttachedParts> -</NoseCone> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>15.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>100.</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>5.805</CalcMass> -<CalcCG>100.</CalcCG> -<WettedSurface>0.0414942</WettedSurface> -<PaintedSurface>0.0414942</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3090</PartNo> -<PartDesc>BT-80</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>7</SerialNo> -<DisplayFlags>1</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>88.9</Station> -<OD>66.</OD> -<ID>65.79</ID> -<Len>200.</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>190.2</Xb> -<CalcMass>7.65502</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>8</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>279.1</Station> -<OD>65.02</OD> -<ID>25.4</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>165.</Xb> -<CalcMass>7.62626</CalcMass> -<CalcCG>1.585</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-(2)0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>9</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>253.9</Station> -<OD>65.</OD> -<ID>25.4</ID> -<Len>3.17</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<BodyTube> -<PartMfg>Public Missiles Ltd.</PartMfg> -<KnownMass>0.</KnownMass> -<Density>958.705</Density> -<Material>Kraft phenolic</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>137.9</Xb> -<CalcMass>9.8818</CalcMass> -<CalcCG>35.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>KS-1.1</PartNo> -<PartDesc>KwikSwitch MMT 29mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>-1.58371</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>10</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>226.8</Station> -<OD>32.26</OD> -<ID>29.21</ID> -<Len>70.</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>29.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -<LaunchLug> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Launch lug</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>77.2</Xb> -<CalcMass>1.11942</CalcMass> -<CalcCG>38.1</CalcCG> -<WettedSurface>0.00374518</WettedSurface> -<PaintedSurface>0.00199411</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>13056</PartNo> -<PartDesc><![CDATA[1/4" X 3]]></PartDesc> -<RadialLoc>37.185</RadialLoc> -<RadialAngle>3.14</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>26</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>166.1</Station> -<OD>8.33</OD> -<ID>7.26</ID> -<Len>76.2</Len> -<FinishCode>0</FinishCode> -<AttachedParts> -</AttachedParts> -</LaunchLug> -<ExternalPod> -<PartMfg>Custom</PartMfg> -<KnownMass>0.</KnownMass> -<Density>0.</Density> -<Name>Pod</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>200.</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>0.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>36.175</RadialLoc> -<RadialAngle>-1.50735</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>29</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>288.9</Station> -<Detachable>1</Detachable> -<AutoCalcRadialDistance>1</AutoCalcRadialDistance> -<AutoCalcRadialAngle>1</AutoCalcRadialAngle> -<AttachedParts> -<BodyTube> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>958.705</Density> -<Material>Kraft phenolic</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>0.400397</CalcMass> -<CalcCG>29.3</CalcCG> -<WettedSurface>0.00116902</WettedSurface> -<PaintedSurface>0.00116902</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>9601</PartNo> -<PartDesc>6 mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>30</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>288.9</Station> -<OD>6.35</OD> -<ID>5.59</ID> -<Len>58.6</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -</AttachedParts> -</ExternalPod> -</AttachedParts> -</BodyTube> -</Stage3Parts> -<Stage2Parts> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>2nd Stage Tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>10.468</CalcMass> -<CalcCG>180.34</CalcCG> -<WettedSurface>0.0748306</WettedSurface> -<PaintedSurface>0.0748306</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3090</PartNo> -<PartDesc>BT-80</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>11</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>288.9</Station> -<OD>66.</OD> -<ID>65.79</ID> -<Len>360.68</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>15.025</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Tube coupler</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>-10.</Xb> -<CalcMass>20.465</CalcMass> -<CalcCG>35.45</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TC-2.56</PartNo> -<PartDesc>Tube Coupler</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>12</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>278.9</Station> -<OD>65.79</OD> -<ID>63.25</ID> -<Len>70.9</Len> -<FinishCode>0</FinishCode> -<UsageCode>4</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<MassObject> -<PartMfg>Custom</PartMfg> -<KnownMass>40.</KnownMass> -<Density>0.</Density> -<Material>Custom</Material> -<Name>Electronics</Name> -<KnownCG>138.3</KnownCG> -<UseKnownCG>1</UseKnownCG> -<Xb>138.3</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>0.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>13</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>427.2</Station> -<TypeCode>0</TypeCode> -<Len>0.</Len> -<AttachedParts> -</AttachedParts> -</MassObject> -<FinSet> -<PartMfg>Quest</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Fin set</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>228.6</Xb> -<CalcMass>1.32269</CalcMass> -<CalcCG>19.05</CalcCG> -<WettedSurface>0.0028791</WettedSurface> -<PaintedSurface>0.0086373</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>Payloader One</PartNo> -<PartDesc>Fin</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.0830777</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>14</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>2.95647</BarrowmanCNa> -<BarrowmanXN>0.52856</BarrowmanXN> -<RockSimCNa>5.54523</RockSimCNa> -<RockSimXN>0.52856</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>517.5</Station> -<FinCount>3</FinCount> -<RootChord>38.1</RootChord> -<TipChord>24.9</TipChord> -<SemiSpan>45.7</SemiSpan> -<MidChordLen>45.7</MidChordLen> -<SweepDistance>6.6</SweepDistance> -<Thickness>2.39</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>2</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.139993</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>54.2541</RockSimRadialXNPerFin> -<RockSimCNaPerFin>2.86063</RockSimCNaPerFin> -<TaperRatio>0.653543</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>302.</Xb> -<CalcMass>7.65502</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>15</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>590.9</Station> -<OD>65.02</OD> -<ID>25.4</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>335.5</Xb> -<CalcMass>7.62626</CalcMass> -<CalcCG>1.585</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC CR-2.56-(2)0.95</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>16</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>624.4</Station> -<OD>65.</OD> -<ID>25.4</ID> -<Len>3.17</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>0</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<BodyTube> -<PartMfg>Public Missiles Ltd.</PartMfg> -<KnownMass>0.</KnownMass> -<Density>958.705</Density> -<Material>Kraft phenolic</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>587.4</Xb> -<CalcMass>9.8818</CalcMass> -<CalcCG>35.</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>KS-1.1</PartNo> -<PartDesc>KwikSwitch MMT 29mm</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>-1.58371</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>17</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>1</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>587.4</Station> -<OD>32.26</OD> -<ID>29.21</ID> -<Len>70.</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>29.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<Ring> -<PartMfg>Semroc</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Engine block</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>2.69315</CalcMass> -<CalcCG>2.39</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TB-7</PartNo> -<PartDesc>Thrust Block</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>18</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>587.4</Station> -<OD>29.21</OD> -<ID>14.61</ID> -<Len>4.78</Len> -<FinishCode>0</FinishCode> -<UsageCode>2</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -</AttachedParts> -</BodyTube> -<LaunchLug> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Launch lug</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>265.8</Xb> -<CalcMass>1.11942</CalcMass> -<CalcCG>38.1</CalcCG> -<WettedSurface>0.00374518</WettedSurface> -<PaintedSurface>0.00199411</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>13056</PartNo> -<PartDesc><![CDATA[1/4" X 3]]></PartDesc> -<RadialLoc>37.185</RadialLoc> -<RadialAngle>1.22</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>27</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>554.7</Station> -<OD>8.33</OD> -<ID>7.26</ID> -<Len>76.2</Len> -<FinishCode>0</FinishCode> -<AttachedParts> -</AttachedParts> -</LaunchLug> -</AttachedParts> -</BodyTube> -</Stage2Parts> -<Stage1Parts> -<Transition> -<PartMfg>BalsaMachining.com</PartMfg> -<KnownMass>0.</KnownMass> -<Density>128.148</Density> -<Material>Balsa</Material> -<Name>Transition</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>8.61936</CalcMass> -<CalcCG>25.1551</CalcCG> -<WettedSurface>0.0098623</WettedSurface> -<PaintedSurface>0.0098623</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>TA6080</PartNo> -<PartDesc>Transition T60 to T80 2.25 in long</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>19</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>-1.213</BarrowmanCNa> -<BarrowmanXN>0.675973</BarrowmanXN> -<RockSimCNa>-1.213</RockSimCNa> -<RockSimXN>0.675973</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>649.58</Station> -<FrontDia>66.</FrontDia> -<RearDia>41.4</RearDia> -<Len>57.15</Len> -<FinishCode>0</FinishCode> -<FrontShoulderLen>20.</FrontShoulderLen> -<RearShoulderLen>38.1</RearShoulderLen> -<ConstructionType>1</ConstructionType> -<WallThickness>3.</WallThickness> -<FrontShoulderDia>64.77</FrontShoulderDia> -<RearShoulderDia>41.38</RearShoulderDia> -<CoreDia>0.</CoreDia> -<ShapeCode>0</ShapeCode> -<ShapeParameter>0.</ShapeParameter> -<EquivNoseLen>153.339</EquivNoseLen> -<EquivNoseOffset>96.1895</EquivNoseOffset> -<AttachedParts> -</AttachedParts> -</Transition> -<BodyTube> -<PartMfg>LOC/Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>0.</CalcMass> -<CalcCG>nan.</CalcCG> -<WettedSurface>0.0544179</WettedSurface> -<PaintedSurface>0.0544179</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC BT-2.14</PartNo> -<PartDesc>Airframe tube</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>20</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(54,250,21)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>706.73</Station> -<OD>41.4</OD> -<ID>41.</ID> -<Len>418.4</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>0</IsMotorMount> -<MotorDia>0.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>0</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -<FinSet> -<PartMfg>Quest</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Elliptical Fins</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>69.7</Xb> -<CalcMass>36.2048</CalcMass> -<CalcCG>46.</CalcCG> -<WettedSurface>0.00676907</WettedSurface> -<PaintedSurface>0.0203072</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>-0.519061</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>21</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>3.61024</BarrowmanCNa> -<BarrowmanXN>0.802926</BarrowmanXN> -<RockSimCNa>6.03948</RockSimCNa> -<RockSimXN>0.802926</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>776.43</Station> -<FinCount>3</FinCount> -<RootChord>92.</RootChord> -<TipChord>46.</TipChord> -<SemiSpan>46.9</SemiSpan> -<MidChordLen>46.9</MidChordLen> -<SweepDistance>33.49</SweepDistance> -<Thickness>3.18</Thickness> -<ShapeCode>1</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>0</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.349066</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>41.5444</RockSimRadialXNPerFin> -<RockSimCNaPerFin>3.21868</RockSimCNaPerFin> -<TaperRatio>0.5</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AttachedParts> -</AttachedParts> -</FinSet> -<CustomFinSet> -<PartMfg>Public Missiles</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1905.24</Density> -<Material>G10 fiberglass</Material> -<Name>Custom Fins</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>241.7</Xb> -<CalcMass>256.292</CalcMass> -<CalcCG>78.9922</CalcCG> -<WettedSurface>0.0355266</WettedSurface> -<PaintedSurface>0.10658</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>FIN-C-02</PartNo> -<PartDesc>Fins</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.357967</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>22</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>25.7037</BarrowmanCNa> -<BarrowmanXN>0.996526</BarrowmanXN> -<RockSimCNa>34.1865</RockSimCNa> -<RockSimXN>0.996822</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>948.43</Station> -<FinCount>3</FinCount> -<RootChord>152.4</RootChord> -<TipChord>84.53</TipChord> -<SemiSpan>146.72</SemiSpan> -<MidChordLen>146.81</MidChordLen> -<SweepDistance>39.07</SweepDistance> -<Thickness>2.38</Thickness> -<ShapeCode>2</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>2</TipShapeCode> -<TabLength>101.6</TabLength> -<TabDepth>10.6</TabDepth> -<TabOffset>35.6</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>87.0529</RockSimRadialXNPerFin> -<RockSimCNaPerFin>19.7376</RockSimCNaPerFin> -<TaperRatio>0.554659</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<AverageChord>121.39</AverageChord> -<EffectiveTipChord>84.5261</EffectiveTipChord> -<PointList>152.4,0|126.202,146.715|36.455,146.715|0,0|</PointList> -<AutoCalcGridStepX>0,0,0,0,0,0,0</AutoCalcGridStepX> -<GridStepCountX>10,10,10,10,10,10,10</GridStepCountX> -<UseAbsoluteGridStepsX>0,0,0,0,0,0,0</UseAbsoluteGridStepsX> -<GridStepSizeX>0.5,10,0.5,0.5,0.00018939,0.001,1</GridStepSizeX> -<SnapToSizeX>0.25,5,0.1,0.1,0.00018939,0.001,1</SnapToSizeX> -<AutoCalcGridStepY>0,0,0,0,0,0,0</AutoCalcGridStepY> -<GridStepCountY>10,10,10,10,10,10,10</GridStepCountY> -<UseAbsoluteGridStepsY>0,0,0,0,0,0,0</UseAbsoluteGridStepsY> -<GridStepSizeY>0.5,10,0.5,0.5,0.00018939,0.001,1</GridStepSizeY> -<SnapToSizeY>0.25,5,0.1,0.1,0.00018939,0.001,1</SnapToSizeY> -<AttachedParts> -</AttachedParts> -</CustomFinSet> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>379.5</Xb> -<CalcMass>1.99074</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC FCR-1.52-1.14</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>23</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>1086.23</Station> -<OD>41.4</OD> -<ID>24.79</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<Ring> -<PartMfg>LOC Precision</PartMfg> -<KnownMass>0.</KnownMass> -<Density>724.996</Density> -<Material>Aircraft plywood (LOC)</Material> -<Name>Centering ring</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>272.</Xb> -<CalcMass>1.99074</CalcMass> -<CalcCG>1.59</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>LOC FCR-1.52-1.14</PartNo> -<PartDesc>Centering Ring</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>24</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>978.73</Station> -<OD>41.4</OD> -<ID>24.79</ID> -<Len>3.18</Len> -<FinishCode>0</FinishCode> -<UsageCode>0</UsageCode> -<AutoSize>1</AutoSize> -<AttachedParts> -</AttachedParts> -</Ring> -<BodyTube> -<PartMfg>Estes</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Body tube</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>259.7</Xb> -<CalcMass>5.22902</CalcMass> -<CalcCG>91.95</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>EST 3086</PartNo> -<PartDesc>BT-50</PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>rgb(0,0,250)</AbientColor> -<DiffuseColor>rgb(0,0,250)</DiffuseColor> -<SpecularColor>rgb(255,255,255)</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>25</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>rgb(0,0,250)</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>966.43</Station> -<OD>24.79</OD> -<ID>24.13</ID> -<Len>183.9</Len> -<FinishCode>0</FinishCode> -<IsMotorMount>1</IsMotorMount> -<MotorDia>24.</MotorDia> -<EngineOverhang>0.5</EngineOverhang> -<FrontExtension>0.</FrontExtension> -<RearExtension>0.</RearExtension> -<IsInsideTube>1</IsInsideTube> -<isStrapOnTube>0</isStrapOnTube> -<AttachedParts> -</AttachedParts> -</BodyTube> -<TubeFinSet> -<PartMfg>Custom</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1121.29</Density> -<Material>Paper</Material> -<Name>Tube fins</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>12.6878</CalcMass> -<CalcCG>24.79</CalcCG> -<WettedSurface>0.0688063</WettedSurface> -<PaintedSurface>0.0688063</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>35.395</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>28</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>10.866</BarrowmanCNa> -<BarrowmanXN>0.707815</BarrowmanXN> -<RockSimCNa>10.866</RockSimCNa> -<RockSimXN>0.707815</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>706.73</Station> -<OD>24.79</OD> -<ID>24.13</ID> -<Len>49.58</Len> -<FinishCode>0</FinishCode> -<TubeCount>9</TubeCount> -<MinTubeAngle>0.715549</MinTubeAngle> -<MaxTubesAllowed>9</MaxTubesAllowed> -<AttachedParts> -</AttachedParts> -</TubeFinSet> -<RingTail> -<PartMfg>Custom</PartMfg> -<KnownMass>0.</KnownMass> -<Density>688.794</Density> -<Material>Cardboard</Material> -<Name>Ringtail</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>0.</Xb> -<CalcMass>2.93707</CalcMass> -<CalcCG>10.</CalcCG> -<WettedSurface>0.00474229</WettedSurface> -<PaintedSurface>0.00444249</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>31</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>2</LocationMode> -<Color>rgb(255,9,18)</Color> -<BarrowmanCNa>39.6386</BarrowmanCNa> -<BarrowmanXN>1.10463</BarrowmanXN> -<RockSimCNa>39.6386</RockSimCNa> -<RockSimXN>1.10463</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>1105.13</Station> -<FinCount>3</FinCount> -<RootChord>20.</RootChord> -<TipChord>20.</TipChord> -<SemiSpan>7.495</SemiSpan> -<MidChordLen>7.495</MidChordLen> -<SweepDistance>0.</SweepDistance> -<Thickness>3.</Thickness> -<ShapeCode>0</ShapeCode> -<FinishCode>0</FinishCode> -<TipShapeCode>0</TipShapeCode> -<TabLength>0.</TabLength> -<TabDepth>0.</TabDepth> -<TabOffset>0.</TabOffset> -<SweepMode>1</SweepMode> -<SweepAngle>0.</SweepAngle> -<RockSimXNPerFin>0.</RockSimXNPerFin> -<RockSimRadialXNPerFin>0.</RockSimRadialXNPerFin> -<RockSimCNaPerFin>0.</RockSimCNaPerFin> -<TaperRatio>0.</TaperRatio> -<CantAngle>0.</CantAngle> -<CantPivotPoint>0.</CantPivotPoint> -<OD>56.39</OD> -<ID>55.37</ID> -<Len>20.</Len> -<TubeDensity>1121.29</TubeDensity> -<TubeDensityType>0</TubeDensityType> -<TubeMaterial>Paper</TubeMaterial> -<AttachedParts> -</AttachedParts> -</RingTail> -<Streamer> -<PartMfg>Apogee</PartMfg> -<KnownMass>0.</KnownMass> -<Density>1309.</Density> -<Material>Mylar</Material> -<Name>Streamer</Name> -<KnownCG>0.</KnownCG> -<UseKnownCG>0</UseKnownCG> -<Xb>149.4</Xb> -<CalcMass>5.67514</CalcMass> -<CalcCG>50.8</CalcCG> -<WettedSurface>0.</WettedSurface> -<PaintedSurface>0.</PaintedSurface> -<GlueJointLength>0.</GlueJointLength> -<DensityType>0</DensityType> -<PartNo>29006</PartNo> -<PartDesc><![CDATA[4" Wide Mylar]]></PartDesc> -<RadialLoc>0.</RadialLoc> -<RadialAngle>0.</RadialAngle> -<Texture>file=()|position=(0,0,0)|origin=(0.5,0.5,0.5)|scale=(1,1,1)|repeat=(1)|interpolate=(0)|flipr(0)|flips(0)|flipt=(0)|preventseam=(1)</Texture> -<Opacity>1.</Opacity> -<Specular>0.</Specular> -<SpecularPower>1.</SpecularPower> -<Ambient>0.</Ambient> -<Diffuse>1.</Diffuse> -<AbientColor>blue</AbientColor> -<DiffuseColor>blue</DiffuseColor> -<SpecularColor>white</SpecularColor> -<UseSingleColor>1</UseSingleColor> -<SerialNo>32</SerialNo> -<DisplayFlags>0</DisplayFlags> -<MetricsFlags>0</MetricsFlags> -<LocationMode>0</LocationMode> -<Color>blue</Color> -<BarrowmanCNa>0.</BarrowmanCNa> -<BarrowmanXN>0.</BarrowmanXN> -<RockSimCNa>0.</RockSimCNa> -<RockSimXN>0.</RockSimXN> -<SimpleColorModel>1</SimpleColorModel> -<ProduceTemplate>0</ProduceTemplate> -<TemplateUnits>8</TemplateUnits> -<Removed>0</Removed> -<Station>856.13</Station> -<Len>1422.4</Len> -<Width>101.6</Width> -<Thickness>0.03</Thickness> -<StreamerCount>1</StreamerCount> -<DragCoefficient>0.127</DragCoefficient> -<IsFolded>0</IsFolded> -<AutoCalcCd>1</AutoCalcCd> -<AttachedParts> -</AttachedParts> -</Streamer> -</AttachedParts> -</BodyTube> -</Stage1Parts> -<SideViewDims> -</SideViewDims> -<BaseViewDims> -</BaseViewDims> -<VertViewDims> -</VertViewDims> -</RocketDesign> -</DesignInformation> -<SimulationResultsList> -</SimulationResultsList> -</RockSimDocument> diff --git a/core/test/net/sf/openrocket/gui/TestGUI.java b/core/test/net/sf/openrocket/gui/TestGUI.java deleted file mode 100644 index 6e05aabb..00000000 --- a/core/test/net/sf/openrocket/gui/TestGUI.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.sf.openrocket.gui; - -import org.junit.Test; - -public class TestGUI { - - @Test - public void test() { - // No-op - } - -} diff --git a/core/test/net/sf/openrocket/gui/configdialog/FinSetConfigTest.java b/core/test/net/sf/openrocket/gui/configdialog/FinSetConfigTest.java deleted file mode 100644 index e45693bc..00000000 --- a/core/test/net/sf/openrocket/gui/configdialog/FinSetConfigTest.java +++ /dev/null @@ -1,257 +0,0 @@ -package net.sf.openrocket.gui.configdialog; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.gui.adaptors.DoubleModel; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -public class FinSetConfigTest extends BaseTestCase { - - static Method method; - - @BeforeClass - public static void classSetup() throws Exception { - method = FinSetConfig.class.getDeclaredMethod("computeFinTabLength", List.class, Double.class, Double.class, DoubleModel.class, RocketComponent.class); - Assert.assertNotNull(method); - method.setAccessible(true); - } - - /** - * Test no centering rings. - * - * @throws Exception - */ - @Test - public void testComputeFinTabLength() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - RocketComponent parent = new BodyTube(); - - Double result = (Double)method.invoke(null, rings, 10d, 11d, dm, parent); - Assert.assertEquals(0.0001, 11d, result.doubleValue()); - result = (Double)method.invoke(null, null, 10d, 11d, dm, parent); - Assert.assertEquals(11d, result.doubleValue(), 0.0001); - } - - /** - * Test 2 rings both ahead of the fin. - */ - @Test - public void testCompute2LeadingRings() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - RocketComponent parent = new BodyTube(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setLength(0.004); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setPositionValue(0.43); - CenteringRing ring2 = new CenteringRing(); - ring2.setLength(0.004); - ring2.setRelativePosition(RocketComponent.Position.TOP); - ring2.setPositionValue(0.45); - rings.add(ring1); - rings.add(ring2); - parent.addChild(ring1); - parent.addChild(ring2); - - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, parent); - Assert.assertEquals(0.01, result.doubleValue(), 0.0001); - - } - - /** - * Test one ring, ahead of the fin. - */ - @Test - public void testCompute1Ring() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setLength(0.004); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setPositionValue(0.43); - rings.add(ring1); - - RocketComponent parent = new BodyTube(); - parent.addChild(ring1); - - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, parent); - Assert.assertEquals(0.01, result.doubleValue(), 0.0001); - } - - /** - * Test one ring ahead of the fin, one ring within the root chord. - */ - @Test - public void testComputeOneLeadingOneRingWithinRoot() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setLength(0.004); - ring1.setPositionValue(0.43); - CenteringRing ring2 = new CenteringRing(); - ring2.setRelativePosition(RocketComponent.Position.TOP); - ring2.setLength(0.004); - ring2.setPositionValue(0.45); - rings.add(ring1); - rings.add(ring2); - - RocketComponent parent = new BodyTube(1d, 0.01); - parent.addChild(ring1); - parent.addChild(ring2); - - Double result = (Double)method.invoke(null, rings, 0.45d, 0.01, dm, parent); - Assert.assertEquals(0.01 - 0.004, result.doubleValue(), 0.0001); - } - - /** - * Test one ring ahead of the fin, one ring beyond the root chord. - */ - @Test - public void testComputeOneLeadingOneTrailingRing() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setLength(0.004); - ring1.setPositionValue(0.43); - CenteringRing ring2 = new CenteringRing(); - ring2.setRelativePosition(RocketComponent.Position.TOP); - ring2.setLength(0.004); - ring2.setPositionValue(0.48); - rings.add(ring1); - rings.add(ring2); - - RocketComponent parent = new BodyTube(); - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, ring1); - Assert.assertEquals(0.01, result.doubleValue(), 0.0001); - } - - /** - * Test one ring within the root chord, another ring beyond the root chord. - */ - @Test - public void testComputeOneWithinRootOneTrailingRing() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setLength(0.004); - ring1.setPositionValue(0.4701); - CenteringRing ring2 = new CenteringRing(); - ring2.setLength(0.004); - ring2.setRelativePosition(RocketComponent.Position.TOP); - ring2.setPositionValue(0.48); - rings.add(ring1); - rings.add(ring2); - RocketComponent parent = new BodyTube(1.0d, 0.1d); - parent.addChild(ring1); - parent.addChild(ring2); - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, parent); - Assert.assertEquals(0.0059, result.doubleValue(), 0.0001); - } - - /** - * Test both rings within the root chord. - */ - @Test - public void testBothRingsWithinRootChord() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - RocketComponent parent = new BodyTube(1.0000d, 0.1d); - CenteringRing ring1 = new CenteringRing(); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setLength(0.004); - ring1.setPositionValue(0.4701); - parent.addChild(ring1); - CenteringRing ring2 = new CenteringRing(); - ring2.setLength(0.004); - ring2.setRelativePosition(RocketComponent.Position.TOP); - ring2.setPositionValue(0.4750); - parent.addChild(ring2); - rings.add(ring1); - rings.add(ring2); - - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, parent); - Assert.assertEquals(0.0009, result.doubleValue(), 0.0002); - } - - - /** - * Test both rings beyond the root chord. - */ - @Test - public void testBothRingsBeyondRootChord() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setRelativePosition(RocketComponent.Position.TOP); - ring1.setLength(0.004); - ring1.setPositionValue(0.48); - CenteringRing ring2 = new CenteringRing(); - ring2.setRelativePosition(RocketComponent.Position.TOP); - ring2.setLength(0.004); - ring2.setPositionValue(0.49); - rings.add(ring1); - rings.add(ring2); - RocketComponent parent = new BodyTube(1.0d, 0.1d); - parent.addChild(ring1); - parent.addChild(ring2); - - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, parent); - Assert.assertEquals(0.0, result.doubleValue(), 0.0001); - } - - /** - * Test both rings within the root chord - the top ring has an adjacent ring (so 3 rings total). - */ - @Test - public void test3RingsWithinRootChord() throws Exception { - DoubleModel dm = new DoubleModel(1d); - List<CenteringRing> rings = new ArrayList<CenteringRing>(); - - CenteringRing ring1 = new CenteringRing(); - ring1.setRelativePosition(RocketComponent.Position.ABSOLUTE); - ring1.setLength(0.004); - ring1.setPositionValue(0.47); - CenteringRing ring2 = new CenteringRing(); - ring2.setRelativePosition(RocketComponent.Position.ABSOLUTE); - ring2.setLength(0.004); - ring2.setPositionValue(0.4702); - CenteringRing ring3 = new CenteringRing(); - ring3.setRelativePosition(RocketComponent.Position.ABSOLUTE); - ring3.setLength(0.004); - ring3.setPositionValue(0.4770); - rings.add(ring1); - rings.add(ring2); - rings.add(ring3); - BodyTube parent = new BodyTube(1.0d, 0.1d); - parent.setPositionValue(0); - parent.addChild(ring1); - parent.addChild(ring2); - parent.addChild(ring3); - - Double result = (Double)method.invoke(null, rings, 0.47d, 0.01, dm, parent); - Assert.assertEquals(0.0028, result.doubleValue(), 0.0001); - } - -} diff --git a/core/test/net/sf/openrocket/gui/print/PrintUnitTest.java b/core/test/net/sf/openrocket/gui/print/PrintUnitTest.java deleted file mode 100644 index f92d18bc..00000000 --- a/core/test/net/sf/openrocket/gui/print/PrintUnitTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.sf.openrocket.gui.print; - -import org.junit.Assert; -import org.junit.Test; - -/** -* PrintUnit Tester. -* -*/ -public class PrintUnitTest { - - /** - * - * Method: toMillis(double length) - * - */ - @Test - public void testToMillis() throws Exception { - Assert.assertEquals(25.400000, PrintUnit.INCHES.toMillis(1), 0.00001); - Assert.assertEquals(1, PrintUnit.MILLIMETERS.toInches(PrintUnit.INCHES.toMillis(1)), 0.000001); - } - - /** - * - * Method: toCentis(double length) - * - */ - @Test - public void testToCentis() throws Exception { - Assert.assertEquals(4, PrintUnit.CENTIMETERS.toMeters(PrintUnit.METERS.toCentis(4)), 0.000001); - Assert.assertEquals(4, PrintUnit.CENTIMETERS.toPoints(PrintUnit.POINTS.toCentis(4)), 0.000001); - } - - /** - * - * Method: toPoints(double length) - * - */ - @Test - public void testToPoints() throws Exception { - Assert.assertEquals(1, PrintUnit.POINTS.toInches(72), 0.00001); - Assert.assertEquals(25.4, PrintUnit.POINTS.toMillis(72), 0.00001); - Assert.assertEquals(1, PrintUnit.MILLIMETERS.toPoints(PrintUnit.POINTS.toMillis(1)), 0.000001); - - Assert.assertEquals(28.3464567, PrintUnit.CENTIMETERS.toPoints(1), 0.000001d); - } - - -} diff --git a/core/test/net/sf/openrocket/gui/print/TestPaperSize.java b/core/test/net/sf/openrocket/gui/print/TestPaperSize.java deleted file mode 100644 index 82677cdc..00000000 --- a/core/test/net/sf/openrocket/gui/print/TestPaperSize.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.sf.openrocket.gui.print; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TestPaperSize { - - @Test - public void testGetDefaultForCountry() { - assertEquals(PaperSize.LETTER, PaperSize.getDefaultForCountry("US")); - assertEquals(PaperSize.LETTER, PaperSize.getDefaultForCountry("cA")); - assertEquals(PaperSize.LETTER, PaperSize.getDefaultForCountry("mx")); - - assertEquals(PaperSize.A4, PaperSize.getDefaultForCountry("FI")); - assertEquals(PaperSize.A4, PaperSize.getDefaultForCountry("xy")); - - assertNull(PaperSize.getDefaultForCountry("FIN")); - assertNull(PaperSize.getDefaultForCountry("a")); - assertNull(PaperSize.getDefaultForCountry("A4")); - assertNull(PaperSize.getDefaultForCountry(null)); - } - - @Test - public void testGetSizeFromString() { - assertEquals(PaperSize.LETTER, PaperSize.getSizeFromString("Letter")); - assertEquals(PaperSize.LEGAL, PaperSize.getSizeFromString(" legal\t")); - assertEquals(PaperSize.A4, PaperSize.getSizeFromString(" A4\n")); - assertEquals(PaperSize.A3, PaperSize.getSizeFromString("A3")); - - assertNull(PaperSize.getSizeFromString("#A4")); - assertNull(PaperSize.getSizeFromString("")); - assertNull(PaperSize.getSizeFromString(null)); - } - -} diff --git a/core/test/net/sf/openrocket/l10n/TestClassBasedTranslator.java b/core/test/net/sf/openrocket/l10n/TestClassBasedTranslator.java deleted file mode 100644 index 254b6619..00000000 --- a/core/test/net/sf/openrocket/l10n/TestClassBasedTranslator.java +++ /dev/null @@ -1,79 +0,0 @@ -package net.sf.openrocket.l10n; - -import static org.junit.Assert.*; - -import java.util.MissingResourceException; - -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.jmock.auto.Mock; -import org.jmock.integration.junit4.JMock; -import org.jmock.integration.junit4.JUnit4Mockery; -import org.junit.Test; -import org.junit.runner.RunWith; - - -@RunWith(JMock.class) -public class TestClassBasedTranslator { - Mockery context = new JUnit4Mockery(); - - @Mock - Translator translator; - - @Test - public void testClassName() { - ClassBasedTranslator cbt = new ClassBasedTranslator(null, 0); - assertEquals("TestClassBasedTranslator", cbt.getClassName()); - - cbt = new ClassBasedTranslator(null, "foobar"); - assertEquals("foobar", cbt.getClassName()); - } - - @Test - public void testGetWithClassName() { - ClassBasedTranslator cbt = new ClassBasedTranslator(translator, 0); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(translator).get("TestClassBasedTranslator.fake.key1"); will(returnValue("foobar")); - }}); - // @formatter:on - - assertEquals("foobar", cbt.get("fake.key1")); - } - - - @Test - public void testGetWithoutClassName() { - ClassBasedTranslator cbt = new ClassBasedTranslator(translator, 0); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(translator).get("TestClassBasedTranslator.fake.key2"); will(throwException(new MissingResourceException("a", "b", "c"))); - oneOf(translator).get("fake.key2"); will(returnValue("barbaz")); - }}); - // @formatter:on - - assertEquals("barbaz", cbt.get("fake.key2")); - } - - - @Test - public void testMissing() { - ClassBasedTranslator cbt = new ClassBasedTranslator(translator, 0); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(translator).get("TestClassBasedTranslator.fake.key3"); will(throwException(new MissingResourceException("a", "b", "c"))); - oneOf(translator).get("fake.key3"); will(throwException(new MissingResourceException("a", "b", "c"))); - }}); - // @formatter:on - - try { - fail("Returned: " + cbt.get("fake.key3")); - } catch (MissingResourceException e) { - assertEquals("Neither key 'TestClassBasedTranslator.fake.key3' nor 'fake.key3' could be found", e.getMessage()); - } - - } -} diff --git a/core/test/net/sf/openrocket/l10n/TestDebugTranslator.java b/core/test/net/sf/openrocket/l10n/TestDebugTranslator.java deleted file mode 100644 index 698094f9..00000000 --- a/core/test/net/sf/openrocket/l10n/TestDebugTranslator.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.sf.openrocket.l10n; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class TestDebugTranslator { - - @Test - public void testGetEnglish() { - DebugTranslator trans = new DebugTranslator(null); - assertEquals("[material:Paper (office)]", trans.get("material", "Paper (office)")); - } - - - @Test - public void testGetBase() { - DebugTranslator trans = new DebugTranslator(null); - assertEquals("Paper (office)", trans.getBaseText("material", "[material:Paper (office)]")); - assertEquals("Papier (toilet)", trans.getBaseText("material", "Papier (toilet)")); - } - - -} diff --git a/core/test/net/sf/openrocket/l10n/TestExceptionSuppressingTranslator.java b/core/test/net/sf/openrocket/l10n/TestExceptionSuppressingTranslator.java deleted file mode 100644 index 1f9e8995..00000000 --- a/core/test/net/sf/openrocket/l10n/TestExceptionSuppressingTranslator.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.sf.openrocket.l10n; - -import static org.junit.Assert.*; - -import java.util.MissingResourceException; - -import net.sf.openrocket.startup.Application; -import net.sf.openrocket.startup.ExceptionHandler; - -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.jmock.auto.Mock; -import org.jmock.integration.junit4.JMock; -import org.jmock.integration.junit4.JUnit4Mockery; -import org.junit.Test; -import org.junit.runner.RunWith; - -@RunWith(JMock.class) -public class TestExceptionSuppressingTranslator { - Mockery context = new JUnit4Mockery(); - - @Mock - Translator translator; - - @Mock - ExceptionHandler exceptionHandler; - - @Test - public void testSuccessful() { - Application.setExceptionHandler(exceptionHandler); - ExceptionSuppressingTranslator est = new ExceptionSuppressingTranslator(translator); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(translator).get("fake.key4"); will(returnValue("foobar")); - }}); - // @formatter:on - - assertEquals("foobar", est.get("fake.key4")); - } - - - @Test - public void testFailure() { - Application.setExceptionHandler(exceptionHandler); - ExceptionSuppressingTranslator est = new ExceptionSuppressingTranslator(translator); - - assertFalse("Prerequisite failed", ExceptionSuppressingTranslator.errorReported); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(exceptionHandler).handleErrorCondition(with(any(String.class)), with(any(MissingResourceException.class))); - oneOf(translator).get("fake.key5"); will(throwException(new MissingResourceException("a", "b", "c"))); - oneOf(translator).get("fake.key5"); will(throwException(new MissingResourceException("a", "b", "c"))); - oneOf(translator).get("fake.key6"); will(throwException(new MissingResourceException("a", "b", "c"))); - }}); - // @formatter:on - - // Test first failure - assertEquals("fake.key5", est.get("fake.key5")); - assertTrue(ExceptionSuppressingTranslator.errorReported); - - // Test second failure - assertEquals("fake.key5", est.get("fake.key5")); - assertTrue(ExceptionSuppressingTranslator.errorReported); - - // Test failure with other key - assertEquals("fake.key6", est.get("fake.key6")); - assertTrue(ExceptionSuppressingTranslator.errorReported); - } - - -} diff --git a/core/test/net/sf/openrocket/l10n/TestL10N.java b/core/test/net/sf/openrocket/l10n/TestL10N.java deleted file mode 100644 index 6194931a..00000000 --- a/core/test/net/sf/openrocket/l10n/TestL10N.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.l10n; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.util.Chars; - -import org.junit.Test; - -public class TestL10N { - - @Test - public void testNormalize() { - assertEquals("hello", L10N.normalize("hello")); - assertEquals("hello", L10N.normalize("Hello")); - assertEquals("hello", L10N.normalize(" \t Hello \n ")); - assertEquals("hello", L10N.normalize("H\u00eall\u00d6")); - assertEquals("hello_world", L10N.normalize("Hello World!")); - assertEquals("hello_world", L10N.normalize("? Hello\nWorld !")); - assertEquals("hello_123", L10N.normalize("Hello 123!")); - assertEquals("hello_123", L10N.normalize("Hello/123?")); - - assertEquals("plywood_birch", L10N.normalize("Plywood (birch)")); - assertEquals("styrofoam_blue_foam_xps", L10N.normalize("Styrofoam \"Blue foam\" (XPS)")); - assertEquals("tubular_nylon_11_mm_7_16_in", L10N.normalize("Tubular nylon (11 mm, 7/16 in)")); - - assertEquals("m2", L10N.normalize("m" + Chars.SQUARED)); - assertEquals("a_b", L10N.normalize("a" + Chars.NBSP + "b")); - assertEquals("1_2a", L10N.normalize(Chars.FRAC12 + "A")); - } -} diff --git a/core/test/net/sf/openrocket/l10n/TestResourceBundleTranslator.java b/core/test/net/sf/openrocket/l10n/TestResourceBundleTranslator.java deleted file mode 100644 index 992bcc2c..00000000 --- a/core/test/net/sf/openrocket/l10n/TestResourceBundleTranslator.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.sf.openrocket.l10n; - -import static org.junit.Assert.*; - -import java.util.Locale; -import java.util.MissingResourceException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class TestResourceBundleTranslator { - - private Locale originalDefaultLocale; - - @Before - public void setup() { - // Default locale affects resource bundles, so set something non-English - this.originalDefaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.GERMAN); - } - - @After - public void teardown() { - Locale.setDefault(originalDefaultLocale); - } - - - @Test - public void testSuccessfulDefault() { - ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages"); - assertEquals("messages_de.properties", trans.get("debug.currentFile")); - } - - @Test - public void testSuccessfulNonDefault() { - ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages", Locale.FRENCH); - assertEquals("messages_fr.properties", trans.get("debug.currentFile")); - } - - @Test - public void testFailure() { - ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages", Locale.US); - try { - fail("Returned: " + trans.get("missing")); - } catch (MissingResourceException e) { - // Expected - } - } - - @Test - public void testGetEnglish() { - ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages", Locale.FRENCH); - assertEquals("Papier (bureau)", trans.get("material", "Paper (office)")); - assertEquals("Paper (toilet)", trans.get("material", "Paper (toilet)")); - } - - - @Test - public void testGetBase() { - ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages", Locale.FRENCH); - assertEquals("Paper (office)", trans.getBaseText("material", "Papier (bureau)")); - assertEquals("Papier (toilet)", trans.getBaseText("material", "Papier (toilet)")); - } - - -} diff --git a/core/test/net/sf/openrocket/logging/CyclicBufferTest.java b/core/test/net/sf/openrocket/logging/CyclicBufferTest.java deleted file mode 100644 index c7672178..00000000 --- a/core/test/net/sf/openrocket/logging/CyclicBufferTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package net.sf.openrocket.logging; - -import static org.junit.Assert.*; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Random; - -import org.junit.Test; - - -public class CyclicBufferTest { - - @Test - public void testBasic() { - CyclicBuffer<Integer> buffer = new CyclicBuffer<Integer>(5); - LinkedList<Integer> correct = new LinkedList<Integer>(); - - Random rnd = new Random(); - for (int i=0; i<50; i++) { - int n = rnd.nextInt(); - buffer.add(n); - correct.add(n); - if (correct.size() > 5) - correct.remove(); - assertEquals(correct, buffer.asList()); - } - } - - @Test - public void testComplex() { - CyclicBuffer<Integer> buffer = new CyclicBuffer<Integer>(5); - - testContents(buffer); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.offer(1); - testContents(buffer, 1); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.add(2); - testContents(buffer, 1, 2); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.add(3); - testContents(buffer, 1, 2, 3); - assertEquals(0, buffer.getOverwriteCount()); - - assertEquals(1, (int)buffer.remove()); - testContents(buffer, 2, 3); - assertEquals(0, buffer.getOverwriteCount()); - - assertEquals(2, (int)buffer.peek()); - testContents(buffer, 2, 3); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.offer(-2); - testContents(buffer, 2, 3, -2); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.offer(-3); - testContents(buffer, 2, 3, -2, -3); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.offer(-4); - testContents(buffer, 2, 3, -2, -3, -4); - assertEquals(0, buffer.getOverwriteCount()); - - buffer.offer(5); - testContents(buffer, 3, -2, -3, -4, 5); - assertEquals(1, buffer.getOverwriteCount()); - - buffer.offer(6); - testContents(buffer, -2, -3, -4, 5, 6); - assertEquals(2, buffer.getOverwriteCount()); - - assertEquals(-2, (int)buffer.peek()); - testContents(buffer, -2, -3, -4, 5, 6); - assertEquals(2, buffer.getOverwriteCount()); - - assertEquals(-2, (int)buffer.remove()); - testContents(buffer, -3, -4, 5, 6); - assertEquals(2, buffer.getOverwriteCount()); - - assertEquals(-3, (int)buffer.remove()); - testContents(buffer, -4, 5, 6); - assertEquals(2, buffer.getOverwriteCount()); - - assertEquals(-4, (int)buffer.poll()); - testContents(buffer, 5, 6); - assertEquals(2, buffer.getOverwriteCount()); - - assertEquals(5, (int)buffer.remove()); - testContents(buffer, 6); - assertEquals(2, buffer.getOverwriteCount()); - - assertEquals(6, (int)buffer.poll()); - testContents(buffer); - assertEquals(2, buffer.getOverwriteCount()); - - assertNull(buffer.peek()); - assertNull(buffer.poll()); - testContents(buffer); - assertEquals(2, buffer.getOverwriteCount()); - } - - - @Test - public void testRandom() { - CyclicBuffer<Integer> buffer = new CyclicBuffer<Integer>(4); - LinkedList<Integer> correct = new LinkedList<Integer>(); - - Random rnd = new Random(); - for (int i=0; i<500; i++) { - - if (rnd.nextBoolean()) { - int n = rnd.nextInt(); - buffer.add(n); - correct.add(n); - if (correct.size() > 4) - correct.remove(); - } else { - Integer n = buffer.poll(); - if (correct.size() > 0) { - assertEquals(correct.remove(), n); - } else { - assertNull(n); - } - } - - assertEquals(correct, buffer.asList()); - } - } - - - private void testContents(CyclicBuffer<Integer> buffer, int ... values) { - - // Test using iterator - Iterator<Integer> iterator = buffer.iterator(); - for (int v: values) { - assertTrue(iterator.hasNext()); - assertEquals(v, (int)iterator.next()); - } - assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException ignore) { } - - // Test using list - List<Integer> list = buffer.asList(); - assertEquals("List: " + list, values.length, list.size()); - for (int i=0; i<values.length; i++) { - assertEquals(values[i], (int)list.get(i)); - } - - } - - -} diff --git a/core/test/net/sf/openrocket/logging/LogLevelBufferLoggerTest.java b/core/test/net/sf/openrocket/logging/LogLevelBufferLoggerTest.java deleted file mode 100644 index 4bd9b8d4..00000000 --- a/core/test/net/sf/openrocket/logging/LogLevelBufferLoggerTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.sf.openrocket.logging; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.Test; - -public class LogLevelBufferLoggerTest { - - @Test - public void testLogger() { - LogLevelBufferLogger logger = new LogLevelBufferLogger(4); - - logger.debug("debug 1"); - logger.debug("debug 2"); - logger.user("user 1"); - logger.info("info 1"); - logger.info("info 2"); - logger.warn("warn 1"); - logger.debug("debug 3"); - logger.debug("debug 4"); - logger.user("user 2"); - logger.info("info 3"); - logger.error("error 1"); - logger.debug("debug 5"); - logger.warn("warn 2"); - logger.debug("debug 6"); - logger.user("user 3"); - logger.info("info 4"); - logger.debug("debug 7"); - logger.info("info 5"); - logger.debug("debug 8"); - logger.info("info 6"); - - List<LogLine> list = logger.getLogs(); - assertEquals(16, list.size()); - - assertEquals("user 1", list.get(0).getMessage()); - assertEquals("warn 1", list.get(1).getMessage()); - assertEquals("user 2", list.get(2).getMessage()); - assertEquals("===== 2 INFO lines removed =====", list.get(3).getMessage()); - assertEquals("info 3", list.get(4).getMessage()); - assertEquals("error 1", list.get(5).getMessage()); - assertEquals("===== 4 DEBUG lines removed =====", list.get(6).getMessage()); - assertEquals("debug 5", list.get(7).getMessage()); - assertEquals("warn 2", list.get(8).getMessage()); - assertEquals("debug 6", list.get(9).getMessage()); - assertEquals("user 3", list.get(10).getMessage()); - assertEquals("info 4", list.get(11).getMessage()); - assertEquals("debug 7", list.get(12).getMessage()); - assertEquals("info 5", list.get(13).getMessage()); - assertEquals("debug 8", list.get(14).getMessage()); - assertEquals("info 6", list.get(15).getMessage()); - - } - -} diff --git a/core/test/net/sf/openrocket/logging/LogLevelTest.java b/core/test/net/sf/openrocket/logging/LogLevelTest.java deleted file mode 100644 index 63c77012..00000000 --- a/core/test/net/sf/openrocket/logging/LogLevelTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.sf.openrocket.logging; - -import static net.sf.openrocket.logging.LogLevel.*; -import static org.junit.Assert.*; - -import org.junit.Test; - -public class LogLevelTest { - - @Test - public void testLevels() { - assertTrue(DEBUG.atLeast(DEBUG)); - assertFalse(DEBUG.atLeast(INFO)); - assertTrue(ERROR.atLeast(WARN)); - - assertTrue(ERROR.moreThan(WARN)); - assertFalse(ERROR.moreThan(ERROR)); - - assertEquals(5, LENGTH); - } - -} diff --git a/core/test/net/sf/openrocket/logging/LoggingTest.java b/core/test/net/sf/openrocket/logging/LoggingTest.java deleted file mode 100644 index 39e4777d..00000000 --- a/core/test/net/sf/openrocket/logging/LoggingTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.sf.openrocket.logging; - -import static org.junit.Assert.*; - -import java.util.List; - -import org.junit.Test; - -public class LoggingTest { - - @Test - public void testLoggers() { - // Ensure a sane stack trace - actualTest(); - } - - private void actualTest() { - BufferLogger log3 = new BufferLogger(3); - BufferLogger log4 = new BufferLogger(4); - - DelegatorLogger delegator = new DelegatorLogger(); - delegator.addLogger(log3); - delegator.addLogger(log4); - - delegator.debug("one"); - delegator.debug("two"); - delegator.info("three"); - delegator.warn(1, "four"); - delegator.error("five"); - - List<LogLine> logs = log4.getLogs(); - assertEquals(4, logs.size()); - assertTrue(logs.get(0).toString(), logs.get(0).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +DEBUG \\(-\\) two")); - assertTrue(logs.get(1).toString(), logs.get(1).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +INFO \\(LoggingTest.java:[0-9]+\\) three")); - assertTrue(logs.get(2).toString(), logs.get(2).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +WARN \\(LoggingTest.java:[0-9]+ LoggingTest.java:[0-9]+\\) four")); - assertTrue(logs.get(3).toString(), logs.get(3).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +ERROR \\(LoggingTest.java:[0-9]+\\) five")); - - logs = log3.getLogs(); - assertEquals(3, logs.size()); - assertTrue(logs.get(0).toString(), logs.get(0).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +INFO \\(LoggingTest.java:[0-9]+\\) three")); - assertTrue(logs.get(1).toString(), logs.get(1).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +WARN \\(LoggingTest.java:[0-9]+ LoggingTest.java:[0-9]+\\) four")); - assertTrue(logs.get(2).toString(), logs.get(2).toString().matches( - " *[0-9]+ +[0-9]+\\.[0-9]+ +ERROR \\(LoggingTest.java:[0-9]+\\) five")); - - } - - public static void main(String[] args) { - PrintStreamLogger logger = new PrintStreamLogger(); - - logger.debug("a debug message"); - logger.info("an info message"); - logger.warn("a warning message"); - logger.error("an error message"); - - logger.debug(4, "Debugging"); - } -} diff --git a/core/test/net/sf/openrocket/logging/TraceExceptionTest.java b/core/test/net/sf/openrocket/logging/TraceExceptionTest.java deleted file mode 100644 index 72f3c13a..00000000 --- a/core/test/net/sf/openrocket/logging/TraceExceptionTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.logging; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class TraceExceptionTest { - - private TraceException getViaAccess() { - - /* - * The SubClass test bases on the fact that getViaAccess method is defined on a row number < 20 - * and the return statement is on a row number > 20. - * - * The JRE sometimes adds an additional "access$NNN" method call between the calls with the - * row number equal to the method definition line. - * - * - * - * - * - * - * - */ - - return new TraceException(0, 1); - } - - - @Test - public void testBasic() { - TraceException trace = new TraceException(); - assertMatch("\\(TraceExceptionTest.java:[2-9][0-9]\\)", trace); - } - - - @Test - public void testOneLevelUp() { - // @formatter:off - these need to be on the same line number - TraceException trace = getOneLevelUp(); TraceException ref = new TraceException(); - // @formatter:on - assertEquals(ref.getMessage(), trace.getMessage()); - } - - private TraceException getOneLevelUp() { - return new TraceException(1); - } - - - @Test - public void testTwoLevels() { - TraceException trace = getTwoLevels(); - assertMatch("\\(TraceExceptionTest.java:[2-9][0-9] TraceExceptionTest.java:[2-9][0-9]\\)", trace); - } - - private TraceException getTwoLevels() { - return new TraceException(0, 1); - } - - - @Test - public void testViaSubclass() { - /* - * This tests that TraceException.getMessage ignores the synthetic "access$0" method calls. - */ - - TraceException trace = new SubClass().getTrace(); - assertMatch("\\(TraceExceptionTest.java:[2-9][0-9] TraceExceptionTest.java:[2-9][0-9]\\)", trace); - } - - private class SubClass { - private TraceException getTrace() { - return getViaAccess(); - } - } - - - - - - private void assertMatch(String regex, TraceException trace) { - boolean match = trace.getMessage().matches(regex); - if (!match) { - trace.printStackTrace(); - assertTrue("Was: " + trace.getMessage(), match); - } - } - -} diff --git a/core/test/net/sf/openrocket/models/gravity/WGSGravityModelTest.java b/core/test/net/sf/openrocket/models/gravity/WGSGravityModelTest.java deleted file mode 100644 index a0aea634..00000000 --- a/core/test/net/sf/openrocket/models/gravity/WGSGravityModelTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.models.gravity; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.util.WorldCoordinate; - -import org.junit.Test; - - -public class WGSGravityModelTest { - - private WGSGravityModel model = new WGSGravityModel(); - - @Test - public void testSurfaceGravity() { - // Equator - test(0, 0, 0, 9.780); - // Mid-latitude - test(45, 0, 0, 9.806); - // Mid-latitude - test(45, 99, 0, 9.806); - // South pole - test(-90, 0, 0, 9.832); - } - - @Test - public void testAltitudeEffect() { - test(45, 0, -100, 9.806); - test(45, 0, 0, 9.806); - test(45, 0, 10, 9.806); - test(45, 0, 100, 9.806); - test(45, 0, 1000, 9.803); - test(45, 0, 10000, 9.775); - test(45, 0, 100000, 9.505); - } - - private void test(double lat, double lon, double alt, double g) { - WorldCoordinate wc = new WorldCoordinate(lat, lon, alt); - assertEquals(g, model.getGravity(wc), 0.001); - assertEquals(g, model.getGravity(wc), 0.001); - } - -} diff --git a/core/test/net/sf/openrocket/motor/ManufacturerTest.java b/core/test/net/sf/openrocket/motor/ManufacturerTest.java deleted file mode 100644 index cd0ce25e..00000000 --- a/core/test/net/sf/openrocket/motor/ManufacturerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.sf.openrocket.motor; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ManufacturerTest { - - @Test - public void testExisting() { - - Manufacturer m1, m2, m3, m4, m5; - - m1 = Manufacturer.getManufacturer("aerotech"); - m2 = Manufacturer.getManufacturer("a "); - m3 = Manufacturer.getManufacturer("-isp-"); - m4 = Manufacturer.getManufacturer("at/rcs"); - m5 = Manufacturer.getManufacturer("e"); - - assertTrue(m1 == m2); - assertTrue(m1 == m3); - assertTrue(m1 == m4); - assertFalse(m1 == m5); - - } - - public void testContrail() { - Manufacturer c1, c2; - - c1 = Manufacturer.getManufacturer("Contrail" ); - - // Used in rsp files. - c2 = Manufacturer.getManufacturer("Contrail_Rockets"); - - assertNotNull(c1); - assertEquals(c1,c2); - } - - @Test - public void testNew() { - - Manufacturer m1, m2, m3; - - m1 = Manufacturer.getManufacturer("Unknown"); - m2 = Manufacturer.getManufacturer(" Unknown/ "); - m3 = Manufacturer.getManufacturer("Unknown/a"); - - assertEquals(m1.getDisplayName(), "Unknown"); - assertEquals(m2.getDisplayName(), "Unknown"); - assertTrue(m1 == m2); - - assertEquals(m3.getDisplayName(), "Unknown/a"); - assertFalse(m1 == m3); - - } - - @Test - public void testSimpleName() { - - Manufacturer m1, m2, m3, m4; - - m1 = Manufacturer.getManufacturer("cs"); - m2 = Manufacturer.getManufacturer("Cesaroni Technology"); - m3 = Manufacturer.getManufacturer("Cesaroni Technology Inc"); - m4 = Manufacturer.getManufacturer("Cesaroni Technology Inc."); - - assertEquals(m1.getDisplayName(), "Cesaroni Technology Inc."); - assertEquals(m1.toString(), "Cesaroni Technology Inc."); - assertEquals(m1.getSimpleName(), "Cesaroni Technology"); - - assertTrue(m1 == m2); - assertTrue(m1 == m3); - assertTrue(m1 == m4); - - } - - @Test - public void testMatches() { - - Manufacturer m1; - - m1 = Manufacturer.getManufacturer("aerotech"); - - assertTrue(m1.matches("a")); - assertTrue(m1.matches("a/")); - assertTrue(m1.matches("a/rcs")); - assertTrue(m1.matches("a/rms")); - assertTrue(m1.matches("aerotech ...-/%#_!")); - assertTrue(m1.matches(" .isp/")); - - assertFalse(m1.matches("aero/tech")); - assertFalse(m1.matches("aero.tech")); - assertFalse(m1.matches("aero_tech")); - assertFalse(m1.matches("aero tech")); - } - -} diff --git a/core/test/net/sf/openrocket/motor/MotorDigestTest.java b/core/test/net/sf/openrocket/motor/MotorDigestTest.java deleted file mode 100644 index 916ab12c..00000000 --- a/core/test/net/sf/openrocket/motor/MotorDigestTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package net.sf.openrocket.motor; - -import static org.junit.Assert.assertEquals; - -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import net.sf.openrocket.motor.MotorDigest.DataType; -import net.sf.openrocket.util.TextUtil; - -import org.junit.Test; - - -public class MotorDigestTest { - - private static final double[] timeArray = { - 0.0, 0.123456789, 0.4115, Math.nextAfter(Math.nextAfter(1.4445, 0), 0) - }; - - private static final double[] massArray = { - 0.54321, 0.43211 - }; - - private static final double[] thrustArray = { - 0.0, 0.2345678, 9999.3335, 0.0 - }; - - private static final int[] intData = { - // Time (ms) - 0, 4, 0, 123, 412, 1445, - // Mass specific (0.1g) - 1, 2, 5432, 4321, - // Thrust (mN) - 5, 4, 0, 235, 9999334, 0 - }; - - - @Test - public void testMotorDigest() throws NoSuchAlgorithmException { - - MessageDigest correct = MessageDigest.getInstance("MD5"); - for (int value: intData) { - correct.update((byte) ((value >>> 24) & 0xFF)); - correct.update((byte) ((value >>> 16) & 0xFF)); - correct.update((byte) ((value >>> 8) & 0xFF)); - correct.update((byte) (value & 0xFF)); - } - - MotorDigest motor = new MotorDigest(); - motor.update(DataType.TIME_ARRAY, timeArray); - motor.update(DataType.MASS_SPECIFIC, massArray); - motor.update(DataType.FORCE_PER_TIME, thrustArray); - - - assertEquals(TextUtil.hexString(correct.digest()), motor.getDigest()); - } - - - @Test - public void testCommentDigest() throws NoSuchAlgorithmException, UnsupportedEncodingException { - - assertEquals(md5("Hello world!"), MotorDigest.digestComment("Hello world! ")); - assertEquals(md5("Hello world!"), MotorDigest.digestComment("\nHello\tworld!\n\r")); - assertEquals(md5("Hello world!"), MotorDigest.digestComment("Hello\r\r\r\nworld!")); - assertEquals(md5("Hello\u00e4 world!"), MotorDigest.digestComment("Hello\u00e4\r\r\nworld!")); - - } - - - private static String md5(String source) - throws NoSuchAlgorithmException, UnsupportedEncodingException { - MessageDigest digest = MessageDigest.getInstance("MD5"); - return TextUtil.hexString(digest.digest(source.getBytes("UTF-8"))); - } -} diff --git a/core/test/net/sf/openrocket/motor/ThrustCurveMotorTest.java b/core/test/net/sf/openrocket/motor/ThrustCurveMotorTest.java deleted file mode 100644 index 327ec375..00000000 --- a/core/test/net/sf/openrocket/motor/ThrustCurveMotorTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.sf.openrocket.motor; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.Inertia; - -import org.junit.Test; - -public class ThrustCurveMotorTest { - - private final double EPS = 0.000001; - - private final double radius = 0.025; - private final double length = 0.10; - private final double longitudinal = Inertia.filledCylinderLongitudinal(radius, length); - private final double rotational = Inertia.filledCylinderRotational(radius); - - private final ThrustCurveMotor motor = - new ThrustCurveMotor(Manufacturer.getManufacturer("foo"), - "X6", "Description of X6", Motor.Type.RELOAD, - new double[] {0, 2, Motor.PLUGGED}, radius*2, length, - new double[] {0, 1, 3, 4}, // time - new double[] {0, 2, 3, 0}, // thrust - new Coordinate[] { - new Coordinate(0.02,0,0,0.05), - new Coordinate(0.02,0,0,0.05), - new Coordinate(0.02,0,0,0.05), - new Coordinate(0.03,0,0,0.03) - }, "digestA"); - - @Test - public void testMotorData() { - - assertEquals("X6", motor.getDesignation()); - assertEquals("X6-5", motor.getDesignation(5.0)); - assertEquals("Description of X6", motor.getDescription()); - assertEquals(Motor.Type.RELOAD, motor.getMotorType()); - - } - - @Test - public void testInstance() { - MotorInstance instance = motor.getInstance(); - - verify(instance, 0, 0.05, 0.02); - instance.step(0.0, 0, null); - verify(instance, 0, 0.05, 0.02); - instance.step(0.5, 0, null); - verify(instance, 0.5, 0.05, 0.02); - instance.step(1.5, 0, null); - verify(instance, (1.5 + 2.125)/2, 0.05, 0.02); - instance.step(2.5, 0, null); - verify(instance, (2.125 + 2.875)/2, 0.05, 0.02); - instance.step(3.0, 0, null); - verify(instance, (2+3.0/4 + 3)/2, 0.05, 0.02); - instance.step(3.5, 0, null); - verify(instance, (1.5 + 3)/2, 0.045, 0.0225); - instance.step(4.5, 0, null); - // mass and cg is simply average of the end points - verify(instance, 1.5/4, 0.035, 0.0275); - instance.step(5.0, 0, null); - verify(instance, 0, 0.03, 0.03); - } - - private void verify(MotorInstance instance, double thrust, double mass, double cgx) { - assertEquals("Testing thrust", thrust, instance.getThrust(), EPS); - assertEquals("Testing mass", mass, instance.getCG().weight, EPS); - assertEquals("Testing cg x", cgx, instance.getCG().x, EPS); - assertEquals("Testing longitudinal inertia", mass*longitudinal, instance.getLongitudinalInertia(), EPS); - assertEquals("Testing rotational inertia", mass*rotational, instance.getRotationalInertia(), EPS); - } - - -} diff --git a/core/test/net/sf/openrocket/optimization/TestSearchPattern.java b/core/test/net/sf/openrocket/optimization/TestSearchPattern.java deleted file mode 100644 index fcb618b8..00000000 --- a/core/test/net/sf/openrocket/optimization/TestSearchPattern.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.optimization; - -import static org.junit.Assert.*; - -import java.util.List; - -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.optimization.general.multidim.SearchPattern; - -import org.junit.Test; - -public class TestSearchPattern { - - @Test - public void testRegularSimplex() { - for (int dim = 1; dim < 20; dim++) { - List<Point> points = SearchPattern.regularSimplex(dim); - assertEquals(dim, points.size()); - - for (int i = 0; i < dim; i++) { - // Test dot product - for (int j = i + 1; j < dim; j++) { - double[] x = points.get(i).asArray(); - double[] y = points.get(j).asArray(); - double dot = 0; - for (int k = 0; k < dim; k++) { - dot += x[k] * y[k]; - } - assertEquals(0.5, dot, 0.000000001); - } - - // Test positive coordinates - for (int j = 0; j < dim; j++) { - assertTrue(points.get(i).get(j) >= 0); - } - - // Test length - assertEquals(1.0, points.get(i).length(), 0.000000001); - } - } - } - -} diff --git a/core/test/net/sf/openrocket/optimization/rocketoptimization/TestRocketOptimizationFunction.java b/core/test/net/sf/openrocket/optimization/rocketoptimization/TestRocketOptimizationFunction.java deleted file mode 100644 index 48cc648b..00000000 --- a/core/test/net/sf/openrocket/optimization/rocketoptimization/TestRocketOptimizationFunction.java +++ /dev/null @@ -1,212 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization; - -import static org.junit.Assert.*; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.optimization.general.Point; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.unit.Value; -import net.sf.openrocket.util.Pair; - -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.jmock.auto.Mock; -import org.jmock.integration.junit4.JMock; -import org.jmock.integration.junit4.JUnit4Mockery; -import org.junit.Test; -import org.junit.runner.RunWith; - - -@RunWith(JMock.class) -public class TestRocketOptimizationFunction { - Mockery context = new JUnit4Mockery(); - - @Mock - OptimizableParameter parameter; - @Mock - OptimizationGoal goal; - @Mock - SimulationDomain domain; - @Mock - SimulationModifier modifier1; - @Mock - SimulationModifier modifier2; - @Mock - RocketOptimizationListener listener; - - @Test - public void testNormalEvaluation() throws InterruptedException, OptimizationException { - final Rocket rocket = new Rocket(); - final Simulation simulation = new Simulation(rocket); - - final double p1 = 0.4; - final double p2 = 0.7; - final double ddist = -0.43; - final Value dref = new Value(ddist, Unit.NOUNIT2); - final double pvalue = 9.81; - final Value pvalueValue = new Value(9.81, Unit.NOUNIT2); - final double gvalue = 8.81; - final Point point = new Point(p1, p2); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(modifier1).modify(simulation, p1); - oneOf(modifier2).modify(simulation, p2); - oneOf(domain).getDistanceToDomain(simulation); will(returnValue(new Pair<Double,Value>(ddist, dref))); - oneOf(parameter).computeValue(simulation); will(returnValue(pvalue)); - oneOf(parameter).getUnitGroup(); will(returnValue(UnitGroup.UNITS_NONE)); - oneOf(goal).getMinimizationParameter(pvalue); will(returnValue(gvalue)); - oneOf(modifier1).getCurrentSIValue(simulation); will(returnValue(0.2)); - oneOf(modifier1).getUnitGroup(); will(returnValue(UnitGroup.UNITS_LENGTH)); - oneOf(modifier2).getCurrentSIValue(simulation); will(returnValue(0.3)); - oneOf(modifier2).getUnitGroup(); will(returnValue(UnitGroup.UNITS_LENGTH)); - oneOf(listener).evaluated(point, new Value[] { - new Value(0.2, UnitGroup.UNITS_LENGTH.getDefaultUnit()), - new Value(0.3, UnitGroup.UNITS_LENGTH.getDefaultUnit()) - }, dref, pvalueValue, gvalue); - }}); - // @formatter:on - - RocketOptimizationFunction function = new RocketOptimizationFunction(simulation, - parameter, goal, domain, modifier1, modifier2) { - @Override - Simulation newSimulationInstance(Simulation sim) { - return sim; - } - }; - function.addRocketOptimizationListener(listener); - - double value = function.evaluate(point); - assertEquals(gvalue, value, 0); - } - - @Test - public void testNaNValue() throws InterruptedException, OptimizationException { - final Rocket rocket = new Rocket(); - final Simulation simulation = new Simulation(rocket); - - final double p1 = 0.4; - final double p2 = 0.7; - final double ddist = -0.43; - final Value dref = new Value(0.33, Unit.NOUNIT2); - final double pvalue = 9.81; - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(modifier1).modify(simulation, p1); - oneOf(modifier2).modify(simulation, p2); - oneOf(domain).getDistanceToDomain(simulation); will(returnValue(new Pair<Double,Value>(ddist, dref))); - oneOf(parameter).computeValue(simulation); will(returnValue(pvalue)); - oneOf(parameter).getUnitGroup(); will(returnValue(UnitGroup.UNITS_NONE)); - oneOf(goal).getMinimizationParameter(pvalue); will(returnValue(Double.NaN)); - }}); - // @formatter:on - - - RocketOptimizationFunction function = new RocketOptimizationFunction(simulation, - parameter, goal, domain, modifier1, modifier2) { - @Override - Simulation newSimulationInstance(Simulation sim) { - return sim; - } - }; - - - double value = function.evaluate(new Point(p1, p2)); - assertEquals(Double.MAX_VALUE, value, 0); - } - - - @Test - public void testOutsideDomain() throws InterruptedException, OptimizationException { - final Rocket rocket = new Rocket(); - final Simulation simulation = new Simulation(rocket); - - final double p1 = 0.4; - final double p2 = 0.7; - final double ddist = 0.98; - final Value dref = new Value(ddist, Unit.NOUNIT2); - final Point point = new Point(p1, p2); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(modifier1).modify(simulation, p1); - oneOf(modifier2).modify(simulation, p2); - oneOf(domain).getDistanceToDomain(simulation); will(returnValue(new Pair<Double,Value>(ddist, dref))); - oneOf(modifier1).getCurrentSIValue(simulation); will(returnValue(0.2)); - oneOf(modifier1).getUnitGroup(); will(returnValue(UnitGroup.UNITS_LENGTH)); - oneOf(modifier2).getCurrentSIValue(simulation); will(returnValue(0.3)); - oneOf(modifier2).getUnitGroup(); will(returnValue(UnitGroup.UNITS_LENGTH)); - oneOf(listener).evaluated(point, new Value[] { - new Value(0.2, UnitGroup.UNITS_LENGTH.getDefaultUnit()), - new Value(0.3, UnitGroup.UNITS_LENGTH.getDefaultUnit()) - }, dref, null, 1.98E200); - }}); - // @formatter:on - - - RocketOptimizationFunction function = new RocketOptimizationFunction(simulation, - parameter, goal, domain, modifier1, modifier2) { - @Override - Simulation newSimulationInstance(Simulation sim) { - return sim; - } - }; - function.addRocketOptimizationListener(listener); - - double value = function.evaluate(new Point(p1, p2)); - assertTrue(value > 1e100); - } - - @Test - public void testOutsideDomain2() throws InterruptedException, OptimizationException { - final Rocket rocket = new Rocket(); - final Simulation simulation = new Simulation(rocket); - - final double p1 = 0.4; - final double p2 = 0.7; - final double ddist = Double.NaN; - final Value dref = new Value(0.33, Unit.NOUNIT2); - - // @formatter:off - context.checking(new Expectations() {{ - oneOf(modifier1).modify(simulation, p1); - oneOf(modifier2).modify(simulation, p2); - oneOf(domain).getDistanceToDomain(simulation); will(returnValue(new Pair<Double,Value>(ddist, dref))); - }}); - // @formatter:on - - - RocketOptimizationFunction function = new RocketOptimizationFunction(simulation, - parameter, goal, domain, modifier1, modifier2) { - @Override - Simulation newSimulationInstance(Simulation sim) { - return sim; - } - }; - - double value = function.evaluate(new Point(p1, p2)); - assertEquals(Double.MAX_VALUE, value, 0); - } - - - @Test - public void testNewSimulationInstance() { - final Rocket rocket = new Rocket(); - rocket.setName("Foobar"); - final Simulation simulation = new Simulation(rocket); - simulation.setName("MySim"); - - RocketOptimizationFunction function = new RocketOptimizationFunction(simulation, - parameter, goal, domain, modifier1, modifier2); - - Simulation sim = function.newSimulationInstance(simulation); - assertFalse(simulation == sim); - assertEquals("MySim", sim.getName()); - assertFalse(rocket == sim.getRocket()); - assertEquals("Foobar", sim.getRocket().getName()); - } - -} diff --git a/core/test/net/sf/openrocket/optimization/rocketoptimization/modifiers/TestGenericModifier.java b/core/test/net/sf/openrocket/optimization/rocketoptimization/modifiers/TestGenericModifier.java deleted file mode 100644 index deacacf4..00000000 --- a/core/test/net/sf/openrocket/optimization/rocketoptimization/modifiers/TestGenericModifier.java +++ /dev/null @@ -1,102 +0,0 @@ -package net.sf.openrocket.optimization.rocketoptimization.modifiers; - -import static net.sf.openrocket.util.MathUtil.EPSILON; -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.optimization.general.OptimizationException; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.unit.UnitGroup; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class TestGenericModifier { - - private TestValue value; - private GenericModifier<TestValue> gm; - private Simulation sim; - - @Before - public void setup() { - value = new TestValue(); - sim = new Simulation(new Rocket()); - - Object related = new Object(); - - gm = new GenericModifier<TestGenericModifier.TestValue>("Test modifier", "Description", related, - UnitGroup.UNITS_NONE, 2.0, TestValue.class, "value") { - @Override - protected TestValue getModifiedObject(Simulation simulation) { - Assert.assertTrue(simulation == sim); - return value; - } - }; - - gm.setMinValue(0.5); - gm.setMaxValue(5.5); - } - - @Test - public void testGetCurrentValue() throws OptimizationException { - value.d = 1.0; - assertEquals(2.0, gm.getCurrentSIValue(sim), EPSILON); - value.d = 2.0; - assertEquals(4.0, gm.getCurrentSIValue(sim), EPSILON); - } - - @Test - public void testGetCurrentScaledValue() throws OptimizationException { - value.d = 0.0; - assertEquals(-0.1, gm.getCurrentScaledValue(sim), EPSILON); - value.d = 1.0; - assertEquals(0.3, gm.getCurrentScaledValue(sim), EPSILON); - value.d = 2.0; - assertEquals(0.7, gm.getCurrentScaledValue(sim), EPSILON); - value.d = 3.0; - assertEquals(1.1, gm.getCurrentScaledValue(sim), EPSILON); - } - - @Test - public void testModify() throws OptimizationException { - value.d = 0.0; - gm.modify(sim, -0.5); - assertEquals(-1.0, value.d, EPSILON); - - gm.modify(sim, 0.0); - assertEquals(0.25, value.d, EPSILON); - - gm.modify(sim, 0.5); - assertEquals(1.5, value.d, EPSILON); - - gm.modify(sim, 1.0); - assertEquals(2.75, value.d, EPSILON); - - gm.modify(sim, 1.5); - assertEquals(4.0, value.d, EPSILON); - } - - public void testSingularRange() throws OptimizationException { - gm.setMinValue(1.0); - gm.setMaxValue(1.0); - value.d = 0.5; - assertEquals(0.0, gm.getCurrentScaledValue(sim), EPSILON); - value.d = 1.0; - assertEquals(0.5, gm.getCurrentScaledValue(sim), EPSILON); - value.d = 1.00001; - assertEquals(1.0, gm.getCurrentScaledValue(sim), EPSILON); - } - - public class TestValue { - private double d; - - public double getValue() { - return d; - } - - public void setValue(double value) { - this.d = value; - } - } - -} diff --git a/core/test/net/sf/openrocket/preset/BodyTubeComponentTests.java b/core/test/net/sf/openrocket/preset/BodyTubeComponentTests.java deleted file mode 100644 index 891d9ed3..00000000 --- a/core/test/net/sf/openrocket/preset/BodyTubeComponentTests.java +++ /dev/null @@ -1,142 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.BodyTube; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to BodyTube RocketComponents through - * the BodyTube.loadFromPreset mechanism. - * - * Test BodyTube is well defined. - * - * Test calling setters on BodyTube will clear the ComponentPreset. - * - */ -public class BodyTubeComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - BodyTube bt = new BodyTube(); - - assertSame(ComponentPreset.Type.BODY_TUBE, bt.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - assertEquals(2.0, bt.getLength(), 0.0); - assertEquals(1.0, bt.getOuterRadius(), 0.0); - assertEquals(1.0, bt.getAftRadius(), 0.0); - assertEquals(0.5, bt.getInnerRadius(), 0.0); - - assertFalse(bt.isAftRadiusAutomatic()); - assertFalse(bt.isFilled()); - assertFalse(bt.isForeRadiusAutomatic()); - assertFalse(bt.isOuterRadiusAutomatic()); - - assertSame(preset.get(ComponentPreset.MATERIAL), bt.getMaterial()); - assertEquals(100.0, bt.getMass(), 0.05); - } - - @Test - public void changeLengthLeavesPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setLength(1.0); - - assertSame(preset, bt.getPresetComponent()); - } - - @Test - public void changeODClearsPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setOuterRadius(2.0); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeIDClearsPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setInnerRadius(0.75); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setThickness(0.1); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeFinishLeavesPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setFinish(Finish.POLISHED); - - assertSame(preset, bt.getPresetComponent()); - } - - @Test - public void changeFillClearsPreset() { - BodyTube bt = new BodyTube(); - - bt.loadPreset(preset); - - bt.setFilled(true); - - assertNull(bt.getPresetComponent()); - } -} diff --git a/core/test/net/sf/openrocket/preset/BodyTubePresetTests.java b/core/test/net/sf/openrocket/preset/BodyTubePresetTests.java deleted file mode 100644 index 33d75293..00000000 --- a/core/test/net/sf/openrocket/preset/BodyTubePresetTests.java +++ /dev/null @@ -1,271 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of BODY_TUBE type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class BodyTubePresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH - }, - new String[] { - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyOuterDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyInnerDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyThicknessDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testComputeInnerDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(1.0, preset.get(ComponentPreset.INNER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeOuterDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(2.0, preset.get(ComponentPreset.OUTER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeThickness() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeThicknessLooses() throws Exception { - // If all OUTER_DIAMETER, INNER_DIAMETER and THICKNESS are - // specified, THICKNESS is recomputed. - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 15.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("TubeCustom", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - -} diff --git a/core/test/net/sf/openrocket/preset/BulkHeadComponentTests.java b/core/test/net/sf/openrocket/preset/BulkHeadComponentTests.java deleted file mode 100644 index 6a1c8463..00000000 --- a/core/test/net/sf/openrocket/preset/BulkHeadComponentTests.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.Bulkhead; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to Bulkhead RocketComponents through - * the Bulkhead.loadFromPreset mechanism. - * - * Test Bulkhead is well defined. - * - * Test calling setters on Bulkhead will clear the ComponentPreset. - * - */ -public class BulkHeadComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.MASS, 100.0); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - Bulkhead bt = new Bulkhead(); - - assertSame(ComponentPreset.Type.BULK_HEAD, bt.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - Bulkhead bt = new Bulkhead(); - - bt.loadPreset(preset); - - assertEquals(2.0, bt.getLength(), 0.0); - assertEquals(1.0, bt.getOuterRadius(), 0.0); - - assertFalse(bt.isOuterRadiusAutomatic()); - - assertSame(preset.get(ComponentPreset.MATERIAL), bt.getMaterial()); - assertEquals(100.0, bt.getMass(), 0.05); - } - - @Test - public void changeLengthLeavesPreset() { - Bulkhead bt = new Bulkhead(); - - bt.loadPreset(preset); - - bt.setLength(1.0); - - assertSame(preset, bt.getPresetComponent()); - } - - @Test - public void changeODClearsPreset() { - Bulkhead bt = new Bulkhead(); - - bt.loadPreset(preset); - - bt.setOuterRadius(2.0); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeODAutomaticClearsPreset() { - Bulkhead bt = new Bulkhead(); - - bt.loadPreset(preset); - - bt.setOuterRadiusAutomatic(true); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - Bulkhead bt = new Bulkhead(); - - bt.loadPreset(preset); - - bt.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(bt.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/BulkHeadPresetTests.java b/core/test/net/sf/openrocket/preset/BulkHeadPresetTests.java deleted file mode 100644 index 2f393bac..00000000 --- a/core/test/net/sf/openrocket/preset/BulkHeadPresetTests.java +++ /dev/null @@ -1,173 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of BULK_HEAD type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class BulkHeadPresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.OUTER_DIAMETER - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "No OuterDiameter specified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.OUTER_DIAMETER - }, - new String[] { - "No PartNo specified", - "No Length specified", - "No OuterDiameter specified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH, - ComponentPreset.OUTER_DIAMETER - }, - new String[] { - "No Length specified", - "No OuterDiameter specified" - } - ); - } - } - - @Test - public void testOuterDiameterRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.OUTER_DIAMETER - }, - new String[] { - "No OuterDiameter specified" - } - ); - } - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("BulkHeadCustom", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BULK_HEAD); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - -} diff --git a/core/test/net/sf/openrocket/preset/CenteringRingComponentTests.java b/core/test/net/sf/openrocket/preset/CenteringRingComponentTests.java deleted file mode 100644 index dac3f8fd..00000000 --- a/core/test/net/sf/openrocket/preset/CenteringRingComponentTests.java +++ /dev/null @@ -1,116 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.CenteringRing; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to CenteringRing RocketComponents through - * the CenteringRing.loadFromPreset mechanism. - * - * Test CenteringRing is well defined. - * - * Test calling setters on CenteringRing will clear the ComponentPreset. - * - */ -public class CenteringRingComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - CenteringRing cr = new CenteringRing(); - - assertSame(ComponentPreset.Type.CENTERING_RING, cr.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - CenteringRing cr = new CenteringRing(); - - cr.loadPreset(preset); - - assertEquals(2.0, cr.getLength(), 0.0); - assertEquals(1.0, cr.getOuterRadius(), 0.0); - assertEquals(0.5, cr.getInnerRadius(), 0.0); - - assertFalse(cr.isOuterRadiusAutomatic()); - - assertSame(preset.get(ComponentPreset.MATERIAL), cr.getMaterial()); - assertEquals(100.0, cr.getMass(), 0.05); - } - - @Test - public void changeLengthLeavesPreset() { - CenteringRing cr = new CenteringRing(); - - cr.loadPreset(preset); - - cr.setLength(1.0); - - assertSame(preset, cr.getPresetComponent()); - } - - @Test - public void changeODClearsPreset() { - CenteringRing cr = new CenteringRing(); - - cr.loadPreset(preset); - - cr.setOuterRadius(2.0); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeIDClearsPreset() { - CenteringRing cr = new CenteringRing(); - - cr.loadPreset(preset); - - cr.setInnerRadius(0.75); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - CenteringRing cr = new CenteringRing(); - - cr.loadPreset(preset); - - cr.setThickness(0.1); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - CenteringRing cr = new CenteringRing(); - - cr.loadPreset(preset); - - cr.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(cr.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/CenteringRingPresetTests.java b/core/test/net/sf/openrocket/preset/CenteringRingPresetTests.java deleted file mode 100644 index 718e4be5..00000000 --- a/core/test/net/sf/openrocket/preset/CenteringRingPresetTests.java +++ /dev/null @@ -1,271 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of CENTERING_RING type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class CenteringRingPresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH - }, - new String[] { - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyOuterDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyInnerDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyThicknessDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testComputeInnerDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(1.0, preset.get(ComponentPreset.INNER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeOuterDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(2.0, preset.get(ComponentPreset.OUTER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeThickness() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeThicknessLooses() throws Exception { - // If all OUTER_DIAMETER, INNER_DIAMETER and THICKNESS are - // specified, THICKNESS is recomputed. - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 15.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("CenteringRingCustom", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.CENTERING_RING); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - -} diff --git a/core/test/net/sf/openrocket/preset/EngineBlockComponentTests.java b/core/test/net/sf/openrocket/preset/EngineBlockComponentTests.java deleted file mode 100644 index 759a3b7b..00000000 --- a/core/test/net/sf/openrocket/preset/EngineBlockComponentTests.java +++ /dev/null @@ -1,116 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.EngineBlock; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to EngineBlock RocketComponents through - * the EngineBlock.loadFromPreset mechanism. - * - * Test EngineBlock is well defined. - * - * Test calling setters on EngineBlock will clear the ComponentPreset. - * - */ -public class EngineBlockComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - EngineBlock eb = new EngineBlock(); - - assertSame(ComponentPreset.Type.ENGINE_BLOCK, eb.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - EngineBlock eb = new EngineBlock(); - - eb.loadPreset(preset); - - assertEquals(2.0, eb.getLength(), 0.0); - assertEquals(1.0, eb.getOuterRadius(), 0.0); - assertEquals(0.5, eb.getInnerRadius(), 0.0); - - assertFalse(eb.isOuterRadiusAutomatic()); - - assertSame(preset.get(ComponentPreset.MATERIAL), eb.getMaterial()); - assertEquals(100.0, eb.getMass(), 0.05); - } - - @Test - public void changeLengthLeavesPreset() { - EngineBlock eb = new EngineBlock(); - - eb.loadPreset(preset); - - eb.setLength(1.0); - - assertSame(preset, eb.getPresetComponent()); - } - - @Test - public void changeODClearsPreset() { - EngineBlock eb = new EngineBlock(); - - eb.loadPreset(preset); - - eb.setOuterRadius(2.0); - - assertNull(eb.getPresetComponent()); - } - - @Test - public void changeIDClearsPreset() { - EngineBlock eb = new EngineBlock(); - - eb.loadPreset(preset); - - eb.setInnerRadius(0.75); - - assertNull(eb.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - EngineBlock eb = new EngineBlock(); - - eb.loadPreset(preset); - - eb.setThickness(0.1); - - assertNull(eb.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - EngineBlock eb = new EngineBlock(); - - eb.loadPreset(preset); - - eb.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(eb.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/EngineBlockPresetTests.java b/core/test/net/sf/openrocket/preset/EngineBlockPresetTests.java deleted file mode 100644 index d032b513..00000000 --- a/core/test/net/sf/openrocket/preset/EngineBlockPresetTests.java +++ /dev/null @@ -1,271 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of ENGINE_BLOCK type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class EngineBlockPresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH - }, - new String[] { - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyOuterDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyInnerDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyThicknessDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testComputeInnerDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(1.0, preset.get(ComponentPreset.INNER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeOuterDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(2.0, preset.get(ComponentPreset.OUTER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeThickness() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeThicknessLooses() throws Exception { - // If all OUTER_DIAMETER, INNER_DIAMETER and THICKNESS are - // specified, THICKNESS is recomputed. - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 15.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("EngineBlockCustom", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.ENGINE_BLOCK); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - -} diff --git a/core/test/net/sf/openrocket/preset/LaunchLugComponentTests.java b/core/test/net/sf/openrocket/preset/LaunchLugComponentTests.java deleted file mode 100644 index e232aa62..00000000 --- a/core/test/net/sf/openrocket/preset/LaunchLugComponentTests.java +++ /dev/null @@ -1,126 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.LaunchLug; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to LaunchLug RocketComponents through - * the LaunchLug.loadFromPreset mechanism. - * - * Test LaunchLug is well defined. - * - * Test calling setters on LaunchLug will clear the ComponentPreset. - * - */ -public class LaunchLugComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - LaunchLug bt = new LaunchLug(); - - assertSame(ComponentPreset.Type.LAUNCH_LUG, bt.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - assertEquals(2.0, bt.getLength(), 0.0); - assertEquals(1.0, bt.getOuterRadius(), 0.0); - assertEquals(0.5, bt.getInnerRadius(), 0.0); - - assertSame(preset.get(ComponentPreset.MATERIAL), bt.getMaterial()); - assertEquals(100.0, bt.getMass(), 0.05); - } - - @Test - public void changeLengthLeavesPreset() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - bt.setLength(1.0); - - assertSame(preset, bt.getPresetComponent()); - } - - @Test - public void changeODClearsPreset() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - bt.setOuterRadius(2.0); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeIDClearsPreset() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - bt.setInnerRadius(0.75); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - bt.setThickness(0.1); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - bt.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(bt.getPresetComponent()); - } - - @Test - public void changeFinishLeavesPreset() { - LaunchLug bt = new LaunchLug(); - - bt.loadPreset(preset); - - bt.setFinish(Finish.POLISHED); - - assertSame(preset, bt.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/LaunchLugPresetTests.java b/core/test/net/sf/openrocket/preset/LaunchLugPresetTests.java deleted file mode 100644 index 207931d3..00000000 --- a/core/test/net/sf/openrocket/preset/LaunchLugPresetTests.java +++ /dev/null @@ -1,271 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of LAUNCH_LUG type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class LaunchLugPresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH - }, - new String[] { - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyOuterDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyInnerDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyThicknessDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testComputeInnerDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(1.0, preset.get(ComponentPreset.INNER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeOuterDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(2.0, preset.get(ComponentPreset.OUTER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeThickness() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeThicknessLooses() throws Exception { - // If all OUTER_DIAMETER, INNER_DIAMETER and THICKNESS are - // specified, THICKNESS is recomputed. - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 15.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("TubeCustom", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.LAUNCH_LUG); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - -} diff --git a/core/test/net/sf/openrocket/preset/NoseConeComponentTests.java b/core/test/net/sf/openrocket/preset/NoseConeComponentTests.java deleted file mode 100644 index 37f7dd4e..00000000 --- a/core/test/net/sf/openrocket/preset/NoseConeComponentTests.java +++ /dev/null @@ -1,174 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to NoseCone RocketComponents through - * the NoseCone.loadFromPreset mechanism. - * - * Test NoseCone is well defined. - * - * Test calling setters on NoseCone will clear the ComponentPreset. - * - */ -public class NoseConeComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.AFT_SHOULDER_LENGTH, 1.0); - presetspec.put(ComponentPreset.AFT_SHOULDER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - NoseCone nc = new NoseCone(); - - assertSame(ComponentPreset.Type.NOSE_CONE, nc.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - assertEquals(2.0, nc.getLength(), 0.0); - assertSame(Transition.Shape.CONICAL, nc.getType()); - assertEquals(1.0, nc.getAftRadius(), 0.0); - assertEquals(0.0, nc.getForeShoulderLength(), 0.0); - assertEquals(0.0, nc.getForeShoulderRadius(), 0.0); - assertEquals(1.0, nc.getAftShoulderLength(), 0.0); - assertEquals(0.5, nc.getAftShoulderRadius(), 0.0); - assertEquals(0.5, nc.getAftShoulderThickness(), 0.0); - - assertFalse(nc.isForeRadiusAutomatic()); - assertFalse(nc.isAftRadiusAutomatic()); - assertTrue(nc.isFilled()); - - assertSame(preset.get(ComponentPreset.MATERIAL), nc.getMaterial()); - assertEquals(100.0, nc.getMass(), 0.05); - } - - @Test - public void changeLengthClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setLength(1.0); - - assertNull(nc.getPresetComponent()); - } - - @Test - public void changeAftRadiusClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setAftRadius(2.0); - - assertNull(nc.getPresetComponent()); - } - - @Test - public void changeAftRadiusAutomaticClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setAftRadiusAutomatic(true); - - assertNull(nc.getPresetComponent()); - } - - @Test - public void changeAftShoulderRadiusClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setAftShoulderRadius(2.0); - - assertNull(nc.getPresetComponent()); - } - - @Test - public void changeAftSholderLengthLeavesPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setAftShoulderLength(2.0); - - assertSame(preset, nc.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setThickness(0.1); - - assertNull(nc.getPresetComponent()); - } - - - @Test - public void changeFilledClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setFilled(false); - - assertNull(nc.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(nc.getPresetComponent()); - } - - @Test - public void changeFinishLeavesPreset() { - NoseCone nc = new NoseCone(); - - nc.loadPreset(preset); - - nc.setFinish(Finish.POLISHED); - - assertSame(preset, nc.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/NoseConePresetTests.java b/core/test/net/sf/openrocket/preset/NoseConePresetTests.java deleted file mode 100644 index 56e849c5..00000000 --- a/core/test/net/sf/openrocket/preset/NoseConePresetTests.java +++ /dev/null @@ -1,208 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -/** - * Test construction of NOSE_CONE type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class NoseConePresetTests extends BaseTestCase { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.SHAPE - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "No AftOuterDiameter specified", - "No Shape specified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.SHAPE - }, - new String[] { - "No PartNo specified", - "No Length specified", - "No AftOuterDiameter specified", - "No Shape specified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.SHAPE - }, - new String[] { - "No Length specified", - "No AftOuterDiameter specified", - "No Shape specified" - } - ); - } - } - - @Test - public void testShapeRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.SHAPE - }, - new String[] { - "No AftOuterDiameter specified", - "No Shape specified" - } - ); - } - } - - @Test - public void testAftOuterDiameterRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.AFT_OUTER_DIAMETER - }, - new String[] { - "No AftOuterDiameter specified" - } - ); - } - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // constants put into the presetspec above. - double volume = /*base area*/Math.PI; - volume *= 2.0 /* times height *// 3.0; /* one third */ - - double density = 100.0 / volume; - - assertEquals("NoseConeCustom", preset.get(ComponentPreset.MATERIAL).getName()); - // note - epsilon is 1% of the simple computation of density - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.01 * density); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.NOSE_CONE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // constants put into the presetspec above. - double volume = /*base area*/Math.PI; - volume *= 2.0 /* times height *// 3.0; /* one third */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - // note - epsilon is 1% of the simple computation of density - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.01 * density); - } - -} diff --git a/core/test/net/sf/openrocket/preset/ParachutePresetTests.java b/core/test/net/sf/openrocket/preset/ParachutePresetTests.java deleted file mode 100644 index e6b3110a..00000000 --- a/core/test/net/sf/openrocket/preset/ParachutePresetTests.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.sf.openrocket.preset; - -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of PARACHUTE type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class ParachutePresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.DIAMETER, - ComponentPreset.LINE_COUNT, - ComponentPreset.LINE_LENGTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Diameter specified", - "No LineCount specified", - "No LineLength specified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.DIAMETER, - ComponentPreset.LINE_COUNT, - ComponentPreset.LINE_LENGTH - }, - new String[] { - "No PartNo specified", - "No Diameter specified", - "No LineCount specified", - "No LineLength specified" - } - ); - } - } - - @Test - public void testDiameterRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put( ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.DIAMETER, - ComponentPreset.LINE_COUNT, - ComponentPreset.LINE_LENGTH - }, - new String[] { - "No Diameter specified", - "No LineCount specified", - "No LineLength specified" - } - ); - } - } - - @Test - public void testLineCountRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put( ComponentPreset.PARTNO, "partno"); - presetspec.put( ComponentPreset.DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.LINE_COUNT, - ComponentPreset.LINE_LENGTH - }, - new String[] { - "No LineCount specified", - "No LineLength specified" - } - ); - } - } - - @Test - public void testLineLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put( ComponentPreset.PARTNO, "partno"); - presetspec.put( ComponentPreset.DIAMETER, 2.0); - presetspec.put( ComponentPreset.LINE_COUNT, 6); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.LINE_LENGTH - }, - new String[] { - "No LineLength specified" - } - ); - } - } - -} diff --git a/core/test/net/sf/openrocket/preset/ParachuterComponentTests.java b/core/test/net/sf/openrocket/preset/ParachuterComponentTests.java deleted file mode 100644 index e2489960..00000000 --- a/core/test/net/sf/openrocket/preset/ParachuterComponentTests.java +++ /dev/null @@ -1,128 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.Parachute; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to Parachute RocketComponents through - * the Parachute.loadFromPreset mechanism. - * - * Test Parachute is well defined. - * - * Test calling setters on Parachute will clear the ComponentPreset. - * - */ -public class ParachuterComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.PARACHUTE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.DIAMETER, 20.0); - presetspec.put(ComponentPreset.LINE_COUNT, 8); - presetspec.put(ComponentPreset.LINE_LENGTH, 12.0); - Material m = Material.newMaterial(Material.Type.SURFACE, "testMaterial", 2.0, true); - presetspec.put(ComponentPreset.MATERIAL, m); - m = Material.newMaterial(Material.Type.LINE, "testLineMaterial", 3, true); - presetspec.put(ComponentPreset.LINE_MATERIAL, m); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - Parachute cr = new Parachute(); - - assertSame(ComponentPreset.Type.PARACHUTE, cr.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - assertEquals(20.0, cr.getDiameter(), 0.0); - assertEquals(8, cr.getLineCount(), 0.0); - assertEquals(12.0, cr.getLineLength(), 0.0); - - assertSame(preset.get(ComponentPreset.MATERIAL), cr.getMaterial()); - assertSame(preset.get(ComponentPreset.LINE_MATERIAL), cr.getLineMaterial()); - } - - @Test - public void changeDiameterClearsPreset() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - cr.setDiameter(1.0); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeAreaClearsPreset() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - cr.setArea(1.0); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeLineCountClearsPreset() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - cr.setLineCount(12); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeLineLengthLeavesPreset() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - cr.setLineLength(24); - - assertSame(preset, cr.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - cr.setMaterial(Material.newMaterial(Material.Type.SURFACE, "new", 1.0, true)); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeLineMaterialLeavesPreset() { - Parachute cr = new Parachute(); - - cr.loadPreset(preset); - - cr.setLineMaterial(Material.newMaterial(Material.Type.LINE, "new", 1.0, true)); - - assertSame(preset, cr.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/PresetAssertHelper.java b/core/test/net/sf/openrocket/preset/PresetAssertHelper.java deleted file mode 100644 index 84b7c03b..00000000 --- a/core/test/net/sf/openrocket/preset/PresetAssertHelper.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; - -public abstract class PresetAssertHelper { - - public static void assertInvalidPresetException( InvalidComponentPresetException exceptions, TypedKey<?>[] keys, String[] messages ) { - if ( keys != null ) { - assertEquals( keys.length, exceptions.getInvalidParameters().size() ); - for( TypedKey<?> expectedKey : keys ) { - boolean keyFound = false; - for( TypedKey<?> k : exceptions.getInvalidParameters() ) { - if ( expectedKey == k ) { - keyFound = true; - break; - } - } - if ( ! keyFound ) { - fail( "Expected key " + expectedKey + " not in exception"); - } - } - } else { - assertEquals(0, exceptions.getInvalidParameters().size() ); - } - if ( messages != null ) { - assertEquals( messages.length, exceptions.getErrors().size() ); - for( String expectedMessage : messages ) { - boolean stringMatched = false; - for ( String s : exceptions.getErrors() ) { - if ( s.contains( expectedMessage ) ) { - stringMatched = true; - break; - } - } - if( !stringMatched ) { - fail( "Expected string \"" + expectedMessage + "\" not reported in errors"); - } - } - } else { - assertEquals(0, exceptions.getErrors().size() ); - } - } -} diff --git a/core/test/net/sf/openrocket/preset/StreamerComponentTests.java b/core/test/net/sf/openrocket/preset/StreamerComponentTests.java deleted file mode 100644 index 099a8d54..00000000 --- a/core/test/net/sf/openrocket/preset/StreamerComponentTests.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.Streamer; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to Streamer RocketComponents through - * the Streamer.loadFromPreset mechanism. - * - * Test Streamer is well defined. - * - * Test calling setters on Streamer will clear the ComponentPreset. - * - */ -public class StreamerComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.STREAMER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 20.0); - presetspec.put(ComponentPreset.WIDTH, 2.0); - Material m = Material.newMaterial(Material.Type.SURFACE, "testMaterial", 2.0, true); - presetspec.put(ComponentPreset.MATERIAL, m); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - Streamer cr = new Streamer(); - - assertSame(ComponentPreset.Type.STREAMER, cr.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - Streamer cr = new Streamer(); - - cr.loadPreset(preset); - - assertEquals(20.0, cr.getStripLength(), 0.0); - assertEquals(2.0, cr.getStripWidth(), 0.0); - assertEquals(2.0, cr.getLength(), 0.0); - - assertSame(preset.get(ComponentPreset.MATERIAL), cr.getMaterial()); - assertEquals(80.0, cr.getMass(), 0.05); - } - - @Test - public void changeLengthClearsPreset() { - Streamer cr = new Streamer(); - - cr.loadPreset(preset); - - cr.setStripLength(1.0); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeWidthClearsPreset() { - Streamer cr = new Streamer(); - - cr.loadPreset(preset); - - cr.setStripWidth(1.0); - - assertNull(cr.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - Streamer cr = new Streamer(); - - cr.loadPreset(preset); - - cr.setMaterial(Material.newMaterial(Material.Type.SURFACE, "new", 1.0, true)); - - assertNull(cr.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/StreamerPresetTests.java b/core/test/net/sf/openrocket/preset/StreamerPresetTests.java deleted file mode 100644 index a16fd14c..00000000 --- a/core/test/net/sf/openrocket/preset/StreamerPresetTests.java +++ /dev/null @@ -1,108 +0,0 @@ -package net.sf.openrocket.preset; - -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of STREAMER type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class StreamerPresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.STREAMER); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.WIDTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "No Width specified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.STREAMER); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.WIDTH - }, - new String[] { - "No PartNo specified", - "No Length specified", - "No Width specified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.STREAMER); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put( ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH, - ComponentPreset.WIDTH - }, - new String[] { - "No Length specified", - "No Width specified" - } - ); - } - } - - @Test - public void testWidthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.STREAMER); - presetspec.put( ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put( ComponentPreset.PARTNO, "partno"); - presetspec.put( ComponentPreset.LENGTH, 2.0); - ComponentPresetFactory.create(presetspec); - } catch ( InvalidComponentPresetException ex ) { - PresetAssertHelper.assertInvalidPresetException( ex, - new TypedKey<?>[] { - ComponentPreset.WIDTH - }, - new String[] { - "No Width specified" - } - ); - } - } - -} diff --git a/core/test/net/sf/openrocket/preset/TransitionComponentTests.java b/core/test/net/sf/openrocket/preset/TransitionComponentTests.java deleted file mode 100644 index 9826613c..00000000 --- a/core/test/net/sf/openrocket/preset/TransitionComponentTests.java +++ /dev/null @@ -1,210 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to Transition RocketComponents through - * the Transition.loadFromPreset mechanism. - * - * Test Transition is well defined. - * - * Test calling setters on Transition will clear the ComponentPreset. - * - */ -public class TransitionComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.FORE_OUTER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.AFT_SHOULDER_LENGTH, 1.0); - presetspec.put(ComponentPreset.AFT_SHOULDER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.FORE_SHOULDER_LENGTH, 1.0); - presetspec.put(ComponentPreset.FORE_SHOULDER_DIAMETER, 0.5); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - Transition tr = new Transition(); - - assertSame(ComponentPreset.Type.TRANSITION, tr.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - assertEquals(2.0, tr.getLength(), 0.0); - assertSame(Transition.Shape.CONICAL, tr.getType()); - assertEquals(1.0, tr.getAftRadius(), 0.0); - assertEquals(1.0, tr.getForeShoulderLength(), 0.0); - assertEquals(0.25, tr.getForeShoulderRadius(), 0.0); - assertEquals(0.25, tr.getForeShoulderThickness(), 0.0); - assertEquals(1.0, tr.getAftShoulderLength(), 0.0); - assertEquals(0.5, tr.getAftShoulderRadius(), 0.0); - assertEquals(0.5, tr.getAftShoulderThickness(), 0.0); - - assertFalse(tr.isForeRadiusAutomatic()); - assertFalse(tr.isAftRadiusAutomatic()); - assertTrue(tr.isFilled()); - - assertSame(preset.get(ComponentPreset.MATERIAL), tr.getMaterial()); - assertEquals(100.0, tr.getMass(), 1.0); - } - - @Test - public void changeLengthClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setLength(1.0); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeAftRadiusClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setAftRadius(2.0); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeAftRadiusAutomaticClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setAftRadiusAutomatic(true); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeForeRadiusClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setForeRadius(2.0); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeForeRadiusAutomaticClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setForeRadiusAutomatic(true); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeForeShoulderRadiusClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setForeShoulderRadius(2.0); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeAftShoulderRadiusClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setAftShoulderRadius(2.0); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeAftSholderLengthLeavesPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setAftShoulderLength(2.0); - - assertSame(preset, tr.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setThickness(0.1); - - assertNull(tr.getPresetComponent()); - } - - - @Test - public void changeFilledClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setFilled(false); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(tr.getPresetComponent()); - } - - @Test - public void changeFinishLeavesPreset() { - Transition tr = new Transition(); - - tr.loadPreset(preset); - - tr.setFinish(Finish.POLISHED); - - assertSame(preset, tr.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/TransitionPresetTests.java b/core/test/net/sf/openrocket/preset/TransitionPresetTests.java deleted file mode 100644 index 26593dd8..00000000 --- a/core/test/net/sf/openrocket/preset/TransitionPresetTests.java +++ /dev/null @@ -1,222 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -/** - * Test construction of TRANSITION type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class TransitionPresetTests extends BaseTestCase { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.FORE_OUTER_DIAMETER - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "No AftOuterDiameter specified", - "No ForeOuterDiameter specified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.FORE_OUTER_DIAMETER - }, - new String[] { - "No PartNo specified", - "No Length specified", - "No AftOuterDiameter specified", - "No ForeOuterDiameter specified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH, - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.FORE_OUTER_DIAMETER - }, - new String[] { - "No Length specified", - "No AftOuterDiameter specified", - "No ForeOuterDiameter specified" - } - ); - } - } - - @Test - public void testAftOuterDiameterRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.AFT_OUTER_DIAMETER, - ComponentPreset.FORE_OUTER_DIAMETER - }, - new String[] { - "No AftOuterDiameter specified", - "No ForeOuterDiameter specified" - } - ); - } - } - - - @Test - public void testForeOuterDiameterRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.FORE_OUTER_DIAMETER - }, - new String[] { - "No ForeOuterDiameter specified" - } - ); - } - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.FORE_OUTER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // constants put into the presetspec above. - double volume = /*base area*/Math.PI * (1.0 * 1.0 + 1.0 * 0.5 + 0.5 * 0.5); - - volume *= 2.0 /* times height *// 3.0; /* one third */ - - double density = 100.0 / volume; - - assertEquals("TransitionCustom", preset.get(ComponentPreset.MATERIAL).getName()); - - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.01 * density); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.FORE_OUTER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TRANSITION); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.SHAPE, Transition.Shape.CONICAL); - presetspec.put(ComponentPreset.AFT_OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.FORE_OUTER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.FILLED, true); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // constants put into the presetspec above. - double totvolume = /*base area*/Math.PI; - - totvolume *= 4.0 /* times height *// 3.0; /* one third */ - - double uppervolume = /*fore area*/Math.PI * 0.5 * 0.5; - uppervolume *= 2.0 /* times height *// 3.0; /* one third */ - - double volume = totvolume - uppervolume; - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.01 * density); - } - -} diff --git a/core/test/net/sf/openrocket/preset/TubeCouplerComponentTests.java b/core/test/net/sf/openrocket/preset/TubeCouplerComponentTests.java deleted file mode 100644 index 829f664f..00000000 --- a/core/test/net/sf/openrocket/preset/TubeCouplerComponentTests.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.*; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.rocketcomponent.TubeCoupler; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Before; -import org.junit.Test; - -/** - * Test application of ComponentPresets to TubeCoupler RocketComponents through - * the TubeCoupler.loadFromPreset mechanism. - * - * Test TubeCoupler is well defined. - * - * Test calling setters on TubeCoupler will clear the ComponentPreset. - * - */ -public class TubeCouplerComponentTests extends BaseTestCase { - - ComponentPreset preset; - - @Before - public void createPreset() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - preset = ComponentPresetFactory.create(presetspec); - } - - @Test - public void testComponentType() { - TubeCoupler tc = new TubeCoupler(); - - assertSame(ComponentPreset.Type.TUBE_COUPLER, tc.getPresetType()); - } - - @Test - public void testLoadFromPresetIsSane() { - TubeCoupler tc = new TubeCoupler(); - - tc.loadPreset(preset); - - assertEquals(2.0, tc.getLength(), 0.0); - assertEquals(1.0, tc.getOuterRadius(), 0.0); - assertEquals(0.5, tc.getInnerRadius(), 0.0); - - assertFalse(tc.isInnerRadiusAutomatic()); - assertFalse(tc.isOuterRadiusAutomatic()); - - assertSame(preset.get(ComponentPreset.MATERIAL), tc.getMaterial()); - assertEquals(100.0, tc.getMass(), 0.05); - } - - @Test - public void changeLengthLeavesPreset() { - TubeCoupler tc = new TubeCoupler(); - - tc.loadPreset(preset); - - tc.setLength(1.0); - - assertSame(preset, tc.getPresetComponent()); - } - - @Test - public void changeODClearsPreset() { - TubeCoupler tc = new TubeCoupler(); - - tc.loadPreset(preset); - - tc.setOuterRadius(2.0); - - assertNull(tc.getPresetComponent()); - } - - @Test - public void changeIDClearsPreset() { - TubeCoupler tc = new TubeCoupler(); - - tc.loadPreset(preset); - - tc.setInnerRadius(0.75); - - assertNull(tc.getPresetComponent()); - } - - @Test - public void changeThicknessClearsPreset() { - TubeCoupler tc = new TubeCoupler(); - - tc.loadPreset(preset); - - tc.setThickness(0.1); - - assertNull(tc.getPresetComponent()); - } - - @Test - public void changeMaterialClearsPreset() { - TubeCoupler tc = new TubeCoupler(); - - tc.loadPreset(preset); - - tc.setMaterial(Material.newMaterial(Material.Type.BULK, "new", 1.0, true)); - - assertNull(tc.getPresetComponent()); - } - -} diff --git a/core/test/net/sf/openrocket/preset/TubeCouplerPresetTests.java b/core/test/net/sf/openrocket/preset/TubeCouplerPresetTests.java deleted file mode 100644 index 7ef16ede..00000000 --- a/core/test/net/sf/openrocket/preset/TubeCouplerPresetTests.java +++ /dev/null @@ -1,271 +0,0 @@ -package net.sf.openrocket.preset; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.motor.Manufacturer; - -import org.junit.Test; - -/** - * Test construction of TUBE_COUPLER type ComponentPresets based on TypedPropertyMap through the - * ComponentPresetFactory.create() method. - * - * Ensure required properties are populated - * - * Ensure any computed values are correctly computed. - * - */ -public class TubeCouplerPresetTests { - - @Test - public void testManufacturerRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.MANUFACTURER, - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No Manufacturer specified", - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testPartNoRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.PARTNO, - ComponentPreset.LENGTH - }, - new String[] { - "No PartNo specified", - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testLengthRequired() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - new TypedKey<?>[] { - ComponentPreset.LENGTH - }, - new String[] { - "No Length specified", - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyOuterDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyInnerDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testOnlyThicknessDiameter() { - try { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 2.0); - ComponentPresetFactory.create(presetspec); - } catch (InvalidComponentPresetException ex) { - PresetAssertHelper.assertInvalidPresetException(ex, - null, - new String[] { - "Preset dimensions underspecified" - } - ); - } - } - - @Test - public void testComputeInnerDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(1.0, preset.get(ComponentPreset.INNER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeOuterDiameter() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 0.5); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(2.0, preset.get(ComponentPreset.OUTER_DIAMETER).doubleValue(), 0.0); - } - - @Test - public void testComputeThickness() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeThicknessLooses() throws Exception { - // If all OUTER_DIAMETER, INNER_DIAMETER and THICKNESS are - // specified, THICKNESS is recomputed. - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.THICKNESS, 15.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals(0.5, preset.get(ComponentPreset.THICKNESS).doubleValue(), 0.0); - } - - @Test - public void testComputeDensityNoMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("TubeCustom", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - - @Test - public void testMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(2.0, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - - } - - @Test - public void testComputeDensityWithMaterial() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.TUBE_COUPLER); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - presetspec.put(ComponentPreset.MATERIAL, Material.newMaterial(Material.Type.BULK, "test", 2.0, true)); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - // Compute the volume by hand here using a slightly different formula from - // the real implementation. The magic numbers are based on the - // constants put into the presetspec above. - double volume = /*outer area*/(Math.PI * 1.0) - /* inner area */(Math.PI * .25); - volume *= 2.0; /* times length */ - - double density = 100.0 / volume; - - assertEquals("test", preset.get(ComponentPreset.MATERIAL).getName()); - assertEquals(density, preset.get(ComponentPreset.MATERIAL).getDensity(), 0.0005); - } - -} diff --git a/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java b/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java deleted file mode 100644 index bbc609d9..00000000 --- a/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import net.sf.openrocket.motor.Manufacturer; -import net.sf.openrocket.preset.ComponentPreset; -import net.sf.openrocket.preset.ComponentPresetFactory; -import net.sf.openrocket.preset.TypedPropertyMap; -import org.junit.Assert; -import org.junit.Test; - -import javax.imageio.ImageIO; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferByte; -import java.io.StringReader; -import java.io.StringWriter; - -/** - */ -public class BaseComponentDTOTest { - - - @Test - public void testImage() throws Exception { - TypedPropertyMap presetspec = new TypedPropertyMap(); - presetspec.put(ComponentPreset.TYPE, ComponentPreset.Type.BODY_TUBE); - presetspec.put(ComponentPreset.MANUFACTURER, Manufacturer.getManufacturer("manufacturer")); - presetspec.put(ComponentPreset.PARTNO, "partno"); - presetspec.put(ComponentPreset.LENGTH, 2.0); - presetspec.put(ComponentPreset.OUTER_DIAMETER, 2.0); - presetspec.put(ComponentPreset.INNER_DIAMETER, 1.0); - presetspec.put(ComponentPreset.MASS, 100.0); - ComponentPreset preset = ComponentPresetFactory.create(presetspec); - - //Convert the presets to a BodyTubeDTO - BodyTubeDTO dto = new BodyTubeDTO(preset); - - //Add an image to the DTO. - BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("/pix/splashscreen.png")); - dto.setImage(image); - - JAXBContext binder = JAXBContext.newInstance(OpenRocketComponentDTO.class); - Marshaller marshaller = binder.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - StringWriter sw = new StringWriter(); - - //Serialize the dto to XML - marshaller.marshal(dto, sw); - String xml = sw.toString(); - - //Read the XML back to create the dto again - Unmarshaller unmarshaller = binder.createUnmarshaller(); - BodyTubeDTO redone = (BodyTubeDTO) unmarshaller.unmarshal(new StringReader(xml)); - - //Compare the image. - Assert.assertArrayEquals(((DataBufferByte) image.getData().getDataBuffer()).getData(), - ((DataBufferByte) redone.getImage().getData().getDataBuffer()).getData()); - - //Assert the rest of the attributes. - Assert.assertEquals(dto.getInsideDiameter(), redone.getInsideDiameter(), 0.00001); - Assert.assertEquals(dto.getLength(), redone.getLength(), 0.00001); - Assert.assertEquals(dto.getOutsideDiameter(), redone.getOutsideDiameter(), 0.00001); - Assert.assertEquals(dto.getDescription(), redone.getDescription()); - Assert.assertEquals(dto.getManufacturer(), redone.getManufacturer()); - Assert.assertEquals(dto.getMass(), redone.getMass(), 0.00001); - Assert.assertEquals(dto.getPartNo(), redone.getPartNo()); - - //Uncomment if you want to write the image to a file to view it. -// ImageIO.write(redone.getImage(), "png", new FileOutputStream("redone.png")); - } -} diff --git a/core/test/net/sf/openrocket/preset/xml/OpenRocketComponentSaverTest.java b/core/test/net/sf/openrocket/preset/xml/OpenRocketComponentSaverTest.java deleted file mode 100644 index 4325fae2..00000000 --- a/core/test/net/sf/openrocket/preset/xml/OpenRocketComponentSaverTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package net.sf.openrocket.preset.xml; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** -* OpenRocketComponentSaver Tester. -* -*/ -public class OpenRocketComponentSaverTest { - - @Before - public void before() throws Exception { - } - - @After - public void after() throws Exception { - } - - /** - * - * Method: marshalToOpenRocketComponent(List<Material> theMaterialList, List<ComponentPreset> thePresetList) - * - */ - @Test - public void testMarshalToOpenRocketComponent() throws Exception { - //TODO: Test goes here... - } - - /** - * - * Method: unmarshalFromOpenRocketComponent(Reader is) - * - */ - @Test - public void testUnmarshalFromOpenRocketComponent() throws Exception { - //TODO: Test goes here... - } - - /** - * - * Method: save(OutputStream dest, List<Material> theMaterialList, List<ComponentPreset> thePresetList) - * - */ - @Test - public void testSave() throws Exception { - //TODO: Test goes here... - } - - - /** - * - * Method: fromOpenRocketComponent(Reader is) - * - */ - @Test - public void testFromOpenRocketComponent() throws Exception { - //TODO: Test goes here... -/* -try { - Method method = OpenRocketComponentSaver.getClass().getMethod("fromOpenRocketComponent", Reader.class); - method.setAccessible(true); - method.invoke(<Object>, <Parameters>); -} catch(NoSuchMethodException e) { -} catch(IllegalAccessException e) { -} catch(InvocationTargetException e) { -} -*/ - } - - /** - * - * Method: toOpenRocketComponentDTO(List<Material> theMaterialList, List<ComponentPreset> thePresetList) - * - */ - @Test - public void testToOpenRocketComponentDTO() throws Exception { - //TODO: Test goes here... -/* -try { - Method method = OpenRocketComponentSaver.getClass().getMethod("toOpenRocketComponentDTO", List<Material>.class, List<ComponentPreset>.class); - method.setAccessible(true); - method.invoke(<Object>, <Parameters>); -} catch(NoSuchMethodException e) { -} catch(IllegalAccessException e) { -} catch(InvocationTargetException e) { -} -*/ - } - - /** - * - * Method: toComponentDTO(ComponentPreset thePreset) - * - */ - @Test - public void testToComponentDTO() throws Exception { - //TODO: Test goes here... -/* -try { - Method method = OpenRocketComponentSaver.getClass().getMethod("toComponentDTO", ComponentPreset.class); - method.setAccessible(true); - method.invoke(<Object>, <Parameters>); -} catch(NoSuchMethodException e) { -} catch(IllegalAccessException e) { -} catch(InvocationTargetException e) { -} -*/ - } - -} diff --git a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompare.java b/core/test/net/sf/openrocket/rocketcomponent/ComponentCompare.java deleted file mode 100644 index aa3fc486..00000000 --- a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompare.java +++ /dev/null @@ -1,147 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import static org.junit.Assert.*; - -import java.lang.reflect.Method; -import java.util.Iterator; -import java.util.regex.Pattern; - -import net.sf.openrocket.util.BugException; - -public class ComponentCompare { - - private static final Pattern GETTER_PATTERN = Pattern.compile("^(is|get)[A-Z].*+"); - - private static final String[] IGNORED_METHODS = { - "getClass", "getChildCount", "getChildren", "getNextComponent", "getID", - "getPreviousComponent", "getParent", "getRocket", "getRoot", "getStage", - "getStageNumber", "getComponentName", - // Rocket specific methods: - "getModID", "getMassModID", "getAerodynamicModID", "getTreeModID", "getFunctionalModID", - "getMotorConfigurationIDs", "getDefaultConfiguration", "getMotorMounts" - }; - - - /** - * Check whether the two components are <em>equal</em>. Two components are considered - * equal if they are of the same type and all of their getXXX() and isXXX() methods - * return equal values. - * - * @param c1 the first component to compare. - * @param c2 the second component to compare. - */ - public static void assertEquality(RocketComponent c1, RocketComponent c2) { - assertEquals(c1.getClass(), c2.getClass()); - - // Same class + similar == equal - assertSimilarity(c1, c2); - } - - - - public static void assertDeepEquality(RocketComponent c1, RocketComponent c2) { - assertEquality(c1, c2); - - Iterator<RocketComponent> i1 = c1.getChildren().iterator(); - Iterator<RocketComponent> i2 = c2.getChildren().iterator(); - while (i1.hasNext()) { - assertTrue("iterator continues", i2.hasNext()); - RocketComponent comp1 = i1.next(); - RocketComponent comp2 = i2.next(); - assertDeepEquality(comp1, comp2); - } - assertFalse("iterator end", i2.hasNext()); - } - - - - public static void assertDeepSimilarity(RocketComponent c1, RocketComponent c2, - boolean allowNameDifference) { - assertSimilarity(c1, c2, allowNameDifference); - - Iterator<RocketComponent> i1 = c1.getChildren().iterator(); - Iterator<RocketComponent> i2 = c2.getChildren().iterator(); - while (i1.hasNext()) { - assertTrue("iterator continues", i2.hasNext()); - RocketComponent comp1 = i1.next(); - RocketComponent comp2 = i2.next(); - assertDeepSimilarity(comp1, comp2, allowNameDifference); - } - assertFalse("iterator end", i2.hasNext()); - } - - - - /** - * Check whether the two components are <em>similar</em>. Two components are similar - * if each of the getXXX and isXXX methods that both object types have return - * equal values. This does not check whether the two components are of the same type. - * - * @param c1 the first component. - * @param c2 the second component. - */ - public static void assertSimilarity(RocketComponent c1, RocketComponent c2) { - assertSimilarity(c1, c2, false); - } - - /** - * Check whether the two components are <em>similar</em>, allowing a name difference. - * - * @param c1 the first component. - * @param c2 the second component. - * @param allowNameDifference whether to allow the components to have different names. - */ - public static void assertSimilarity(RocketComponent c1, RocketComponent c2, - boolean allowNameDifference) { - Class<? extends RocketComponent> class1 = c1.getClass(); - Class<? extends RocketComponent> class2 = c2.getClass(); - - mainloop: for (Method m1 : class1.getMethods()) { - // Check for getter method - String name = m1.getName(); - if (!GETTER_PATTERN.matcher(name).matches()) - continue; - - // Ignore methods that take parameters - if (m1.getParameterTypes().length != 0) - continue; - - // Ignore specific getters - for (String ignore : IGNORED_METHODS) { - if (name.equals(ignore)) - continue mainloop; - } - if (allowNameDifference && name.equals("getName")) - continue; - - - // Check for method in other class - Method m2; - try { - m2 = class2.getMethod(name); - } catch (NoSuchMethodException e) { - continue; - } - - // System.out.println("Testing results of method " + name); - - // Run the methods - Object result1, result2; - try { - result1 = m1.invoke(c1); - result2 = m2.invoke(c2); - } catch (Exception e) { - throw new BugException("Error executing method " + name, e); - } - - if (result1 != null && result2 != null && - result1.getClass().isArray() && result2.getClass().isArray()) { - assertArrayEquals("Comparing result of method " + name, - (Object[]) result1, (Object[]) result2); - } else { - assertEquals("Comparing result of method " + name, result1, result2); - } - } - } - -} diff --git a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java b/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java deleted file mode 100644 index 647750cc..00000000 --- a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.awt.Color; -import java.util.Iterator; - -import net.sf.openrocket.gui.util.ColorConversion; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -public class ComponentCompareTest extends BaseTestCase { - - @Test - public void testComponentEquality() { - - System.out.println("TEST CLASSPATH: " + System.getProperty("java.class.path")); - - Rocket r1 = net.sf.openrocket.util.TestRockets.makeBigBlue(); - Rocket r2 = net.sf.openrocket.util.TestRockets.makeBigBlue(); - - Iterator<RocketComponent> i1 = r1.iterator(true); - Iterator<RocketComponent> i2 = r2.iterator(true); - while (i1.hasNext()) { - assertTrue(i2.hasNext()); - - RocketComponent c1 = i1.next(); - RocketComponent c2 = i2.next(); - - ComponentCompare.assertEquality(c1, c2); - ComponentCompare.assertSimilarity(c1, c2); - } - assertFalse(i2.hasNext()); - - - ComponentCompare.assertDeepEquality(r1, r2); - ComponentCompare.assertDeepSimilarity(r1, r2, false); - - - r1.setColor(ColorConversion.fromAwtColor(Color.YELLOW)); - try { - ComponentCompare.assertEquality(r1, r2); - fail(); - } catch (AssertionError e) { - // Correct behavior - } - - - i1 = r1.iterator(true); - i2 = r2.iterator(true); - boolean finsetfound = false; - while (i1.hasNext()) { - RocketComponent c1 = i1.next(); - RocketComponent c2 = i2.next(); - - if (c1 instanceof FinSet) { - finsetfound = true; - FinSet f1 = (FinSet)c1; - f1.setTabHeight(0.001); - - try { - ComponentCompare.assertEquality(c1, c2); - fail(); - } catch (AssertionError e) { - // Correct behavior - } - } - } - assertTrue(finsetfound); - } - - - @Test - public void testComponentSimilarity() throws IllegalFinPointException { - FinSet trap = new TrapezoidFinSet( - 5, // fins - 5.0, // root - 3.0, // tip - 0.0, // sweep - 2.0); // height - FinSet free = new FreeformFinSet(new Coordinate[] { - new Coordinate(0,0), - new Coordinate(0,2), - new Coordinate(3,2), - new Coordinate(5,0) - }); - free.setFinCount(5); - - ComponentCompare.assertSimilarity(trap, free, true); - - try { - ComponentCompare.assertSimilarity(trap, free); - fail(); - } catch (AssertionError e) { - // Correct behavior - } - - free.setName(trap.getName()); - ComponentCompare.assertSimilarity(trap, free); - - try { - ComponentCompare.assertEquality(trap, free); - fail(); - } catch (AssertionError e) { - // Correct behavior - } - - - BodyTube t1 = new BodyTube(); - BodyTube t2 = new BodyTube(); - t1.addChild(free); - t2.addChild(trap); - - ComponentCompare.assertDeepSimilarity(t1, t2, false); - - try { - ComponentCompare.assertDeepEquality(t1, t2); - fail(); - } catch (AssertionError e) { - // Correct behavior - } - - t1.addChild(new TrapezoidFinSet()); - - try { - ComponentCompare.assertDeepSimilarity(t1, t2, true); - fail(); - } catch (AssertionError e) { - // Correct behavior - } - - } - -} diff --git a/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java b/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java deleted file mode 100644 index 321efbe8..00000000 --- a/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import static org.junit.Assert.*; - -import java.awt.Color; - -import net.sf.openrocket.gui.util.ColorConversion; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.material.Material.Type; -import net.sf.openrocket.rocketcomponent.ExternalComponent.Finish; -import net.sf.openrocket.rocketcomponent.FinSet.CrossSection; -import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition; -import net.sf.openrocket.rocketcomponent.RocketComponent.Position; -import net.sf.openrocket.util.LineStyle; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -public class FinSetTest extends BaseTestCase { - - - @Test - public void testFreeformConvert() { - testFreeformConvert(new TrapezoidFinSet()); - testFreeformConvert(new EllipticalFinSet()); - testFreeformConvert(new FreeformFinSet()); - } - - - private void testFreeformConvert(FinSet fin) { - FreeformFinSet converted; - Material mat = Material.newMaterial(Type.BULK, "foo", 0.1, true); - - fin.setBaseRotation(1.1); - fin.setCantAngle(0.001); - fin.setCGOverridden(true); - fin.setColor(ColorConversion.fromAwtColor(Color.YELLOW)); - fin.setComment("cmt"); - fin.setCrossSection(CrossSection.ROUNDED); - fin.setFinCount(5); - fin.setFinish(Finish.ROUGH); - fin.setLineStyle(LineStyle.DASHDOT); - fin.setMassOverridden(true); - fin.setMaterial(mat); - fin.setOverrideCGX(0.012); - fin.setOverrideMass(0.0123); - fin.setOverrideSubcomponents(true); - fin.setPositionValue(0.1); - fin.setRelativePosition(Position.ABSOLUTE); - fin.setTabHeight(0.01); - fin.setTabLength(0.02); - fin.setTabRelativePosition(TabRelativePosition.END); - fin.setTabShift(0.015); - fin.setThickness(0.005); - - - converted = FreeformFinSet.convertFinSet((FinSet) fin.copy()); - - ComponentCompare.assertSimilarity(fin, converted, true); - - assertEquals(converted.getComponentName(), converted.getName()); - - - // Create test rocket - Rocket rocket = new Rocket(); - Stage stage = new Stage(); - BodyTube body = new BodyTube(); - - rocket.addChild(stage); - stage.addChild(body); - body.addChild(fin); - - Listener l1 = new Listener("l1"); - rocket.addComponentChangeListener(l1); - - fin.setName("Custom name"); - assertTrue(l1.changed); - assertEquals(ComponentChangeEvent.NONFUNCTIONAL_CHANGE, l1.changetype); - - - // Create copy - RocketComponent rocketcopy = rocket.copy(); - - Listener l2 = new Listener("l2"); - rocketcopy.addComponentChangeListener(l2); - - FinSet fincopy = (FinSet) rocketcopy.getChild(0).getChild(0).getChild(0); - FreeformFinSet.convertFinSet(fincopy); - - assertTrue(l2.changed); - assertEquals(ComponentChangeEvent.TREE_CHANGE, - l2.changetype & ComponentChangeEvent.TREE_CHANGE); - - } - - - private static class Listener implements ComponentChangeListener { - private boolean changed = false; - private int changetype = 0; - private final String name; - - public Listener(String name) { - this.name = name; - } - - @Override - public void componentChanged(ComponentChangeEvent e) { - assertFalse("Ensuring listener " + name + " has not been called.", changed); - changed = true; - changetype = e.getType(); - } - } - -} diff --git a/core/test/net/sf/openrocket/rocketcomponent/RocketTest.java b/core/test/net/sf/openrocket/rocketcomponent/RocketTest.java deleted file mode 100644 index 16b5ca5d..00000000 --- a/core/test/net/sf/openrocket/rocketcomponent/RocketTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -public class RocketTest extends BaseTestCase { - - @Test - public void testCopyFrom() { - Rocket r1 = net.sf.openrocket.util.TestRockets.makeIsoHaisu(); - Rocket r2 = net.sf.openrocket.util.TestRockets.makeBigBlue(); - - Rocket copy = (Rocket) r2.copy(); - - ComponentCompare.assertDeepEquality(r2, copy); - - r1.copyFrom(copy); - - ComponentCompare.assertDeepEquality(r1, r2); - } - -} diff --git a/core/test/net/sf/openrocket/rocketcomponent/SymmetricComponentVolumeTest.java b/core/test/net/sf/openrocket/rocketcomponent/SymmetricComponentVolumeTest.java deleted file mode 100644 index 9d554d72..00000000 --- a/core/test/net/sf/openrocket/rocketcomponent/SymmetricComponentVolumeTest.java +++ /dev/null @@ -1,450 +0,0 @@ -package net.sf.openrocket.rocketcomponent; - -import static org.junit.Assert.assertEquals; -import net.sf.openrocket.material.Material; -import net.sf.openrocket.util.Coordinate; -import net.sf.openrocket.util.BaseTestCase.BaseTestCase; - -import org.junit.Test; - -public class SymmetricComponentVolumeTest extends BaseTestCase { - - @Test - public void simpleConeFilled() { - NoseCone nc = new NoseCone(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setFilled(true); - nc.setType(Transition.Shape.CONICAL); - nc.setAftRadius(1.0); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - double volume = Math.PI / 3.0; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(0.75, cg.x, epsilonPercent * 0.75); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleConeWithShoulderFilled() { - NoseCone nc = new NoseCone(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setFilled(true); - nc.setType(Transition.Shape.CONICAL); - nc.setAftRadius(1.0); - nc.setAftShoulderRadius(1.0); - nc.setAftShoulderLength(1.0); - nc.setAftShoulderThickness(1.0); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - double volume = Math.PI / 3.0; - volume += Math.PI; - - double mass = density * volume; - - System.out.println(volume + "\t" + mass); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(1.312, cg.x, epsilonPercent * 1.071); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleConeHollow() { - NoseCone nc = new NoseCone(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setAftRadius(1.0); - nc.setThickness(0.5); - nc.setType(Transition.Shape.CONICAL); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - double volume = Math.PI / 3.0; // outer volume - - // manually projected Thickness of 0.5 on to radius to determine - // the innerConeDimen. Since the outer cone is "square" (height = radius), - // we only need to compute this one dimension in order to compute the - // volume of the inner cone. - double innerConeDimen = 1.0 - Math.sqrt(2.0) / 2.0; - double innerVolume = Math.PI / 3.0 * innerConeDimen * innerConeDimen * innerConeDimen; - volume -= innerVolume; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(0.7454, cg.x, epsilonPercent * 0.7454); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleConeWithShoulderHollow() { - NoseCone nc = new NoseCone(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setType(Transition.Shape.CONICAL); - nc.setAftRadius(1.0); - nc.setThickness(0.5); - nc.setAftShoulderRadius(1.0); - nc.setAftShoulderLength(1.0); - nc.setAftShoulderThickness(0.5); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - double volume = Math.PI / 3.0; // outer volume - - // manually projected Thickness of 0.5 on to radius to determine - // the innerConeDimen. Since the outer cone is "square" (height = radius), - // we only need to compute this one dimension in order to compute the - // volume of the inner cone. - double innerConeDimen = 1.0 - Math.sqrt(2.0) / 2.0; - double innerVolume = Math.PI / 3.0 * innerConeDimen * innerConeDimen * innerConeDimen; - volume -= innerVolume; - - volume += Math.PI - Math.PI * 0.5 * 0.5; - - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(1.2719, cg.x, epsilonPercent * 1.2719); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleTransitionFilled() { - Transition nc = new Transition(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(4.0); - nc.setFilled(true); - nc.setType(Transition.Shape.CONICAL); - nc.setForeRadius(1.0); - nc.setAftRadius(2.0); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - double volume = Math.PI / 3.0 * (2.0 * 2.0 + 2.0 * 1.0 + 1.0 * 1.0) * 4.0; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(2.4285, cg.x, epsilonPercent * 2.4285); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleTransitionWithShouldersFilled() { - Transition nc = new Transition(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(4.0); - nc.setFilled(true); - nc.setType(Transition.Shape.CONICAL); - nc.setForeRadius(1.0); - nc.setAftRadius(2.0); - nc.setAftShoulderLength(1.0); - nc.setAftShoulderRadius(2.0); - nc.setAftShoulderThickness(2.0); - nc.setForeShoulderLength(1.0); - nc.setForeShoulderRadius(1.0); - nc.setForeShoulderThickness(1.0); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - double volume = Math.PI / 3.0 * (2.0 * 2.0 + 2.0 * 1.0 + 1.0 * 1.0) * 4.0; - // plus aft shoulder: - volume += Math.PI * 1.0 * 2.0 * 2.0; - // plus fore shoulder: - volume += Math.PI * 1.0 * 1.0 * 1.0; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(2.8023, cg.x, epsilonPercent * 2.8023); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleTransitionHollow1() { - Transition nc = new Transition(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setType(Transition.Shape.CONICAL); - nc.setForeRadius(0.5); - nc.setAftRadius(1.0); - nc.setThickness(0.5); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - // Volume of filled transition = - double filledVolume = Math.PI / 3.0 * (1.0 * 1.0 + 1.0 * 0.5 + 0.5 * 0.5) * 1.0; - - // magic 2D cad drawing... - // - // Since the thickness >= fore radius, the - // hollowed out portion of the transition - // forms a cone. - // the dimensions of this cone were determined - // using a 2d cad tool. - - double innerConeRadius = 0.441; - double innerConeLength = 0.882; - double innerVolume = Math.PI / 3.0 * innerConeLength * innerConeRadius * innerConeRadius; - - double volume = filledVolume - innerVolume; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(0.5884, cg.x, epsilonPercent * 0.5884); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleTransitionWithShouldersHollow1() { - Transition nc = new Transition(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setType(Transition.Shape.CONICAL); - nc.setForeRadius(0.5); - nc.setAftRadius(1.0); - nc.setThickness(0.5); - nc.setAftShoulderLength(1.0); - nc.setAftShoulderRadius(1.0); - nc.setAftShoulderThickness(0.5); - nc.setForeShoulderLength(1.0); - nc.setForeShoulderRadius(0.5); - nc.setForeShoulderThickness(0.5); // note this means fore shoulder is filled. - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - // Volume of filled transition = - double filledVolume = Math.PI / 3.0 * (1.0 * 1.0 + 1.0 * 0.5 + 0.5 * 0.5) * 1.0; - - // magic 2D cad drawing... - // - // Since the thickness >= fore radius, the - // hollowed out portion of the transition - // forms a cone. - // the dimensions of this cone were determined - // using a 2d cad tool. - - double innerConeRadius = 0.441; - double innerConeLength = 0.882; - double innerVolume = Math.PI / 3.0 * innerConeLength * innerConeRadius * innerConeRadius; - - double volume = filledVolume - innerVolume; - - // Now add aft shoulder - volume += Math.PI * 1.0 * 1.0 * 1.0 - Math.PI * 1.0 * 0.5 * 0.5; - // Now add fore shoulder - volume += Math.PI * 1.0 * 0.5 * 0.5; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(0.8581, cg.x, epsilonPercent * 0.8581); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleTransitionHollow2() { - Transition nc = new Transition(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setType(Transition.Shape.CONICAL); - nc.setForeRadius(0.5); - nc.setAftRadius(1.0); - nc.setThickness(0.25); - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - // Volume of filled transition = - double filledVolume = Math.PI / 3.0 * (1.0 * 1.0 + 1.0 * 0.5 + 0.5 * 0.5) * 1.0; - - // magic 2D cad drawing... - // - // Since the thickness < fore radius, the - // hollowed out portion of the transition - // forms a transition. - // the dimensions of this transition were determined - // using a 2d cad tool. - - double innerTransitionAftRadius = 0.7205; - double innerTransitionForeRadius = 0.2205; - double innerVolume = Math.PI / 3.0 - * (innerTransitionAftRadius * innerTransitionAftRadius + innerTransitionAftRadius * innerTransitionForeRadius + innerTransitionForeRadius * innerTransitionForeRadius); - - double volume = filledVolume - innerVolume; - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(0.56827, cg.x, epsilonPercent * 0.56827); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - - @Test - public void simpleTransitionWithShouldersHollow2() { - Transition nc = new Transition(); - - final double epsilonPercent = 0.001; - final double density = 2.0; - - nc.setLength(1.0); - nc.setType(Transition.Shape.CONICAL); - nc.setForeRadius(0.5); - nc.setAftRadius(1.0); - nc.setThickness(0.25); - nc.setAftShoulderLength(1.0); - nc.setAftShoulderRadius(1.0); - nc.setAftShoulderThickness(0.25); - nc.setForeShoulderLength(1.0); - nc.setForeShoulderRadius(0.5); - nc.setForeShoulderThickness(0.25); - - nc.setMaterial(Material.newMaterial(Material.Type.BULK, "test", density, true)); - - Coordinate cg = nc.getCG(); - - System.out.println(nc.getComponentVolume() + "\t" + nc.getMass()); - System.out.println(cg); - - // Volume of filled transition = - double filledVolume = Math.PI / 3.0 * (1.0 * 1.0 + 1.0 * 0.5 + 0.5 * 0.5) * 1.0; - - // magic 2D cad drawing... - // - // Since the thickness < fore radius, the - // hollowed out portion of the transition - // forms a transition. - // the dimensions of this transition were determined - // using a 2d cad tool. - - double innerTransitionAftRadius = 0.7205; - double innerTransitionForeRadius = 0.2205; - double innerVolume = Math.PI / 3.0 - * (innerTransitionAftRadius * innerTransitionAftRadius + innerTransitionAftRadius * innerTransitionForeRadius + innerTransitionForeRadius * innerTransitionForeRadius); - - double volume = filledVolume - innerVolume; - - // now add aft shoulder - volume += Math.PI * 1.0 * 1.0 * 1.0 - Math.PI * 1.0 * 0.75 * 0.75; - // now add fore shoulder - volume += Math.PI * 1.0 * 0.5 * 0.5 - Math.PI * 1.0 * 0.25 * 0.25; - - - double mass = density * volume; - - System.out.println(volume); - - assertEquals(volume, nc.getComponentVolume(), epsilonPercent * volume); - assertEquals(mass, nc.getMass(), epsilonPercent * mass); - - assertEquals(0.7829, cg.x, epsilonPercent * 0.7829); - assertEquals(mass, cg.weight, epsilonPercent * mass); - } - -} diff --git a/core/test/net/sf/openrocket/simplerocket.ork b/core/test/net/sf/openrocket/simplerocket.ork deleted file mode 100644 index 453cdec9..00000000 Binary files a/core/test/net/sf/openrocket/simplerocket.ork and /dev/null differ diff --git a/core/test/net/sf/openrocket/simulation/customexpression/TestExpressions.java b/core/test/net/sf/openrocket/simulation/customexpression/TestExpressions.java deleted file mode 100644 index d67bca0a..00000000 --- a/core/test/net/sf/openrocket/simulation/customexpression/TestExpressions.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.sf.openrocket.simulation.customexpression; - -import org.junit.Test; - -import static org.junit.Assert.*; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.rocketcomponent.Rocket; - -public class TestExpressions { - - @Test - public void testExpressions() { - // TODO Auto-generated constructor stub - - OpenRocketDocument doc = new OpenRocketDocument(new Rocket()); - - //CustomExpression exp = new CustomExpression(doc, "Kinetic energy", "Ek", "J", ".5*m*Vt^2"); - - CustomExpression exp = new CustomExpression(doc, "Average mass", "Mavg", "kg", "mean(m[0:t])"); - System.out.println( exp.getExpressionString() ); - - } -} diff --git a/core/test/net/sf/openrocket/unit/FractionalUnitTest.java b/core/test/net/sf/openrocket/unit/FractionalUnitTest.java deleted file mode 100644 index 093f0596..00000000 --- a/core/test/net/sf/openrocket/unit/FractionalUnitTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package net.sf.openrocket.unit; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class FractionalUnitTest { - - private final static Unit testUnit = new FractionalUnit(1, "unit", "unit", 4, 0.5); - private final static Unit testUnitApprox = new FractionalUnit(1, "unit", "unit", 16, 0.5, 0.02); - - private final static Unit inchUnit = new FractionalUnit(0.0254, "in/64", "in", 64, 1d/16d); - - @Test - public void testRound() { - - assertEquals(-1d, testUnit.round(-1.125), 0.0); // rounds to -1 since mod is even - assertEquals(-1d, testUnit.round(-1.0), 0.0); - assertEquals(-1d, testUnit.round(-.875), 0.0); // rounds to -1 since mod is even - - assertEquals(-0.75d, testUnit.round(-.874), 0.0); - assertEquals(-0.75d, testUnit.round(-.75), 0.0); - assertEquals(-0.75d, testUnit.round(-.626), 0.0); - - assertEquals(-0.5d, testUnit.round(-.625), 0.0); // rounds to -.5 since mod is even - assertEquals(-0.5d, testUnit.round(-.5), 0.0); - assertEquals(-0.5d, testUnit.round(-.375), 0.0); // rounds to -.5 since mod is even - - assertEquals(-0.25d, testUnit.round(-.374), 0.0); - assertEquals(-0.25d, testUnit.round(-.25), 0.0); - assertEquals(-0.25d, testUnit.round(-.126), 0.0); - - assertEquals(0d, testUnit.round(-.125), 0.0); - assertEquals(0d, testUnit.round(0), 0.0); - assertEquals(0d, testUnit.round(.125), 0.0); - - assertEquals(0.25d, testUnit.round(.126), 0.0); - assertEquals(0.25d, testUnit.round(.25), 0.0); - assertEquals(0.25d, testUnit.round(.374), 0.0); - - assertEquals(0.5d, testUnit.round(.375), 0.0); // rounds to .5 since mod is even - assertEquals(0.5d, testUnit.round(.5), 0.0); - assertEquals(0.5d, testUnit.round(.625), 0.0); // rounds to .5 since mod is even - - assertEquals(0.75d, testUnit.round(.626), 0.0); - assertEquals(0.75d, testUnit.round(.75), 0.0); - assertEquals(0.75d, testUnit.round(.874), 0.0); - - assertEquals(1d, testUnit.round(.875), 0.0); // rounds to 1 since mod is even - assertEquals(1d, testUnit.round(1.0), 0.0); - assertEquals(1d, testUnit.round(1.125), 0.0); // rounds to 1 since mod is even - - } - - @Test - public void testIncrement() { - - assertEquals( -1d, testUnit.getNextValue(-1.2), 0.0); - assertEquals( -1d, testUnit.getNextValue(-1.4), 0.0); - - assertEquals( -0.5d, testUnit.getNextValue(-0.7), 0.0); - assertEquals( -0.5d, testUnit.getNextValue(-0.9), 0.0); - assertEquals( -0.5d, testUnit.getNextValue(-1.0), 0.0); - - assertEquals( 0.0d, testUnit.getNextValue(-0.05), 0.0 ); - assertEquals( 0.0d, testUnit.getNextValue(-0.062), 0.0 ); - assertEquals( 0.0d, testUnit.getNextValue(-0.07), 0.0 ); - assertEquals( 0.0d, testUnit.getNextValue(-0.11), 0.0 ); - - assertEquals( 0.5d, testUnit.getNextValue(0), 0.0 ); - assertEquals( 0.5d, testUnit.getNextValue(0.01), 0.0 ); - assertEquals( 0.5d, testUnit.getNextValue(0.062), 0.0 ); - assertEquals( 0.5d, testUnit.getNextValue(0.0625), 0.0); - - assertEquals( 1d, testUnit.getNextValue(0.51), 0.0); - assertEquals( 1d, testUnit.getNextValue(0.7), 0.0); - } - - @Test - public void testDecrement() { - - assertEquals( -1.5d, testUnit.getPreviousValue(-1.2), 0.0); - assertEquals( -1.5d, testUnit.getPreviousValue(-1.4), 0.0); - assertEquals( -1.5d, testUnit.getPreviousValue(-1.0), 0.0); - - assertEquals( -1d, testUnit.getPreviousValue(-0.7), 0.0); - assertEquals( -1d, testUnit.getPreviousValue(-0.9), 0.0); - - assertEquals( -0.5d, testUnit.getPreviousValue(-0.01), 0.0 ); - assertEquals( -0.5d, testUnit.getPreviousValue(-0.05), 0.0 ); - assertEquals( -0.5d, testUnit.getPreviousValue(-0.062), 0.0 ); - assertEquals( -0.5d, testUnit.getPreviousValue(-0.07), 0.0 ); - assertEquals( -0.5d, testUnit.getPreviousValue(0), 0.0 ); - - assertEquals( 0.0d, testUnit.getPreviousValue(0.49), 0.0 ); - assertEquals( 0.0d, testUnit.getPreviousValue(0.262), 0.0 ); - assertEquals( 0.0d, testUnit.getPreviousValue(0.51), 0.0); - - assertEquals( 0.5d, testUnit.getPreviousValue(0.7), 0.0); - - assertEquals( 1.0d, testUnit.getPreviousValue(1.2), 0.0); - } - - @Test - public void testToStringDefaultPrecision() { - - // default epsilon is 0.025 - assertEquals("-1.2", testUnit.toString(-1.2)); - assertEquals("-1 \u00B9\u2044\u2084", testUnit.toString(-1.225)); - assertEquals("-1 \u00B9\u2044\u2084", testUnit.toString(-1.227)); - assertEquals("-1 \u00B9\u2044\u2084", testUnit.toString(-1.25)); - assertEquals("-1 \u00B9\u2044\u2084", testUnit.toString(-1.25)); - assertEquals("-1 \u00B9\u2044\u2084", testUnit.toString(-1.275)); - assertEquals("-1.3", testUnit.toString(-1.3)); - - assertEquals("-0.2", testUnit.toString(-.2)); - assertEquals("-\u00B9\u2044\u2084", testUnit.toString(-.225)); - assertEquals("-\u00B9\u2044\u2084", testUnit.toString(-.25)); - assertEquals("-\u00B9\u2044\u2084", testUnit.toString(-.274)); - //assertEquals("-1/4", testUnit.toString(-.275)); // this has roundoff error which pushes it over epsilon - assertEquals("-0.3", testUnit.toString(-.3)); - - assertEquals("-0.1", testUnit.toString(-.1)); - assertEquals("0", testUnit.toString(-0.024)); - assertEquals("0", testUnit.toString(0)); - assertEquals("0", testUnit.toString(.024)); - assertEquals("0.1", testUnit.toString(.1)); - - assertEquals("0.2", testUnit.toString(.2)); - assertEquals("\u00B9\u2044\u2084", testUnit.toString(.225)); - assertEquals("\u00B9\u2044\u2084", testUnit.toString(.25)); - assertEquals("\u00B9\u2044\u2084", testUnit.toString(.274)); - assertEquals("0.3", testUnit.toString(.3)); - - assertEquals("1.2", testUnit.toString(1.2)); - assertEquals("1 \u00B9\u2044\u2084", testUnit.toString(1.225)); - assertEquals("1 \u00B9\u2044\u2084", testUnit.toString(1.25)); - assertEquals("1 \u00B9\u2044\u2084", testUnit.toString(1.275)); - assertEquals("1.3", testUnit.toString(1.3)); - - } - - @Test - public void testToStringWithPrecision() { - - // epsilon is .02 - assertEquals("-1 \u00B3\u2044\u2081\u2086", testUnitApprox.toString(-1.2)); - assertEquals("-1.225", testUnitApprox.toString(-1.225)); - assertEquals("-1 \u00B9\u2044\u2084", testUnitApprox.toString(-1.25)); - assertEquals("-1.275", testUnitApprox.toString(-1.275)); - assertEquals("-1 \u2075\u2044\u2081\u2086", testUnitApprox.toString(-1.3)); - - assertEquals("-\u00B3\u2044\u2081\u2086", testUnitApprox.toString(-.2)); - assertEquals("-0.225", testUnitApprox.toString(-.225)); - assertEquals("-\u00B9\u2044\u2084", testUnitApprox.toString(-.25)); - assertEquals("-0.275", testUnitApprox.toString(-.275)); - assertEquals("-\u2075\u2044\u2081\u2086", testUnitApprox.toString(-.3)); - - assertEquals("-0.1", testUnitApprox.toString(-.1)); - assertEquals("-0.024", testUnitApprox.toString(-0.024)); - assertEquals("0", testUnitApprox.toString(0)); - assertEquals("0.024", testUnitApprox.toString(.024)); - assertEquals("0.1", testUnitApprox.toString(.1)); - - assertEquals("\u00B3\u2044\u2081\u2086", testUnitApprox.toString(.2)); - assertEquals("0.225", testUnitApprox.toString(.225)); - assertEquals("\u00B9\u2044\u2084", testUnitApprox.toString(.25)); - assertEquals("0.275", testUnitApprox.toString(.275)); - assertEquals("\u2075\u2044\u2081\u2086", testUnitApprox.toString(.3)); - - assertEquals("1 \u00B3\u2044\u2081\u2086", testUnitApprox.toString(1.2)); - assertEquals("1.225", testUnitApprox.toString(1.225)); - assertEquals("1 \u00B9\u2044\u2084", testUnitApprox.toString(1.25)); - assertEquals("1.275", testUnitApprox.toString(1.275)); - assertEquals("1 \u2075\u2044\u2081\u2086", testUnitApprox.toString(1.3)); - - } - - @Test - public void testInchToString() { - - // Just some random test points. - assertEquals( "\u00B9\u2044\u2086\u2084", inchUnit.toString( 1d/64d*0.0254)); - - assertEquals( "-\u2075\u2044\u2086\u2084", inchUnit.toString( -5d/64d*0.0254)); - - assertEquals( "4 \u00B9\u2044\u2082", inchUnit.toString( 9d/2d*0.0254)); - - assertEquals( "0.002", inchUnit.toString( 0.002*0.0254)); - - // default body tube length: - double length = 8d * 0.025; - - assertEquals( "7 \u2077\u2044\u2088", inchUnit.toString( length) ); - - // had problems with roundoff in decrement. - - double v = inchUnit.toUnit(length); - for ( int i = 0; i< 15; i++ ) { - assertTrue( v > inchUnit.getPreviousValue(v) ); - v = inchUnit.getPreviousValue(v); - } - - } - -} diff --git a/core/test/net/sf/openrocket/unit/UnitToStringTest.java b/core/test/net/sf/openrocket/unit/UnitToStringTest.java deleted file mode 100644 index 6b96a5f1..00000000 --- a/core/test/net/sf/openrocket/unit/UnitToStringTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package net.sf.openrocket.unit; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class UnitToStringTest { - - @Test - public void testPositiveToString() { - // very small positive numbers ( < 0.0005) are returned as "0" - assertEquals("0",Unit.NOUNIT2.toString(0.00040)); - assertEquals("0",Unit.NOUNIT2.toString(0.00050)); // check boundary of change in format - - // positive number < 0.095 use 3 digit decimal format - assertEquals("0.001",Unit.NOUNIT2.toString(0.00051)); // check boundary of change in format - assertEquals("0.001",Unit.NOUNIT2.toString(0.00060)); - - // rounding at third digit. - assertEquals("0.001",Unit.NOUNIT2.toString(0.0014)); - assertEquals("0.002",Unit.NOUNIT2.toString(0.0015)); // round to even - assertEquals("0.002",Unit.NOUNIT2.toString(0.0016)); - assertEquals("0.002",Unit.NOUNIT2.toString(0.0024)); - assertEquals("0.002",Unit.NOUNIT2.toString(0.0025)); // round to even - assertEquals("0.003",Unit.NOUNIT2.toString(0.0026)); - assertEquals("0.009",Unit.NOUNIT2.toString(0.0094)); - - assertEquals("0.01",Unit.NOUNIT2.toString(0.0095)); // no trailing zeros after rounding - - assertEquals("0.011",Unit.NOUNIT2.toString(0.0114)); - assertEquals("0.012",Unit.NOUNIT2.toString(0.0115)); // round to even - assertEquals("0.012",Unit.NOUNIT2.toString(0.0119)); - assertEquals("0.012",Unit.NOUNIT2.toString(0.0124)); - assertEquals("0.012",Unit.NOUNIT2.toString(0.0125)); // round to even - assertEquals("0.013",Unit.NOUNIT2.toString(0.0129)); - - assertEquals("0.095",Unit.NOUNIT2.toString(0.0949)); // boundary check - - // positive numbers < 100 - assertEquals("0.1",Unit.NOUNIT2.toString(0.095)); // boundary check - - assertEquals("0.11",Unit.NOUNIT2.toString(0.111)); - assertEquals("0.12",Unit.NOUNIT2.toString(0.115)); // round to even - assertEquals("0.12",Unit.NOUNIT2.toString(0.117)); - assertEquals("0.12",Unit.NOUNIT2.toString(0.121)); - assertEquals("0.12",Unit.NOUNIT2.toString(0.125)); // round to even - assertEquals("0.13",Unit.NOUNIT2.toString(0.127)); - - assertEquals("1.11",Unit.NOUNIT2.toString(1.113)); - assertEquals("1.12",Unit.NOUNIT2.toString(1.115)); // round to even - assertEquals("1.12",Unit.NOUNIT2.toString(1.117)); - assertEquals("1.12",Unit.NOUNIT2.toString(1.123)); - assertEquals("1.12",Unit.NOUNIT2.toString(1.125)); // round to even - assertEquals("1.13",Unit.NOUNIT2.toString(1.127)); - - assertEquals("12.3",Unit.NOUNIT2.toString(12.320)); - assertEquals("12.4",Unit.NOUNIT2.toString(12.350)); // round to even - assertEquals("12.4",Unit.NOUNIT2.toString(12.355)); - assertEquals("12.4",Unit.NOUNIT2.toString(12.420)); - assertEquals("12.4",Unit.NOUNIT2.toString(12.450)); // round to even - assertEquals("12.5",Unit.NOUNIT2.toString(12.455)); - - // positive numbers <= 1E6 - assertEquals("123",Unit.NOUNIT2.toString(123.20)); - assertEquals("124",Unit.NOUNIT2.toString(123.50)); // round to even - assertEquals("124",Unit.NOUNIT2.toString(123.55)); - assertEquals("124",Unit.NOUNIT2.toString(124.20)); - assertEquals("124",Unit.NOUNIT2.toString(124.50)); // round to even - assertEquals("125",Unit.NOUNIT2.toString(124.55)); - - assertEquals("1234",Unit.NOUNIT2.toString(1234.2)); - assertEquals("1234",Unit.NOUNIT2.toString(1234.5)); // round to even - assertEquals("1235",Unit.NOUNIT2.toString(1234.6)); - assertEquals("1235",Unit.NOUNIT2.toString(1235.2)); - assertEquals("1236",Unit.NOUNIT2.toString(1235.5)); // round to even - assertEquals("1236",Unit.NOUNIT2.toString(1235.6)); - - assertEquals("123457",Unit.NOUNIT2.toString(123456.789)); - - assertEquals("1000000",Unit.NOUNIT2.toString(1000000)); // boundary check - - // positive numbers > 1E6 - assertEquals("1.23E6",Unit.NOUNIT2.toString(1234567.89)); - assertEquals("1.23E7",Unit.NOUNIT2.toString(12345678.9)); - - - } - - @Test - public void testNegativeToString() { - // very small negative numbers ( < 0.0005) are returned as "0" - assertEquals("0",Unit.NOUNIT2.toString(-0.00040)); - assertEquals("0",Unit.NOUNIT2.toString(-0.00050)); // check boundary of change in format - - // negative number < 0.095 use 3 digit decimal format - assertEquals("-0.001",Unit.NOUNIT2.toString(-0.00051)); // check boundary of change in format - assertEquals("-0.001",Unit.NOUNIT2.toString(-0.00060)); - - // rounding at third digit. - assertEquals("-0.001",Unit.NOUNIT2.toString(-0.0014)); - assertEquals("-0.002",Unit.NOUNIT2.toString(-0.0015)); // round to even - assertEquals("-0.002",Unit.NOUNIT2.toString(-0.0016)); - assertEquals("-0.002",Unit.NOUNIT2.toString(-0.0024)); - assertEquals("-0.002",Unit.NOUNIT2.toString(-0.0025)); // round to even - assertEquals("-0.003",Unit.NOUNIT2.toString(-0.0026)); - assertEquals("-0.009",Unit.NOUNIT2.toString(-0.0094)); - - assertEquals("-0.01",Unit.NOUNIT2.toString(-0.0095)); // no trailing zeros after rounding - - assertEquals("-0.011",Unit.NOUNIT2.toString(-0.0114)); - assertEquals("-0.012",Unit.NOUNIT2.toString(-0.0115)); // round to even - assertEquals("-0.012",Unit.NOUNIT2.toString(-0.0119)); - assertEquals("-0.012",Unit.NOUNIT2.toString(-0.0124)); - assertEquals("-0.012",Unit.NOUNIT2.toString(-0.0125)); // round to even - assertEquals("-0.013",Unit.NOUNIT2.toString(-0.0129)); - - assertEquals("-0.095",Unit.NOUNIT2.toString(-0.0949)); // boundary check - - // negative numbers < 100 - assertEquals("-0.1",Unit.NOUNIT2.toString(-0.095)); // boundary check - - assertEquals("-0.11",Unit.NOUNIT2.toString(-0.111)); - assertEquals("-0.12",Unit.NOUNIT2.toString(-0.115)); // round to even - assertEquals("-0.12",Unit.NOUNIT2.toString(-0.117)); - assertEquals("-0.12",Unit.NOUNIT2.toString(-0.121)); - assertEquals("-0.12",Unit.NOUNIT2.toString(-0.125)); // round to even - assertEquals("-0.13",Unit.NOUNIT2.toString(-0.127)); - - assertEquals("-1.11",Unit.NOUNIT2.toString(-1.113)); - assertEquals("-1.12",Unit.NOUNIT2.toString(-1.115)); // round to even - assertEquals("-1.12",Unit.NOUNIT2.toString(-1.117)); - assertEquals("-1.12",Unit.NOUNIT2.toString(-1.123)); - assertEquals("-1.12",Unit.NOUNIT2.toString(-1.125)); // round to even - assertEquals("-1.13",Unit.NOUNIT2.toString(-1.127)); - - assertEquals("-12.3",Unit.NOUNIT2.toString(-12.320)); - assertEquals("-12.4",Unit.NOUNIT2.toString(-12.350)); // round to even - assertEquals("-12.4",Unit.NOUNIT2.toString(-12.355)); - assertEquals("-12.4",Unit.NOUNIT2.toString(-12.420)); - assertEquals("-12.4",Unit.NOUNIT2.toString(-12.450)); // round to even - assertEquals("-12.5",Unit.NOUNIT2.toString(-12.455)); - - // negative numbers <= 1E6 - assertEquals("-123",Unit.NOUNIT2.toString(-123.20)); - assertEquals("-124",Unit.NOUNIT2.toString(-123.50)); // round to even - assertEquals("-124",Unit.NOUNIT2.toString(-123.55)); - assertEquals("-124",Unit.NOUNIT2.toString(-124.20)); - assertEquals("-124",Unit.NOUNIT2.toString(-124.50)); // round to even - assertEquals("-125",Unit.NOUNIT2.toString(-124.55)); - - assertEquals("-1234",Unit.NOUNIT2.toString(-1234.2)); - assertEquals("-1234",Unit.NOUNIT2.toString(-1234.5)); // round to even - assertEquals("-1235",Unit.NOUNIT2.toString(-1234.6)); - assertEquals("-1235",Unit.NOUNIT2.toString(-1235.2)); - assertEquals("-1236",Unit.NOUNIT2.toString(-1235.5)); // round to even - assertEquals("-1236",Unit.NOUNIT2.toString(-1235.6)); - - assertEquals("-123457",Unit.NOUNIT2.toString(-123456.789)); - - assertEquals("-1000000",Unit.NOUNIT2.toString(-1000000)); // boundary check - - // negative numbers > 1E6 - assertEquals("-1.23E6",Unit.NOUNIT2.toString(-1234567.89)); - assertEquals("-1.23E7",Unit.NOUNIT2.toString(-12345678.9)); - - - } - - -} diff --git a/core/test/net/sf/openrocket/unit/ValueTest.java b/core/test/net/sf/openrocket/unit/ValueTest.java deleted file mode 100644 index 9440c4d0..00000000 --- a/core/test/net/sf/openrocket/unit/ValueTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.unit; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ValueTest { - - @Test - public void testValues() { - Value v1, v2; - - v1 = new Value(273.15, UnitGroup.UNITS_TEMPERATURE.findApproximate("F")); - v2 = new Value(283.15, UnitGroup.UNITS_TEMPERATURE.findApproximate("C")); - - assertTrue(v1.compareTo(v2) > 0); - assertTrue(v2.compareTo(v1) < 0); - assertTrue(v1.compareTo(v1) == 0); - assertTrue(v2.compareTo(v2) == 0); - - v2 = new Value(283.15, UnitGroup.UNITS_TEMPERATURE.findApproximate("K")); - assertTrue(v1.compareTo(v2) > 0); - assertTrue(v2.compareTo(v1) < 0); - assertEquals("283 K", v2.toString()); - - v2 = new Value(283.15, UnitGroup.UNITS_TEMPERATURE.findApproximate("F")); - assertTrue(v1.compareTo(v2) < 0); - assertTrue(v2.compareTo(v1) > 0); - - - v1 = new Value(Double.NaN, UnitGroup.UNITS_TEMPERATURE.findApproximate("F")); - assertTrue(v1.compareTo(v2) > 0); - assertTrue(v2.compareTo(v1) < 0); - - v2 = new Value(Double.NaN, UnitGroup.UNITS_TEMPERATURE.findApproximate("F")); - assertTrue(v1.compareTo(v2) == 0); - assertTrue(v1.compareTo(v2) == 0); - assertEquals("N/A", v1.toString()); - assertEquals("N/A", v2.toString()); - - } - -} diff --git a/core/test/net/sf/openrocket/util/ArrayUtilsTest.java b/core/test/net/sf/openrocket/util/ArrayUtilsTest.java deleted file mode 100644 index ee8b5e96..00000000 --- a/core/test/net/sf/openrocket/util/ArrayUtilsTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -public class ArrayUtilsTest { - - @Test(expected=NullPointerException.class) - public void testCopyOfRange_NullArg() { - ArrayUtils.copyOfRange( (Byte[]) null, 0 , 14); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testCopyOfRange_StartTooBig() { - Integer[] original = new Integer[5]; - ArrayUtils.copyOfRange( original, 8 , 14); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testCopyOfRange_StartTooSmall() { - Integer[] original = new Integer[5]; - ArrayUtils.copyOfRange( original, -1 , 14); - } - - @Test(expected=IllegalArgumentException.class) - public void testCopyOfRange_IllegalRange() { - Integer[] original = new Integer[5]; - ArrayUtils.copyOfRange( original, 5, 0 ); - } - - @Test - public void testCopyOfRange() { - Integer[] original = new Integer[5]; - for ( int i =0; i < 5; i++ ) { - original[i] = i; - } - Integer[] copy = ArrayUtils.copyOfRange( original, 0, 0 ); - assertEquals( 0, copy.length ); - - copy = ArrayUtils.copyOfRange( original, 2, 2 ); - assertEquals( 0, copy.length ); - - copy = ArrayUtils.copyOfRange( original, 0, 2 ); - assertEquals( 2, copy.length ); - for( int i =0; i< 2; i++ ) { - assertEquals( original[i], copy[i] ); - } - - copy = ArrayUtils.copyOfRange( original, 2, 5 ); - assertEquals( 3, copy.length ); - for( int i =0; i< 3; i++ ) { - assertEquals( original[i+2], copy[i] ); - } - - copy = ArrayUtils.copyOfRange( original, 2, 15 ); - assertEquals( 13, copy.length ); - for( int i =0; i< 3; i++ ) { - assertEquals( original[i+2], copy[i] ); - } - for ( int i=3; i< 13; i++ ) { - assertNull(copy[i]); - } - - } - - @Test - public void testCopyOfRange_ZeroSize() { - Integer[] original = new Integer[0]; - - Integer[] copy = ArrayUtils.copyOfRange( original, 0, 0 ); - assertEquals( 0, copy.length ); - - copy = ArrayUtils.copyOfRange( original, 0, 2 ); - assertEquals( 2, copy.length ); - for( int i =0; i< 2; i++ ) { - assertEquals( null, copy[i] ); - } - - } - - @Test - public void testRante0() { - double[] ary = ArrayUtils.range(0., 0., 1.0); - assertEquals(1, ary.length); - assertEquals( 0.0, ary[0], 0.0 ); - } - - @Test - public void testRange1() { - double[] ary = ArrayUtils.range(0.0, 0.5, 1.0); - assertEquals(1, ary.length); - assertEquals( 0.0, ary[0], 0.0 ); - } - - @Test - public void testRange2() { - double[] ary = ArrayUtils.range(0.0, 1.0, 0.5); - assertEquals(3, ary.length); - assertEquals( 0.0, ary[0], 0.0 ); - assertEquals( 0.5, ary[1], 0.0 ); - assertEquals( 1.0, ary[2], 0.0 ); - } - - @Test - public void testRange3() { - double [] ary = ArrayUtils.range(0.0, 1.0, 0.4 ); - assertEquals(3, ary.length); - assertEquals( 0.0, ary[0], 0.0 ); - assertEquals( 0.4, ary[1], 0.0 ); - assertEquals( 0.8, ary[2], 0.0 ); - } - - @Test - public void testRange4() { - double[] ary = ArrayUtils.range(0.0,10.0, 0.5); - assertEquals( 21, ary.length ); - int i =0; - for( double d = 0.0; d < 10.2; d+=0.5){ - assertEquals(d,ary[i++],0.0); - } - assertEquals( i, ary.length ); - } - -} diff --git a/core/test/net/sf/openrocket/util/Base64Test.java b/core/test/net/sf/openrocket/util/Base64Test.java deleted file mode 100644 index edf13005..00000000 --- a/core/test/net/sf/openrocket/util/Base64Test.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.Arrays; -import java.util.Random; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class Base64Test { - - @Test - public void oldMainTest() throws Exception { - - // TODO - this test case should probably be less random and more targeted to - // special cases such as: - // null input - // empty input - // decoding bad string - - Random rnd = new Random(); - - for (int round=0; round < 1000; round++) { - int n = rnd.nextInt(1000); - n = 100000; - - byte[] array = new byte[n]; - rnd.nextBytes(array); - - String encoded = Base64.encode(array); - - byte[] decoded = null; - decoded = Base64.decode(encoded); - - if (!Arrays.equals(array, decoded)) { - fail("Data differs! n="+n); - } - System.out.println("n="+n+" ok!"); - - } - } -} \ No newline at end of file diff --git a/core/test/net/sf/openrocket/util/BaseTestCase/BaseTestCase.java b/core/test/net/sf/openrocket/util/BaseTestCase/BaseTestCase.java deleted file mode 100644 index c5d1feb1..00000000 --- a/core/test/net/sf/openrocket/util/BaseTestCase/BaseTestCase.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.sf.openrocket.util.BaseTestCase; - -import net.sf.openrocket.gui.util.SwingPreferences; -import net.sf.openrocket.startup.Application; - -import org.junit.BeforeClass; - -public class BaseTestCase { - - @BeforeClass - public static void setUpApplication () { - - Application.setPreferences( new SwingPreferences() ); - - } -} diff --git a/core/test/net/sf/openrocket/util/CoordinateTest.java b/core/test/net/sf/openrocket/util/CoordinateTest.java deleted file mode 100644 index 0c74a3a1..00000000 --- a/core/test/net/sf/openrocket/util/CoordinateTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class CoordinateTest { - - private static final double EPS = 0.0000000001; - - @Test - public void coordinateTest() { - - Coordinate x = new Coordinate(1,1,1,1); - Coordinate y = new Coordinate(1,2,3,4); - - assertCoordinateEquals(new Coordinate(2,1,1,1), x.setX(2)); - assertCoordinateEquals(new Coordinate(1,2,1,1), x.setY(2)); - assertCoordinateEquals(new Coordinate(1,1,2,1), x.setZ(2)); - assertCoordinateEquals(new Coordinate(1,1,1,2), x.setWeight(2)); - assertCoordinateEquals(new Coordinate(2,3,4,1), x.setXYZ(y).add(1,1,1)); - - assertFalse(x.isNaN()); - assertTrue(x.setX(Double.NaN).isNaN()); - assertTrue(Coordinate.NaN.isNaN()); - - assertTrue(x.isWeighted()); - assertFalse(x.setWeight(0).isWeighted()); - - - assertCoordinateEquals(x, x.add(Coordinate.NUL)); - assertCoordinateEquals(new Coordinate(2,3,4,5), x.add(y)); - assertCoordinateEquals(new Coordinate(2,3,4,1), x.add(1,2,3)); - assertCoordinateEquals(new Coordinate(2,3,4,5), x.add(1,2,3,4)); - - assertCoordinateEquals(new Coordinate(0,-1,-2,1), x.sub(y)); - assertCoordinateEquals(new Coordinate(0,-1,-2,1), x.sub(1,2,3)); - - assertCoordinateEquals(new Coordinate(2,4,6,8), y.multiply(2)); - - assertEquals(1+2+3, y.dot(x), EPS); - assertEquals(1+2+3, x.dot(y), EPS); - assertEquals(1+2+3, Coordinate.dot(x,y), EPS); - assertEquals(x.dot(x), x.length2(), EPS); - assertEquals(y.dot(y), y.length2(), EPS); - assertEquals(Math.sqrt(1+4+9), y.length(), EPS); - assertEquals(1, y.normalize().length(), EPS); - - assertCoordinateEquals(new Coordinate(1.75,1.75,1.75,4), - new Coordinate(1,1,1,1).average(new Coordinate(2,2,2,3))); - assertCoordinateEquals(new Coordinate(1,1,1,1), - new Coordinate(1,1,1,1).average(new Coordinate(2,2,2,0))); - assertCoordinateEquals(new Coordinate(1.5,1.5,1.5,0), - new Coordinate(1,1,1,0).average(new Coordinate(2,2,2,0))); - - } - - - private void assertCoordinateEquals(Coordinate a, Coordinate b) { - assertEquals(a, b); - assertEquals(a.weight, b.weight, EPS); - } - -} diff --git a/core/test/net/sf/openrocket/util/ExpressionParserTest.java b/core/test/net/sf/openrocket/util/ExpressionParserTest.java deleted file mode 100644 index efbabe9c..00000000 --- a/core/test/net/sf/openrocket/util/ExpressionParserTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ExpressionParserTest { - - private static final double EPS = 1e-10; - - private ExpressionParser parser = new ExpressionParser(); - - @Test - public void testPlainNumber() throws InvalidExpressionException { - assertEquals(1.0, parser.parse("1"), EPS); - assertEquals(1.0, parser.parse("\t 1 "), EPS); - assertEquals(0.9, parser.parse(".9"), EPS); - assertEquals(1.0, parser.parse("1."), EPS); - assertEquals(1.2, parser.parse("1.2"), EPS); - assertEquals(1.2, parser.parse("01.200"), EPS); - } - - @Test - public void testNegativeNumber() throws InvalidExpressionException { - assertEquals(-1.0, parser.parse("-1"), EPS); - assertEquals(-15.0, parser.parse("-15"), EPS); - assertEquals(-0.9, parser.parse("-.9"), EPS); - assertEquals(-1.0, parser.parse("-1."), EPS); - assertEquals(-1.2, parser.parse("-1.2"), EPS); - assertEquals(-1.2, parser.parse("-01.200"), EPS); - } - - - @Test - public void testDecimalComma() throws InvalidExpressionException { - assertEquals(1.0, parser.parse("1,"), EPS); - assertEquals(1.2, parser.parse("1,2"), EPS); - assertEquals(1.2, parser.parse("01,200"), EPS); - assertEquals(0.9, parser.parse(",9"), EPS); - } - - - @Test - public void testSimpleExpression() throws InvalidExpressionException { - assertEquals(3.0, parser.parse("1+2"), EPS); - assertEquals(6.0, parser.parse("1+2.5*2"), EPS); - assertEquals(7.0, parser.parse("(1+2.5) * 2"), EPS); - assertEquals(1.0 + 2.0 / 3.0, parser.parse("1+2/3"), EPS); - } - - @Test - public void testFraction() throws InvalidExpressionException { - assertEquals(1.5, parser.parse("1 1/2"), EPS); - assertEquals(11 + 11.0 / 22.0, parser.parse("11 11/22"), EPS); - assertEquals(-11 - 11.0 / 22.0, parser.parse("-11 11/22"), EPS); - assertEquals(1.5, parser.parse(" 1 1 / 2"), EPS); - assertEquals(11 + 11.0 / 22.0, parser.parse(" 11 11 / 22"), EPS); - assertEquals(2.0 + 3.0 / 7.0, parser.parse("1 + 1 3/7"), EPS); - assertEquals(2.0 + 3.0 / 7.0, parser.parse("1 + 1 3/7"), EPS); - assertEquals(3.0, parser.parse("1 1/2* 2"), EPS); - assertEquals(3.0, parser.parse("1 1/2* 2"), EPS); - } - - @Test - public void testCharConversion() throws InvalidExpressionException { - assertEquals(1 + 1.0 / 9.0, parser.parse("1 \u2081 \u2044 \u2089"), EPS); - } - - @Test - public void testInvalidExpression() { - expectInvalid("1+"); - expectInvalid("1+2/"); - expectInvalid("1 2"); - expectInvalid("12 2.5"); - expectInvalid("1 2.5/4"); - expectInvalid("11 22.55/44"); - expectInvalid("1 2/4.1"); - expectInvalid("11 22/44.11"); - expectInvalid("1.2 3/4"); - expectInvalid("12.23 34/45"); - - expectInvalid("1. 2"); - expectInvalid("1 .2"); - } - - private void expectInvalid(String exp) { - try { - double value = parser.parse(exp); - fail("Expression '" + exp + "' evaluated to " + value + ", expected failure"); - } catch (InvalidExpressionException e) { - // expected - } - } -} diff --git a/core/test/net/sf/openrocket/util/GeodeticComputationStrategyTest.java b/core/test/net/sf/openrocket/util/GeodeticComputationStrategyTest.java deleted file mode 100644 index 29efe41c..00000000 --- a/core/test/net/sf/openrocket/util/GeodeticComputationStrategyTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class GeodeticComputationStrategyTest { - - @Test - public void testSpericalAddCoordinate() { - - double arcmin = (1.0 / 60.0); - double arcsec = (1.0 / (60.0 * 60.0)); - - double lat1 = 50.0 + 3 * arcmin + 59 * arcsec; - double lon1 = -1.0 * (5 + 42 * arcmin + 53 * arcsec); //W - - double lat2 = 58 + 38 * arcmin + 38 * arcsec; - double lon2 = -1.0 * (3 + 4 * arcmin + 12 * arcsec); - - double range = 968.9 * 1000.0; - double bearing = (9.0 + 7 * arcmin + 11 * arcsec) * (Math.PI / 180.0); - - Coordinate coord = new Coordinate(range * Math.sin(bearing), range * Math.cos(bearing), 1000.0); - WorldCoordinate wc = new WorldCoordinate(lat1, lon1, 0.0); - wc = GeodeticComputationStrategy.SPHERICAL.addCoordinate(wc, coord); - - System.out.println(wc.getLatitudeDeg()); - System.out.println(lat2); - - System.out.println(wc.getLongitudeDeg()); - System.out.println(lon2); - - assertEquals(lat2, wc.getLatitudeDeg(), 0.001); - assertEquals(lon2, wc.getLongitudeDeg(), 0.001); - assertEquals(1000.0, wc.getAltitude(), 0.0); - } - - - @Test - public void testAddCoordinates() { - - double min = 1 / 60.0; - double sec = 1 / 3600.0; - - - // Test zero movement - System.out.println("\nTesting zero movement"); - testAddCoordinate(50.0, 20.0, 0, 123, 50.0, 20.0, false); - - - /* - * These example values have been computed using the calculator at - * http://www.movable-type.co.uk/scripts/latlong.html - */ - - // Long distance NE over England, crosses Greenwich meridian - // 50 03N 005 42W to 58 38N 003 04E is 1109km at 027 16'07" - System.out.println("\nTesting 1109km NE over England"); - testAddCoordinate(50 + 3 * min, -5 - 42 * min, 1109000, 27 + 16 * min + 7 * sec, 58 + 38 * min, 3 + 4 * min, false); - - // SW over Brazil - // -10N -60E to -11N -61E is 155.9km at 224 25'34" - System.out.println("\nTesting 155km SW over Brazil"); - testAddCoordinate(-10, -60, 155900, 224 + 25 * min + 34 * sec, -11, -61, true); - - // NW over the 180 meridian - // 63N -179E to 63 01N 179E is 100.9km at 271 56'34" - System.out.println("\nTesting 100km NW over 180 meridian"); - testAddCoordinate(63, -179, 100900, 271 + 56 * min + 34 * sec, 63 + 1 * min, 179, true); - - // NE near the north pole - // 89 50N 0E to 89 45N 175E is 46.29 km at 003 00'01" - System.out.println("\nTesting 46km NE near north pole"); - testAddCoordinate(89 + 50 * min, 0, 46290, 3 + 0 * min + 1 * sec, 89 + 45 * min, 175, false); - - // S directly over south pole - // -89 50N 12E to -89 45N 192E is 46.33km at 180 00'00" - System.out.println("\nTesting 46km directly over south pole "); - testAddCoordinate(-89 - 50 * min, 12, 46330, 180, -89 - 45 * min, -168, false); - - } - - private void testAddCoordinate(double initialLatitude, double initialLongitude, double distance, double bearing, - double finalLatitude, double finalLongitude, boolean testFlat) { - - double tolerance; - - bearing = Math.toRadians(bearing); - - // positive X is EAST, positive Y is NORTH - double deltaX = distance * Math.sin(bearing); - double deltaY = distance * Math.cos(bearing); - - Coordinate coord = new Coordinate(deltaX, deltaY, 1000.0); - WorldCoordinate wc = new WorldCoordinate(initialLatitude, initialLongitude, 0.0); - - // Test SPHERICAL - tolerance = 0.0015 * distance / 111325; - System.out.println("\nSpherical tolerance: " + tolerance); - WorldCoordinate result = GeodeticComputationStrategy.SPHERICAL.addCoordinate(wc, coord); - - System.out.println("Difference Lat: " + Math.abs(finalLatitude - result.getLatitudeDeg())); - System.out.println("Difference Lon: " + Math.abs(finalLongitude - result.getLongitudeDeg())); - assertEquals(finalLatitude, result.getLatitudeDeg(), tolerance); - assertEquals(finalLongitude, result.getLongitudeDeg(), tolerance); - assertEquals(1000.0, result.getAltitude(), 0.0); - - - // Test WGS84 - /* - * Note: Since the example values are computed using a spherical earth approximation, - * the WGS84 method will have significantly larger errors. A tolerance of 1% accommodates - * all cases except the NE flight near the north pole, where the ellipsoidal effect is - * the greatest. - */ - tolerance = 0.04 * distance / 111325; - System.out.println("\nWGS84 tolerance: " + tolerance); - result = GeodeticComputationStrategy.WGS84.addCoordinate(wc, coord); - - System.out.println("Difference Lat: " + Math.abs(finalLatitude - result.getLatitudeDeg())); - System.out.println("Difference Lon: " + Math.abs(finalLongitude - result.getLongitudeDeg())); - assertEquals(finalLatitude, result.getLatitudeDeg(), tolerance); - assertEquals(finalLongitude, result.getLongitudeDeg(), tolerance); - assertEquals(1000.0, result.getAltitude(), 0.0); - - - // Test FLAT - if (testFlat) { - tolerance = 0.02 * distance / 111325; - System.out.println("\nFlat tolerance: " + tolerance); - result = GeodeticComputationStrategy.FLAT.addCoordinate(wc, coord); - - System.out.println("Difference Lat: " + Math.abs(finalLatitude - result.getLatitudeDeg())); - System.out.println("Difference Lon: " + Math.abs(finalLongitude - result.getLongitudeDeg())); - assertEquals(finalLatitude, result.getLatitudeDeg(), tolerance); - assertEquals(finalLongitude, result.getLongitudeDeg(), tolerance); - assertEquals(1000.0, result.getAltitude(), 0.0); - - } - - } - - - - @Test - public void testSpericalGetCoriolisAcceleration() { - - // For positive latitude and rotational velocity, a movement due east results in an acceleration due south - Coordinate velocity = new Coordinate(-1000, 0, 0); - WorldCoordinate wc = new WorldCoordinate(45, 0, 0); - double north_accel = GeodeticComputationStrategy.SPHERICAL.getCoriolisAcceleration(wc, velocity).y; - System.out.println("North accel " + north_accel); - assertTrue(north_accel < 0.0); - - } - -} diff --git a/core/test/net/sf/openrocket/util/LinearInterpolatorTest.java b/core/test/net/sf/openrocket/util/LinearInterpolatorTest.java deleted file mode 100644 index 600f82b1..00000000 --- a/core/test/net/sf/openrocket/util/LinearInterpolatorTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; -import org.junit.Test; - -public class LinearInterpolatorTest { - - @Test - public void oldMainTest() { - LinearInterpolator interpolator = new LinearInterpolator( - new double[] {1, 1.5, 2, 4, 5}, - new double[] {0, 1, 0, 2, 2} - ); - - double[] answer = new double[] { - /* x=0 */ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, - /* x=1 */ 0.00, 0.20, 0.40, 0.60, 0.80, 1.00, 0.80, 0.60, 0.40, 0.20, - /* x=2 */ 0.00, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, - /* x=3 */ 1.00, 1.10, 1.20, 1.30, 1.40, 1.50, 1.60, 1.70, 1.80, 1.90, - /* x=4 */ 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, - /* x=5 */ 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, 2.00, - /* x=6 */ 2.00 - }; - - double x = 0; - for (int i=0; i < answer.length; i++) { - assertEquals( "Answer wrong for x = " + x , answer[i], interpolator.getValue(x), 0.01 ); - x+= 0.1; - } - - } -} diff --git a/core/test/net/sf/openrocket/util/MathUtilTest.java b/core/test/net/sf/openrocket/util/MathUtilTest.java deleted file mode 100644 index 6b9c1e1a..00000000 --- a/core/test/net/sf/openrocket/util/MathUtilTest.java +++ /dev/null @@ -1,296 +0,0 @@ -package net.sf.openrocket.util; - -import static java.lang.Double.NaN; -import static java.lang.Math.PI; -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -public class MathUtilTest { - - public static final double EPS = 0.00000000001; - - /* - @Test - public void rangeTest() { - double[] a; - - a = MathUtil.range(0, 10, 2); - assertEquals(0, a[0], 0); - assertEquals(10, a[5], 0); - assertEquals(6, a.length, 0); - - a = MathUtil.range(1, 2, 2); - assertEquals(1, a[0], 0); - assertEquals(1, a.length, 0); - - } - */ - - @Test - public void miscMathTest() { - - assertEquals(PI * PI, MathUtil.pow2(PI), EPS); - assertEquals(PI * PI * PI, MathUtil.pow3(PI), EPS); - assertEquals(PI * PI * PI * PI, MathUtil.pow4(PI), EPS); - - assertEquals(1.0, MathUtil.clamp(0.9999, 1.0, 2.0), 0); - assertEquals(1.23, MathUtil.clamp(1.23, 1.0, 2.0), 0); - assertEquals(2.0, MathUtil.clamp(2 + EPS / 100, 1.0, 2.0), 0); - - assertEquals(1.0f, MathUtil.clamp(0.9999f, 1.0f, 2.0f), 0); - assertEquals(1.23f, MathUtil.clamp(1.23f, 1.0f, 2.0f), 0); - assertEquals(2.0f, MathUtil.clamp(2.0001f, 1.0f, 2.0f), 0); - - assertEquals(1, MathUtil.clamp(-3, 1, 5)); - assertEquals(3, MathUtil.clamp(3, 1, 5)); - assertEquals(5, MathUtil.clamp(6, 1, 5)); - - assertEquals(-1.0, MathUtil.sign(Double.NEGATIVE_INFINITY), EPS); - assertEquals(-1.0, MathUtil.sign(-100), EPS); - assertEquals(-1.0, MathUtil.sign(Math.nextAfter(0.0, -1.0)), EPS); - assertEquals(1.0, MathUtil.sign(Math.nextUp(0.0)), EPS); - assertEquals(1.0, MathUtil.sign(100), EPS); - assertEquals(1.0, MathUtil.sign(Double.POSITIVE_INFINITY), EPS); - } - - @Test - public void hypotTest() { - - for (int i = 0; i < 10000; i++) { - double x = Math.random() * 100 - 50; - double y = Math.random() * i - i / 2; - double z = Math.hypot(x, y); - assertEquals(z, MathUtil.hypot(x, y), EPS); - } - - } - - @Test - public void reduceTest() { - - for (int i = -1000; i < 1000; i++) { - double angle = Math.random() * 2 * PI; - double shift = angle + i * 2 * PI; - assertEquals(angle, MathUtil.reduce360(shift), EPS); - } - - for (int i = -1000; i < 1000; i++) { - double angle = Math.random() * 2 * PI - PI; - double shift = angle + i * 2 * PI; - assertEquals(angle, MathUtil.reduce180(shift), EPS); - } - - } - - @Test - public void minmaxTest() { - assertEquals(1.0, MathUtil.min(1.0, Math.nextUp(1.0)), 0); - assertEquals(1.0, MathUtil.min(1.0, Double.POSITIVE_INFINITY), 0); - assertEquals(1.0, MathUtil.min(NaN, 1.0), 0); - assertEquals(1.0, MathUtil.min(1.0, NaN), 0); - assertEquals(NaN, MathUtil.min(NaN, NaN), 0); - - assertEquals(Math.nextUp(1.0), MathUtil.max(1.0, Math.nextUp(1.0)), 0); - assertEquals(Double.POSITIVE_INFINITY, MathUtil.max(1.0, Double.POSITIVE_INFINITY), 0); - assertEquals(1.0, MathUtil.max(NaN, 1.0), 0); - assertEquals(1.0, MathUtil.max(1.0, NaN), 0); - assertEquals(NaN, MathUtil.max(NaN, NaN), 0); - - assertEquals(1.0, MathUtil.min(1.0, 2.0, 3.0), 0); - assertEquals(1.0, MathUtil.min(1.0, NaN, NaN), 0); - assertEquals(1.0, MathUtil.min(NaN, 1.0, NaN), 0); - assertEquals(1.0, MathUtil.min(NaN, NaN, 1.0), 0); - assertEquals(1.0, MathUtil.min(2.0, NaN, 1.0), 0); - assertEquals(1.0, MathUtil.min(1.0, 2.0, NaN), 0); - assertEquals(1.0, MathUtil.min(NaN, 2.0, 1.0), 0); - - assertEquals(3.0, MathUtil.max(1.0, 3.0, 2.0), 0); - assertEquals(1.0, MathUtil.max(1.0, NaN, NaN), 0); - assertEquals(1.0, MathUtil.max(NaN, 1.0, NaN), 0); - assertEquals(1.0, MathUtil.max(NaN, NaN, 1.0), 0); - assertEquals(2.0, MathUtil.max(2.0, NaN, 1.0), 0); - assertEquals(2.0, MathUtil.max(1.0, 2.0, NaN), 0); - assertEquals(2.0, MathUtil.max(NaN, 2.0, 1.0), 0); - - assertEquals(1.0, MathUtil.min(1.0, 2.0, 3.0, 4.0), 0); - assertEquals(1.0, MathUtil.min(1.0, NaN, NaN, NaN), 0); - assertEquals(1.0, MathUtil.min(NaN, 1.0, NaN, NaN), 0); - assertEquals(1.0, MathUtil.min(NaN, NaN, 1.0, NaN), 0); - assertEquals(1.0, MathUtil.min(2.0, NaN, 1.0, NaN), 0); - assertEquals(1.0, MathUtil.min(2.0, NaN, NaN, 1.0), 0); - assertEquals(1.0, MathUtil.min(1.0, 2.0, NaN, 3.0), 0); - assertEquals(1.0, MathUtil.min(NaN, 2.0, 3.0, 1.0), 0); - - } - - @Test - public void mapTest() { - assertEquals(1.0, MathUtil.map(1.0, 0.0, 5.0, -1.0, 9.0), EPS); - assertEquals(7.0, MathUtil.map(1.0, 5.0, 0.0, -1.0, 9.0), EPS); - assertEquals(7.0, MathUtil.map(1.0, 0.0, 5.0, 9.0, -1.0), EPS); - assertEquals(6.0, MathUtil.map(6.0, 0.0, 5.0, Math.nextUp(6.0), 6.0), EPS); - assertEquals(6.0, MathUtil.map(6.0, 0.0, 0.0, Math.nextUp(6.0), 6.0), EPS); - try { - MathUtil.map(6.0, 1.0, Math.nextUp(1.0), 1.0, 2.0); - fail("Should not be reached."); - } catch (IllegalArgumentException normal) { - } - - assertEquals(7.0, MathUtil.map(Math.nextUp(1.0), 0.0, 5.0, 9.0, -1.0), EPS); - } - - - @Test - public void mapCoordinateTest() { - assertEquals(new Coordinate(0.8, 2.0, 1.6, 4.0), - MathUtil.map(1.0, 0.0, 5.0, new Coordinate(0, 1, 2, 3), new Coordinate(4, 6, 0, 8))); - } - - - @Test - public void equalsTest() { - assertTrue(MathUtil.equals(1.0, 1.0 + MathUtil.EPSILON / 3)); - assertFalse(MathUtil.equals(1.0, 1.0 + MathUtil.EPSILON * 2)); - assertTrue(MathUtil.equals(-1.0, -1.0 + MathUtil.EPSILON / 3)); - assertFalse(MathUtil.equals(-1.0, -1.0 + MathUtil.EPSILON * 2)); - - for (double zero : new double[] { 0.0, MathUtil.EPSILON / 10, -MathUtil.EPSILON / 10 }) { - - assertTrue(MathUtil.equals(zero, MathUtil.EPSILON / 3)); - assertTrue(MathUtil.equals(zero, -MathUtil.EPSILON / 3)); - assertFalse(MathUtil.equals(zero, MathUtil.EPSILON * 2)); - assertFalse(MathUtil.equals(zero, -MathUtil.EPSILON * 2)); - - assertTrue(MathUtil.equals(MathUtil.EPSILON / 3, zero)); - assertTrue(MathUtil.equals(-MathUtil.EPSILON / 3, zero)); - assertFalse(MathUtil.equals(MathUtil.EPSILON * 2, zero)); - assertFalse(MathUtil.equals(-MathUtil.EPSILON * 2, zero)); - - } - - for (double value : new double[] { PI * 1e20, -PI * 1e20 }) { - assertTrue("value=" + value, MathUtil.equals(value, value + 1)); - assertTrue("value=" + value, MathUtil.equals(value, Math.nextUp(value))); - assertTrue("value=" + value, MathUtil.equals(value, value * (1 + MathUtil.EPSILON))); - } - - assertFalse(MathUtil.equals(NaN, 0.0)); - assertFalse(MathUtil.equals(0.0, NaN)); - assertFalse(MathUtil.equals(NaN, NaN)); - } - - @Test - public void testAverageStddev() { - List<Integer> ints = new ArrayList<Integer>(); - List<Double> doubles = new ArrayList<Double>(); - - ints.add(3); - ints.add(4); - ints.add(7); - ints.add(5); - - doubles.add(3.4); - doubles.add(2.9); - doubles.add(7.5); - doubles.add(5.43); - doubles.add(2.8); - doubles.add(6.6); - - assertEquals(4.75, MathUtil.average(ints), EPS); - assertEquals(1.707825127659933, MathUtil.stddev(ints), EPS); - assertEquals(4.771666666666667, MathUtil.average(doubles), EPS); - assertEquals(2.024454659078999, MathUtil.stddev(doubles), EPS); - } - - @Test - public void testMedian() { - List<Integer> ints = new ArrayList<Integer>(); - List<Double> doubles = new ArrayList<Double>(); - - ints.add(3); - ints.add(4); - ints.add(7); - ints.add(5); - - doubles.add(3.4); - doubles.add(2.9); - doubles.add(7.5); - doubles.add(5.43); - doubles.add(2.8); - doubles.add(6.6); - - assertEquals(4.5, MathUtil.median(ints), EPS); - assertEquals(4.415, MathUtil.median(doubles), EPS); - - ints.add(9); - doubles.add(10.0); - - assertEquals(5, MathUtil.median(ints), EPS); - assertEquals(5.43, MathUtil.median(doubles), EPS); - } - - @Test - public void testInterpolate() { - double v; - List<Double> x; - List<Double> y; - - x = new ArrayList<Double>(); - y = new ArrayList<Double>(); - y.add(1.0); - - v= MathUtil.interpolate(null, y, 0.0); - assertEquals("Failed to test for domain null", Double.NaN, v, EPS); - - v = MathUtil.interpolate(x, y, 0.0); - assertEquals("Failed to test for empty domain", Double.NaN, v, EPS); - - x = new ArrayList<Double>(); - x.add(1.0); - y = new ArrayList<Double>(); - - v = MathUtil.interpolate(x, null, 0.0); - assertEquals("Failed to test for range null", Double.NaN, v, EPS); - - v = MathUtil.interpolate(x, y, 0.0); - assertEquals("Failed to test for empty range", Double.NaN, v, EPS); - - x = new ArrayList<Double>(); - x.add(1.0); - x.add(2.0); - y = new ArrayList<Double>(); - y.add(15.0); - y.add(17.0); - - v = MathUtil.interpolate(x,y,0.0); - assertEquals("Failed to test t out of domain", Double.NaN, v, EPS); - - v = MathUtil.interpolate(x,y,5.0); - assertEquals("Failed to test t out of domain", Double.NaN, v, EPS); - - v = MathUtil.interpolate(x,y,1.0); - assertEquals("Failed to calculate left endpoint", 15.0, v, EPS); - v = MathUtil.interpolate(x,y,2.0); - assertEquals("Failed to calculate right endpoint", 17.0, v, EPS); - v = MathUtil.interpolate(x,y,1.5); - assertEquals("Failed to calculate center", 16.0, v, EPS); - - x = new ArrayList<Double>(); - x.add(0.25); - x.add(0.5); - x.add(1.0); - x.add(2.0); - y = new ArrayList<Double>(); - y.add(0.0); - y.add(0.0); - y.add(15.0); - y.add(17.0); - v = MathUtil.interpolate(x,y,1.5); - assertEquals("Failed to calculate center with longer list", 16.0, v, EPS); - - } -} diff --git a/core/test/net/sf/openrocket/util/MutableTest.java b/core/test/net/sf/openrocket/util/MutableTest.java deleted file mode 100644 index dfc02209..00000000 --- a/core/test/net/sf/openrocket/util/MutableTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; -import net.sf.openrocket.logging.TraceException; - -import org.junit.Test; - -public class MutableTest { - - @Test - public void testMutable() { - Mutable m = new Mutable(); - Throwable t = null; - - m.check(); - m.check(); - assertTrue(m.isMutable()); - - m.immute(); - - try { - m.check(); - fail(); - } catch (IllegalStateException e) { - // Success - t = e.getCause(); - assertTrue(t instanceof TraceException); - } - - m.immute(); - - try { - m.check(); - fail(); - } catch (IllegalStateException e) { - // Success - assertTrue(e.getCause() == t); - } - } - - - @Test - public void testClone() { - Mutable m1 = new Mutable(); - Mutable m2 = m1.clone(); - - assertTrue(m1.isMutable()); - assertTrue(m2.isMutable()); - - m1.immute(); - - assertFalse(m1.isMutable()); - assertTrue(m2.isMutable()); - } - -} diff --git a/core/test/net/sf/openrocket/util/PolyInterpolatorTest.java b/core/test/net/sf/openrocket/util/PolyInterpolatorTest.java deleted file mode 100644 index cb9201f1..00000000 --- a/core/test/net/sf/openrocket/util/PolyInterpolatorTest.java +++ /dev/null @@ -1,212 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class PolyInterpolatorTest { - - @Test - public void oldMainTest() { - { - PolyInterpolator p0 = new PolyInterpolator( - new double[] {0.6, 1.1}, - new double[] {0.6, 1.1} - ); - double[] r0 = p0.interpolator(1.5, 1.6, 2, -3); - double[] answer0 = new double[] { - /* x=0.60*/ 1.4999999999999987, - /* x=0.61*/ 1.5199143999999984, - /* x=0.62*/ 1.5396351999999984, - /* x=0.63*/ 1.5591287999999988, - /* x=0.64*/ 1.578361599999998, - /* x=0.65*/ 1.597299999999998, - /* x=0.66*/ 1.6159103999999977, - /* x=0.67*/ 1.6341591999999976, - /* x=0.68*/ 1.6520127999999976, - /* x=0.69*/ 1.669437599999997, - /* x=0.70*/ 1.6863999999999977, - /* x=0.71*/ 1.702866399999997, - /* x=0.72*/ 1.7188031999999964, - /* x=0.73*/ 1.7341767999999966, - /* x=0.74*/ 1.7489535999999957, - /* x=0.75*/ 1.7630999999999966, - /* x=0.76*/ 1.7765823999999952, - /* x=0.77*/ 1.7893671999999965, - /* x=0.78*/ 1.8014207999999958, - /* x=0.79*/ 1.8127095999999945, - /* x=0.80*/ 1.8231999999999942, - /* x=0.81*/ 1.8328583999999952, - /* x=0.82*/ 1.841651199999994, - /* x=0.83*/ 1.849544799999994, - /* x=0.84*/ 1.856505599999993, - /* x=0.85*/ 1.8624999999999927, - /* x=0.86*/ 1.8674943999999924, - /* x=0.87*/ 1.8714551999999918, - /* x=0.88*/ 1.8743487999999924, - /* x=0.89*/ 1.876141599999992, - /* x=0.90*/ 1.8767999999999914, - /* x=0.91*/ 1.8762903999999914, - /* x=0.92*/ 1.8745791999999906, - /* x=0.93*/ 1.8716327999999898, - /* x=0.94*/ 1.8674175999999907, - /* x=0.95*/ 1.8618999999999888, - /* x=0.96*/ 1.8550463999999902, - /* x=0.97*/ 1.8468231999999887, - /* x=0.98*/ 1.8371967999999885, - /* x=0.99*/ 1.826133599999988, - /* x=1.00*/ 1.8135999999999868, - /* x=1.01*/ 1.7995623999999868, - /* x=1.02*/ 1.783987199999987, - /* x=1.03*/ 1.7668407999999873, - /* x=1.04*/ 1.748089599999986, - /* x=1.05*/ 1.7276999999999854, - /* x=1.06*/ 1.7056383999999847, - /* x=1.07*/ 1.6818711999999838, - /* x=1.08*/ 1.6563647999999844, - /* x=1.09*/ 1.629085599999983, - /* x=1.10*/ 1.5999999999999837 - }; - double x=0.6; - for (int i=0; i<answer0.length; i++) { - assertEquals("r0 different at x=" + x, PolyInterpolator.eval(x, r0), answer0[i],0.00001); - x+=0.01; - } - } - - { - PolyInterpolator p1 = new PolyInterpolator( - new double[] {0.6, 1.1}, - new double[] {0.6, 1.1}, - new double[] {0.6} - ); - double[] r1 = p1.interpolator(1.5, 1.6, 2, -3, 0); - double[] answer1 = new double[] { - /* x=0.60*/ 1.4999999999999907, - /* x=0.61*/ 1.5199912319999909, - /* x=0.62*/ 1.5399301119999906, - /* x=0.63*/ 1.5597649919999914, - /* x=0.64*/ 1.5794449919999898, - /* x=0.65*/ 1.5989199999999888, - /* x=0.66*/ 1.6181406719999905, - /* x=0.67*/ 1.6370584319999903, - /* x=0.68*/ 1.655625471999989, - /* x=0.69*/ 1.6737947519999874, - /* x=0.70*/ 1.691519999999989, - /* x=0.71*/ 1.7087557119999883, - /* x=0.72*/ 1.7254571519999873, - /* x=0.73*/ 1.741580351999988, - /* x=0.74*/ 1.7570821119999884, - /* x=0.75*/ 1.7719199999999875, - /* x=0.76*/ 1.7860523519999871, - /* x=0.77*/ 1.7994382719999862, - /* x=0.78*/ 1.8120376319999876, - /* x=0.79*/ 1.8238110719999838, - /* x=0.80*/ 1.8347199999999855, - /* x=0.81*/ 1.8447265919999851, - /* x=0.82*/ 1.8537937919999865, - /* x=0.83*/ 1.861885311999986, - /* x=0.84*/ 1.8689656319999832, - /* x=0.85*/ 1.8749999999999836, - /* x=0.86*/ 1.8799544319999804, - /* x=0.87*/ 1.8837957119999817, - /* x=0.88*/ 1.8864913919999804, - /* x=0.89*/ 1.8880097919999814, - /* x=0.90*/ 1.8883199999999807, - /* x=0.91*/ 1.8873918719999794, - /* x=0.92*/ 1.88519603199998, - /* x=0.93*/ 1.8817038719999788, - /* x=0.94*/ 1.8768875519999786, - /* x=0.95*/ 1.8707199999999764, - /* x=0.96*/ 1.8631749119999794, - /* x=0.97*/ 1.8542267519999784, - /* x=0.98*/ 1.8438507519999745, - /* x=0.99*/ 1.832022911999974, - /* x=1.00*/ 1.8187199999999768, - /* x=1.01*/ 1.8039195519999738, - /* x=1.02*/ 1.7875998719999755, - /* x=1.03*/ 1.7697400319999765, - /* x=1.04*/ 1.7503198719999729, - /* x=1.05*/ 1.7293199999999675, - /* x=1.06*/ 1.7067217919999687, - /* x=1.07*/ 1.6825073919999713, - /* x=1.08*/ 1.656659711999966, - /* x=1.09*/ 1.629162431999962, - /* x=1.10*/ 1.5999999999999686 - }; - double x=0.6; - for (int i=0; i<answer1.length; i++) { - assertEquals("r1 different at x=" + x, PolyInterpolator.eval(x, r1), answer1[i],0.00001); - x+=0.01; - } - } - { - PolyInterpolator p2 = new PolyInterpolator( - new double[] {0.6, 1.1}, - new double[] {0.6, 1.1}, - new double[] {0.6, 1.1} - ); - double[] r2 = p2.interpolator(1.5, 1.6, 2, -3, 0, 0); - double[] answer2 = new double[] { - /* x=0.60*/ 1.5000000000000844, - /* x=0.61*/ 1.520007366720093, - /* x=0.62*/ 1.5400539750400783, - /* x=0.63*/ 1.5601657929600794, - /* x=0.64*/ 1.58035504128011, - /* x=0.65*/ 1.6006210000000962, - /* x=0.66*/ 1.620950814720107, - /* x=0.67*/ 1.641320303040109, - /* x=0.68*/ 1.6616947609601311, - /* x=0.69*/ 1.682029769280133, - /* x=0.70*/ 1.7022720000001055, - /* x=0.71*/ 1.7223600227201015, - /* x=0.72*/ 1.7422251110400993, - /* x=0.73*/ 1.7617920489601087, - /* x=0.74*/ 1.7809799372800814, - /* x=0.75*/ 1.7997030000000898, - /* x=0.76*/ 1.8178713907201, - /* x=0.77*/ 1.8353919990401195, - /* x=0.78*/ 1.85216925696011, - /* x=0.79*/ 1.8681059452800994, - /* x=0.80*/ 1.8831040000000847, - /* x=0.81*/ 1.897065318720074, - /* x=0.82*/ 1.9098925670401137, - /* x=0.83*/ 1.921489984960104, - /* x=0.84*/ 1.931764193280106, - /* x=0.85*/ 1.940625000000086, - /* x=0.86*/ 1.9479862067200955, - /* x=0.87*/ 1.9537664150401213, - /* x=0.88*/ 1.9578898329600989, - /* x=0.89*/ 1.9602870812801143, - /* x=0.90*/ 1.960896000000119, - /* x=0.91*/ 1.9596624547200818, - /* x=0.92*/ 1.9565411430400914, - /* x=0.93*/ 1.9514964009601528, - /* x=0.94*/ 1.9445030092801048, - /* x=0.95*/ 1.9355470000001276, - /* x=0.96*/ 1.92462646272012, - /* x=0.97*/ 1.9117523510400858, - /* x=0.98*/ 1.8969492889601298, - /* x=0.99*/ 1.8802563772801548, - /* x=1.00*/ 1.86172800000017, - /* x=1.01*/ 1.8414346307201441, - /* x=1.02*/ 1.8194636390400944, - /* x=1.03*/ 1.7959200969601596, - /* x=1.04*/ 1.7709275852801198, - /* x=1.05*/ 1.7446290000001738, - /* x=1.06*/ 1.7171873587201247, - /* x=1.07*/ 1.6887866070401714, - /* x=1.08*/ 1.659632424960222, - /* x=1.09*/ 1.6299530332800884, - /* x=1.10*/ 1.6000000000001648 - }; - - double x=0.6; - for (int i=0; i<answer2.length; i++) { - assertEquals("r2 different at x=" + x, PolyInterpolator.eval(x, r2), answer2[i],0.00001); - x+=0.01; - } - - } - } -} diff --git a/core/test/net/sf/openrocket/util/QuaternionTest.java b/core/test/net/sf/openrocket/util/QuaternionTest.java deleted file mode 100644 index 26a2dc26..00000000 --- a/core/test/net/sf/openrocket/util/QuaternionTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.sf.openrocket.util; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; - - -public class QuaternionTest { - - @Test - public void oldMainTest() { - - // This is normalized already - Quaternion q = new Quaternion(0.237188, 0.570190, -0.514542, 0.594872); - assertEquals( 1.0, q.norm(), 0.01); - - q.normalize(); - assertEquals( 0.237188, q.getW(), 0.00001); - assertEquals( 0.570190, q.getX(), 0.00001); - assertEquals( -0.514542, q.getY(), 0.00001); - assertEquals( 0.594872, q.getZ(), 0.00001); - assertEquals( 1.0, q.norm(), 0.01); - - Coordinate c = new Coordinate(148578428.914, 8126778.954, -607.741); - - Coordinate r = q.rotate(c); - - System.out.println("Rotated: " + q.rotate(c)); - - assertEquals( -42312599.537, r.x, 0.001); - assertEquals( -48162747.551, r.y, 0.001); - assertEquals( 134281904.197, r.z, 0.001); - - c = new Coordinate(0,1,0); - Coordinate rot = new Coordinate(Math.PI/4,0,0); - - System.out.println("Before: "+c); - c = Quaternion.rotation(rot).invRotate(c); - System.out.println("After: "+c); - - assertEquals( 0.0, c.x, 0.001); - assertEquals( 0.707, c.y, 0.001); - assertEquals( -0.707, c.z, 0.001); - - - } - - -} diff --git a/core/test/net/sf/openrocket/util/ReflectionTest.java b/core/test/net/sf/openrocket/util/ReflectionTest.java deleted file mode 100644 index 9f7c10ed..00000000 --- a/core/test/net/sf/openrocket/util/ReflectionTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; - -import org.junit.Test; - -public class ReflectionTest { - - @Test - public void textHandleInvocationTargetException() { - Throwable cause = null; - - try { - cause = new InvocationTargetException(null); - Reflection.handleWrappedException((InvocationTargetException)cause); - fail(); - } catch (BugException e) { - assertTrue(cause == e.getCause()); - } - - try { - cause = new IllegalStateException("Test"); - Reflection.handleWrappedException(new InvocationTargetException(cause)); - fail(); - } catch (IllegalStateException e) { - assertTrue(cause == e); - } - - try { - cause = new AbstractMethodError(); - Reflection.handleWrappedException(new InvocationTargetException(cause)); - fail(); - } catch (AbstractMethodError e) { - assertTrue(cause == e); - } - - try { - cause = new IOException(); - Reflection.handleWrappedException(new InvocationTargetException(cause)); - fail(); - } catch (BugException e) { - assertTrue(cause == e.getCause()); - } - - } - -} diff --git a/core/test/net/sf/openrocket/util/Rotation2DTest.java b/core/test/net/sf/openrocket/util/Rotation2DTest.java deleted file mode 100644 index 6cc6d91f..00000000 --- a/core/test/net/sf/openrocket/util/Rotation2DTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class Rotation2DTest { - - @Test - public void rotationTest() { - - double rot60 = 0.5; - double rot30 = Math.sqrt(3)/2; - - Coordinate x = new Coordinate(1,1,0); - Coordinate y = new Coordinate(0,1,1); - - Rotation2D rot = new Rotation2D(Math.PI/3); // 60 deg - - assertEquals(new Coordinate(rot60, 1, -rot30), rot.rotateY(x)); - assertEquals(new Coordinate(rot60, 1, rot30), rot.invRotateY(x)); - - assertEquals(new Coordinate(1, rot60, rot30), rot.rotateX(x)); - assertEquals(new Coordinate(1, rot60, -rot30), rot.invRotateX(x)); - - assertEquals(new Coordinate(-rot30, rot60, 1), rot.rotateZ(y)); - assertEquals(new Coordinate(rot30, rot60, 1), rot.invRotateZ(y)); - - } - -} diff --git a/core/test/net/sf/openrocket/util/SimpleStackTest.java b/core/test/net/sf/openrocket/util/SimpleStackTest.java deleted file mode 100644 index 16cd312b..00000000 --- a/core/test/net/sf/openrocket/util/SimpleStackTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.util; - -import java.util.NoSuchElementException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -public class SimpleStackTest { - - @Test(expected=NoSuchElementException.class) - public void testEmptyStack() { - SimpleStack<Integer> s = new SimpleStack<Integer>(); - - assertNull(s.peek()); - - s.pop(); - } - - @Test - public void testPushAndPop() { - - SimpleStack<Integer> s = new SimpleStack<Integer>(); - - for( int i = 0; i< 10; i++ ) { - s.push(i); - assertEquals(i+1, s.size()); - } - - for( int i=9; i>= 0; i-- ) { - assertEquals( i, s.peek().intValue() ); - Integer val = s.pop(); - assertEquals( i, val.intValue() ); - assertEquals( i, s.size() ); - } - - assertNull( s.peek() ); - assertEquals( 0, s.size() ); - - } - -} diff --git a/core/test/net/sf/openrocket/util/TestMutex.java b/core/test/net/sf/openrocket/util/TestMutex.java deleted file mode 100644 index 94d5a9f5..00000000 --- a/core/test/net/sf/openrocket/util/TestMutex.java +++ /dev/null @@ -1,175 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -public class TestMutex { - - @Before - public void setup() { - System.setProperty("openrocket.debug.safetycheck", "true"); - } - - @Test - public void testSingleLocking() { - SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex(); - - // Test single locking - assertNull(m.lockingThread); - m.verify(); - m.lock("here"); - assertNotNull(m.lockingThread); - assertTrue(m.unlock("here")); - - } - - @Test - public void testDoubleLocking() { - SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex(); - - // Test double locking - m.verify(); - m.lock("foobar"); - m.verify(); - m.lock("bazqux"); - m.verify(); - assertTrue(m.unlock("bazqux")); - m.verify(); - assertTrue(m.unlock("foobar")); - m.verify(); - } - - @Test - public void testDoubleUnlocking() { - SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex(); - // Mark error reported to not init exception handler - SafetyMutex.ConcreteSafetyMutex.errorReported = true; - - m.lock("here"); - assertTrue(m.unlock("here")); - assertFalse(m.unlock("here")); - } - - - - private volatile int testState = 0; - private volatile String failure = null; - - @Test(timeout = 1000) - public void testThreadingErrors() { - final SafetyMutex.ConcreteSafetyMutex m = new SafetyMutex.ConcreteSafetyMutex(); - - // Initialize and start the thread - Thread thread = new Thread() { - @Override - public void run() { - try { - - // Test locking a locked mutex - waitFor(1); - try { - m.lock("in thread one"); - failure = "Succeeded in locking a mutex locked by a different thread"; - return; - } catch (ConcurrencyException e) { - // OK - } - - // Test unlocking a mutex locked by a different thread - if (m.unlock("in thread two")) { - failure = "Succeeded in unlocking a mutex locked by a different thread"; - return; - } - - // Test verifying a locked mutex that already has an error - try { - m.verify(); - failure = "Succeeded in verifying a mutex locked by a different thread"; - return; - } catch (ConcurrencyException e) { - // OK - } - - // Test locking a mutex after it's been unlocked - testState = 2; - waitFor(3); - m.lock("in thread three"); - m.verify(); - - // Wait for other side to test - testState = 4; - waitFor(5); - - // Exit code - testState = 6; - - } catch (Exception e) { - failure = "Exception occurred in thread: " + e; - return; - } - - } - }; - thread.setDaemon(true); - thread.start(); - - m.lock("one"); - testState = 1; - - waitFor(2); - assertNull("Thread error: " + failure, failure); - - m.verify(); - m.unlock("one"); - testState = 3; - - waitFor(4); - assertNull("Thread error: " + failure, failure); - - try { - m.lock("two"); - fail("Succeeded in locking a locked mutex in main thread"); - } catch (ConcurrencyException e) { - // OK - } - - // Test unlocking a mutex locked by a different thread - assertFalse(m.unlock("here")); - - try { - m.verify(); - fail("Succeeded in verifying a locked mutex in main thread"); - } catch (ConcurrencyException e) { - // OK - } - - testState = 5; - waitFor(6); - assertNull("Thread error: " + failure, failure); - } - - private void waitFor(int state) { - while (testState != state && failure == null) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - } - } - } - - - public void testBogusMutex() { - SafetyMutex m = new SafetyMutex.BogusSafetyMutex(); - m.lock("foo"); - m.lock("bar"); - m.lock("baz"); - m.verify(); - m.unlock("a"); - m.unlock(null); - m.unlock(""); - m.unlock("c"); - } - -} diff --git a/core/test/net/sf/openrocket/util/TextUtilTest.java b/core/test/net/sf/openrocket/util/TextUtilTest.java deleted file mode 100644 index 4c040fbb..00000000 --- a/core/test/net/sf/openrocket/util/TextUtilTest.java +++ /dev/null @@ -1,281 +0,0 @@ -package net.sf.openrocket.util; - -import static java.lang.Math.PI; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertArrayEquals; - -import java.nio.charset.Charset; -import java.util.Random; - -import org.junit.Test; - -public class TextUtilTest { - - @Test - public void testConvertStringToBytes() { - - Charset us_ascii = Charset.forName("US-ASCII"); - - byte[] ZIP_SIGNATURE_CORRECT = "PK".getBytes(us_ascii); - byte[] ZIP_SIGNATURE_TEST = TextUtil.convertStringToBytes( "PK", us_ascii); - - assertArrayEquals( ZIP_SIGNATURE_CORRECT, ZIP_SIGNATURE_TEST ); - - byte[] OPENROCKET_SIGNATURE_CORRECT = "<openrocket".getBytes(us_ascii); - byte[] OPENROCKET_SIGNATURE_TEST = TextUtil.convertStringToBytes( "<openrocket", us_ascii); - - assertArrayEquals( OPENROCKET_SIGNATURE_CORRECT, OPENROCKET_SIGNATURE_TEST); - - byte[] ROCKSIM_SIGNATURE_CORRECT = "<RockSimDoc".getBytes(us_ascii); - byte[] ROCKSIM_SIGNATURE_TEST = TextUtil.convertStringToBytes( "<RockSimDoc", us_ascii); - - assertArrayEquals( ROCKSIM_SIGNATURE_CORRECT, ROCKSIM_SIGNATURE_TEST ); - } - - @Test - public void testHexString() { - assertEquals("", TextUtil.hexString(new byte[0])); - assertEquals("00", TextUtil.hexString(new byte[] { 0x00 })); - assertEquals("ff", TextUtil.hexString(new byte[] { (byte) 0xff })); - - for (int i = 0; i <= 0xff; i++) { - assertEquals(String.format("%02x", i), TextUtil.hexString(new byte[] { (byte) i })); - } - - assertEquals("0f1e2d3c4b5a6978", TextUtil.hexString(new byte[] { - 0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78 - })); - - Random rnd = new Random(); - for (int count = 0; count < 10; count++) { - int n = rnd.nextInt(100); - byte[] bytes = new byte[n]; - rnd.nextBytes(bytes); - StringBuilder sb = new StringBuilder(); - for (byte b : bytes) { - sb.append(String.format("%02x", b & 0xFF)); - } - assertEquals(sb.toString(), TextUtil.hexString(bytes)); - } - } - - @Test - public void specialCaseTest() { - assertEquals("NaN", TextUtil.doubleToString(Double.NaN)); - assertEquals("Inf", TextUtil.doubleToString(Double.POSITIVE_INFINITY)); - assertEquals("-Inf", TextUtil.doubleToString(Double.NEGATIVE_INFINITY)); - assertEquals("0", TextUtil.doubleToString(0.0)); - assertEquals("0", TextUtil.doubleToString(MathUtil.EPSILON / 3)); - assertEquals("0", TextUtil.doubleToString(-MathUtil.EPSILON / 3)); - } - - @Test - public void longTest() { - - assertEquals("3.1416e-5", TextUtil.doubleToString(PI * 1e-5)); - assertEquals("3.1416e-4", TextUtil.doubleToString(PI * 1e-4)); - assertEquals("0.0031416", TextUtil.doubleToString(PI * 1e-3)); - assertEquals("0.031416", TextUtil.doubleToString(PI * 1e-2)); - assertEquals("0.31416", TextUtil.doubleToString(PI * 1e-1)); - assertEquals("3.1416", TextUtil.doubleToString(PI)); - assertEquals("31.416", TextUtil.doubleToString(PI * 1e1)); - assertEquals("314.16", TextUtil.doubleToString(PI * 1e2)); - assertEquals("3141.6", TextUtil.doubleToString(PI * 1e3)); - assertEquals("31416", TextUtil.doubleToString(PI * 1e4)); - assertEquals("314159", TextUtil.doubleToString(PI * 1e5)); - assertEquals("3141593", TextUtil.doubleToString(PI * 1e6)); - assertEquals("31415927", TextUtil.doubleToString(PI * 1e7)); - assertEquals("3.1416e8", TextUtil.doubleToString(PI * 1e8)); - assertEquals("3.1416e9", TextUtil.doubleToString(PI * 1e9)); - assertEquals("3.1416e10", TextUtil.doubleToString(PI * 1e10)); - - assertEquals("-3.1416e-5", TextUtil.doubleToString(-PI * 1e-5)); - assertEquals("-3.1416e-4", TextUtil.doubleToString(-PI * 1e-4)); - assertEquals("-0.0031416", TextUtil.doubleToString(-PI * 1e-3)); - assertEquals("-0.031416", TextUtil.doubleToString(-PI * 1e-2)); - assertEquals("-0.31416", TextUtil.doubleToString(-PI * 1e-1)); - assertEquals("-3.1416", TextUtil.doubleToString(-PI)); - assertEquals("-31.416", TextUtil.doubleToString(-PI * 1e1)); - assertEquals("-314.16", TextUtil.doubleToString(-PI * 1e2)); - assertEquals("-3141.6", TextUtil.doubleToString(-PI * 1e3)); - assertEquals("-31416", TextUtil.doubleToString(-PI * 1e4)); - assertEquals("-314159", TextUtil.doubleToString(-PI * 1e5)); - assertEquals("-3141593", TextUtil.doubleToString(-PI * 1e6)); - assertEquals("-31415927", TextUtil.doubleToString(-PI * 1e7)); - assertEquals("-3.1416e8", TextUtil.doubleToString(-PI * 1e8)); - assertEquals("-3.1416e9", TextUtil.doubleToString(-PI * 1e9)); - assertEquals("-3.1416e10", TextUtil.doubleToString(-PI * 1e10)); - - } - - @Test - public void shortTest() { - double p = 3.1; - assertEquals("3.1e-5", TextUtil.doubleToString(p * 1e-5)); - assertEquals("3.1e-4", TextUtil.doubleToString(p * 1e-4)); - assertEquals("0.0031", TextUtil.doubleToString(p * 1e-3)); - assertEquals("0.031", TextUtil.doubleToString(p * 1e-2)); - assertEquals("0.31", TextUtil.doubleToString(p * 1e-1)); - assertEquals("3.1", TextUtil.doubleToString(p)); - assertEquals("31", TextUtil.doubleToString(p * 1e1)); - assertEquals("310", TextUtil.doubleToString(p * 1e2)); - assertEquals("3100", TextUtil.doubleToString(p * 1e3)); - assertEquals("31000", TextUtil.doubleToString(p * 1e4)); - assertEquals("3.1e5", TextUtil.doubleToString(p * 1e5)); - assertEquals("3.1e6", TextUtil.doubleToString(p * 1e6)); - assertEquals("3.1e7", TextUtil.doubleToString(p * 1e7)); - assertEquals("3.1e8", TextUtil.doubleToString(p * 1e8)); - assertEquals("3.1e9", TextUtil.doubleToString(p * 1e9)); - assertEquals("3.1e10", TextUtil.doubleToString(p * 1e10)); - - assertEquals("-3.1e-5", TextUtil.doubleToString(-p * 1e-5)); - assertEquals("-3.1e-4", TextUtil.doubleToString(-p * 1e-4)); - assertEquals("-0.0031", TextUtil.doubleToString(-p * 1e-3)); - assertEquals("-0.031", TextUtil.doubleToString(-p * 1e-2)); - assertEquals("-0.31", TextUtil.doubleToString(-p * 1e-1)); - assertEquals("-3.1", TextUtil.doubleToString(-p)); - assertEquals("-31", TextUtil.doubleToString(-p * 1e1)); - assertEquals("-310", TextUtil.doubleToString(-p * 1e2)); - assertEquals("-3100", TextUtil.doubleToString(-p * 1e3)); - assertEquals("-31000", TextUtil.doubleToString(-p * 1e4)); - assertEquals("-3.1e5", TextUtil.doubleToString(-p * 1e5)); - assertEquals("-3.1e6", TextUtil.doubleToString(-p * 1e6)); - assertEquals("-3.1e7", TextUtil.doubleToString(-p * 1e7)); - assertEquals("-3.1e8", TextUtil.doubleToString(-p * 1e8)); - assertEquals("-3.1e9", TextUtil.doubleToString(-p * 1e9)); - assertEquals("-3.1e10", TextUtil.doubleToString(-p * 1e10)); - - p = 3; - assertEquals("3e-5", TextUtil.doubleToString(p * 1e-5)); - assertEquals("3e-4", TextUtil.doubleToString(p * 1e-4)); - assertEquals("3e-3", TextUtil.doubleToString(p * 1e-3)); - assertEquals("0.03", TextUtil.doubleToString(p * 1e-2)); - assertEquals("0.3", TextUtil.doubleToString(p * 1e-1)); - assertEquals("3", TextUtil.doubleToString(p)); - assertEquals("30", TextUtil.doubleToString(p * 1e1)); - assertEquals("300", TextUtil.doubleToString(p * 1e2)); - assertEquals("3e3", TextUtil.doubleToString(p * 1e3)); - assertEquals("3e4", TextUtil.doubleToString(p * 1e4)); - assertEquals("3e5", TextUtil.doubleToString(p * 1e5)); - assertEquals("3e6", TextUtil.doubleToString(p * 1e6)); - assertEquals("3e7", TextUtil.doubleToString(p * 1e7)); - assertEquals("3e8", TextUtil.doubleToString(p * 1e8)); - assertEquals("3e9", TextUtil.doubleToString(p * 1e9)); - assertEquals("3e10", TextUtil.doubleToString(p * 1e10)); - - assertEquals("-3e-5", TextUtil.doubleToString(-p * 1e-5)); - assertEquals("-3e-4", TextUtil.doubleToString(-p * 1e-4)); - assertEquals("-3e-3", TextUtil.doubleToString(-p * 1e-3)); - assertEquals("-0.03", TextUtil.doubleToString(-p * 1e-2)); - assertEquals("-0.3", TextUtil.doubleToString(-p * 1e-1)); - assertEquals("-3", TextUtil.doubleToString(-p)); - assertEquals("-30", TextUtil.doubleToString(-p * 1e1)); - assertEquals("-300", TextUtil.doubleToString(-p * 1e2)); - assertEquals("-3e3", TextUtil.doubleToString(-p * 1e3)); - assertEquals("-3e4", TextUtil.doubleToString(-p * 1e4)); - assertEquals("-3e5", TextUtil.doubleToString(-p * 1e5)); - assertEquals("-3e6", TextUtil.doubleToString(-p * 1e6)); - assertEquals("-3e7", TextUtil.doubleToString(-p * 1e7)); - assertEquals("-3e8", TextUtil.doubleToString(-p * 1e8)); - assertEquals("-3e9", TextUtil.doubleToString(-p * 1e9)); - assertEquals("-3e10", TextUtil.doubleToString(-p * 1e10)); - - } - - @Test - public void roundingTest() { - - assertEquals("1.001", TextUtil.doubleToString(1.00096)); - - - /* - * Not testing with 1.00015 because it might be changed during number formatting - * calculations. Its rounding is basically arbitrary anyway. - */ - - assertEquals("1.0002e-5", TextUtil.doubleToString(1.0001500001e-5)); - assertEquals("1.0001e-5", TextUtil.doubleToString(1.0001499999e-5)); - assertEquals("1.0002e-4", TextUtil.doubleToString(1.0001500001e-4)); - assertEquals("1.0001e-4", TextUtil.doubleToString(1.0001499999e-4)); - assertEquals("0.0010002", TextUtil.doubleToString(1.0001500001e-3)); - assertEquals("0.0010001", TextUtil.doubleToString(1.0001499999e-3)); - assertEquals("0.010002", TextUtil.doubleToString(1.0001500001e-2)); - assertEquals("0.010001", TextUtil.doubleToString(1.0001499999e-2)); - assertEquals("0.10002", TextUtil.doubleToString(1.0001500001e-1)); - assertEquals("0.10001", TextUtil.doubleToString(1.0001499999e-1)); - assertEquals("1.0002", TextUtil.doubleToString(1.0001500001)); - assertEquals("1.0001", TextUtil.doubleToString(1.0001499999)); - assertEquals("10.002", TextUtil.doubleToString(1.0001500001e1)); - assertEquals("10.001", TextUtil.doubleToString(1.0001499999e1)); - assertEquals("100.02", TextUtil.doubleToString(1.0001500001e2)); - assertEquals("100.01", TextUtil.doubleToString(1.0001499999e2)); - assertEquals("1000.2", TextUtil.doubleToString(1.0001500001e3)); - assertEquals("1000.1", TextUtil.doubleToString(1.0001499999e3)); - assertEquals("10002", TextUtil.doubleToString(1.0001500001e4)); - assertEquals("10001", TextUtil.doubleToString(1.0001499999e4)); - assertEquals("100012", TextUtil.doubleToString(1.00011500001e5)); - assertEquals("100011", TextUtil.doubleToString(1.00011499999e5)); - assertEquals("1000112", TextUtil.doubleToString(1.000111500001e6)); - assertEquals("1000111", TextUtil.doubleToString(1.000111499999e6)); - assertEquals("10001112", TextUtil.doubleToString(1.0001111500001e7)); - assertEquals("10001111", TextUtil.doubleToString(1.0001111499999e7)); - assertEquals("1.0002e8", TextUtil.doubleToString(1.0001500001e8)); - assertEquals("1.0001e8", TextUtil.doubleToString(1.0001499999e8)); - assertEquals("1.0002e9", TextUtil.doubleToString(1.0001500001e9)); - assertEquals("1.0001e9", TextUtil.doubleToString(1.0001499999e9)); - assertEquals("1.0002e10", TextUtil.doubleToString(1.0001500001e10)); - assertEquals("1.0001e10", TextUtil.doubleToString(1.0001499999e10)); - - - assertEquals("-1.0002e-5", TextUtil.doubleToString(-1.0001500001e-5)); - assertEquals("-1.0001e-5", TextUtil.doubleToString(-1.0001499999e-5)); - assertEquals("-1.0002e-4", TextUtil.doubleToString(-1.0001500001e-4)); - assertEquals("-1.0001e-4", TextUtil.doubleToString(-1.0001499999e-4)); - assertEquals("-0.0010002", TextUtil.doubleToString(-1.0001500001e-3)); - assertEquals("-0.0010001", TextUtil.doubleToString(-1.0001499999e-3)); - assertEquals("-0.010002", TextUtil.doubleToString(-1.0001500001e-2)); - assertEquals("-0.010001", TextUtil.doubleToString(-1.0001499999e-2)); - assertEquals("-0.10002", TextUtil.doubleToString(-1.0001500001e-1)); - assertEquals("-0.10001", TextUtil.doubleToString(-1.0001499999e-1)); - assertEquals("-1.0002", TextUtil.doubleToString(-1.0001500001)); - assertEquals("-1.0001", TextUtil.doubleToString(-1.0001499999)); - assertEquals("-10.002", TextUtil.doubleToString(-1.0001500001e1)); - assertEquals("-10.001", TextUtil.doubleToString(-1.0001499999e1)); - assertEquals("-100.02", TextUtil.doubleToString(-1.0001500001e2)); - assertEquals("-100.01", TextUtil.doubleToString(-1.0001499999e2)); - assertEquals("-1000.2", TextUtil.doubleToString(-1.0001500001e3)); - assertEquals("-1000.1", TextUtil.doubleToString(-1.0001499999e3)); - assertEquals("-10002", TextUtil.doubleToString(-1.0001500001e4)); - assertEquals("-10001", TextUtil.doubleToString(-1.0001499999e4)); - assertEquals("-100012", TextUtil.doubleToString(-1.00011500001e5)); - assertEquals("-100011", TextUtil.doubleToString(-1.00011499999e5)); - assertEquals("-1000112", TextUtil.doubleToString(-1.000111500001e6)); - assertEquals("-1000111", TextUtil.doubleToString(-1.000111499999e6)); - assertEquals("-10001112", TextUtil.doubleToString(-1.0001111500001e7)); - assertEquals("-10001111", TextUtil.doubleToString(-1.0001111499999e7)); - assertEquals("-1.0002e8", TextUtil.doubleToString(-1.0001500001e8)); - assertEquals("-1.0001e8", TextUtil.doubleToString(-1.0001499999e8)); - assertEquals("-1.0002e9", TextUtil.doubleToString(-1.0001500001e9)); - assertEquals("-1.0001e9", TextUtil.doubleToString(-1.0001499999e9)); - assertEquals("-1.0002e10", TextUtil.doubleToString(-1.0001500001e10)); - assertEquals("-1.0001e10", TextUtil.doubleToString(-1.0001499999e10)); - - } - - - @Test - public void randomTest() { - for (int i = 0; i < 10000; i++) { - double orig = Math.random(); - double result; - double expected = Math.rint(orig * 100000) / 100000.0; - - if (orig < 0.1) - continue; - String s = TextUtil.doubleToString(orig); - result = Double.parseDouble(s); - assertEquals(expected, result, 0.00000001); - } - } - -} diff --git a/core/test/net/sf/openrocket/util/TransformationTest.java b/core/test/net/sf/openrocket/util/TransformationTest.java deleted file mode 100644 index cb63b3f2..00000000 --- a/core/test/net/sf/openrocket/util/TransformationTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.sf.openrocket.util; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; - - -public class TransformationTest { - @Test - public void oldMainTest() { - Transformation t; - - t = new Transformation(); - { - Coordinate a = t.transform( new Coordinate(1,0,0) ); - assertEquals( new Coordinate(1,0,0), a ); - a = t.transform( new Coordinate(0,1,0) ); - assertEquals( new Coordinate(0,1,0), a ); - a = t.transform( new Coordinate(0,0,1) ); - assertEquals( new Coordinate(0,0,1), a ); - } - - t = new Transformation(1,2,3); - { - Coordinate a = t.transform( new Coordinate(1,0,0) ); - assertEquals( new Coordinate(2,2,3), a ); - a = t.transform( new Coordinate(0,1,0) ); - assertEquals( new Coordinate(1,3,3), a ); - a = t.transform( new Coordinate(0,0,1) ); - assertEquals( new Coordinate(1,2,4), a ); - } - - - t = new Transformation(new Coordinate(2,3,4)); - { - Coordinate a = t.transform( new Coordinate(1,0,0) ); - assertEquals( new Coordinate(3,3,4), a ); - a = t.transform( new Coordinate(0,1,0) ); - assertEquals( new Coordinate(2,4,4), a ); - a = t.transform( new Coordinate(0,0,1) ); - assertEquals( new Coordinate(2,3,5), a ); - } - - t = Transformation.rotate_y(0.01); - { - Coordinate a = t.transform( new Coordinate(1,0,0) ); - // we need to test individual coordinates due to error. - assertEquals( 1, a.x, .001); - assertEquals( 0, a.y, .001); - assertEquals( -.01, a.z, .001); - a = t.transform( new Coordinate(0,1,0) ); - assertEquals( new Coordinate(0,1,0), a ); - a = t.transform( new Coordinate(0,0,1) ); - // we need to test individual coordinates due to error. - assertEquals( .01, a.x, .001); - assertEquals( 0, a.y, .001); - assertEquals( 1, a.z, .001); - } - - t = new Transformation(-1,0,0); - t = t.applyTransformation(Transformation.rotate_y(0.01)); - t = t.applyTransformation(new Transformation(1,0,0)); - { - Coordinate a = t.transform( new Coordinate(1,0,0) ); - // we need to test individual coordinates due to error. - assertEquals( 1, a.x, .001); - assertEquals( 0, a.y, .001); - assertEquals( -.02, a.z, .001); - a = t.transform( new Coordinate(0,1,0) ); - assertEquals( 0, a.x, .001); - assertEquals( 1, a.y, .001); - assertEquals( -.01, a.z, .001); - a = t.transform( new Coordinate(0,0,1) ); - // we need to test individual coordinates due to error. - assertEquals( .01, a.x, .001); - assertEquals( 0, a.y, .001); - assertEquals( .99, a.z, .001); - } - } - - -} diff --git a/core/test/net/sf/openrocket/util/UniqueIDTest.java b/core/test/net/sf/openrocket/util/UniqueIDTest.java deleted file mode 100644 index c77da324..00000000 --- a/core/test/net/sf/openrocket/util/UniqueIDTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class UniqueIDTest { - - @Test - public void integerTest() { - - int n = UniqueID.next(); - assertTrue(n > 0); - assertEquals(n+1, UniqueID.next()); - assertEquals(n+2, UniqueID.next()); - assertEquals(n+3, UniqueID.next()); - - } - - - @Test - public void stringTest() { - String id = UniqueID.uuid(); - assertNotNull(id); - assertNotSame(id, UniqueID.uuid()); - assertNotSame(id, UniqueID.uuid()); - } - -} diff --git a/core/test/net/sf/openrocket/util/WorldCoordinateTest.java b/core/test/net/sf/openrocket/util/WorldCoordinateTest.java deleted file mode 100644 index ce67dc11..00000000 --- a/core/test/net/sf/openrocket/util/WorldCoordinateTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.sf.openrocket.util; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class WorldCoordinateTest { - - private static final double EPS = 1e-10; - - @Test - public void testConstructor() { - WorldCoordinate wc; - - wc = new WorldCoordinate(10, 15, 130); - assertEquals(10, wc.getLatitudeDeg(), EPS); - assertEquals(15, wc.getLongitudeDeg(), EPS); - assertEquals(130, wc.getAltitude(), 0); - - wc = new WorldCoordinate(100, 190, 13000); - assertEquals(90, wc.getLatitudeDeg(), EPS); - assertEquals(-170, wc.getLongitudeDeg(), EPS); - assertEquals(13000, wc.getAltitude(), 0); - - wc = new WorldCoordinate(-100, -200, -13000); - assertEquals(-90, wc.getLatitudeDeg(), EPS); - assertEquals(160, wc.getLongitudeDeg(), EPS); - assertEquals(-13000, wc.getAltitude(), 0); - } - - @Test - public void testGetLatitude() { - WorldCoordinate wc; - wc = new WorldCoordinate(10, 15, 130); - assertEquals(10, wc.getLatitudeDeg(), EPS); - assertEquals(Math.toRadians(10), wc.getLatitudeRad(), EPS); - } - - @Test - public void testGetLongitude() { - WorldCoordinate wc; - wc = new WorldCoordinate(10, 15, 130); - assertEquals(15, wc.getLongitudeDeg(), EPS); - assertEquals(Math.toRadians(15), wc.getLongitudeRad(), EPS); - } - -} diff --git a/core/web/html/actions/.htaccess b/core/web/html/actions/.htaccess deleted file mode 100644 index d18e09c2..00000000 --- a/core/web/html/actions/.htaccess +++ /dev/null @@ -1,14 +0,0 @@ - -#RewriteEngine On -#RewriteBase /actions/ -#RewriteRule ^reportbug$ reportbug.php - - -# Redirect bug reports to a server that allows sending mail - -Redirect 307 /actions/reportbug http://sampo.kapsi.fi/openrocket/reportbug.php - -RewriteEngine On -RewriteBase /actions/ -RewriteRule ^updates$ updates.php - diff --git a/core/web/html/actions/reportbug.php b/core/web/html/actions/reportbug.php deleted file mode 100644 index 86b8d8cf..00000000 --- a/core/web/html/actions/reportbug.php +++ /dev/null @@ -1,60 +0,0 @@ -<? -$mailaddr = "openrocket-bugs@lists.sourceforge.net"; -//$mailaddr = "sampo.niskanen@gmail.com"; - -$version = $_POST["version"]; -$content = $_POST["content"]; - - -// Parse headers -if (!function_exists('getallheaders')) { - function getallheaders() { - foreach ($_SERVER as $name => $value) { - if (substr($name, 0, 5) == 'HTTP_') { - $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; - } - } - return $headers; - } -} - -$headers = "\n\n\n"; -foreach (getallheaders() as $header => $value) { - $headers = $headers . "$header: $value\n"; -} - -// Set HTTP content-type header -header("Content-type: text/plain; charset=utf-8"); - - -// Check for valid submission -if (preg_match("/^[a-zA-Z0-9. -]{1,30}$/", $version) && - strlen($content) > 0) { - - $subject = date("Y-m-d H:i:s") . " Automatic bug report for OpenRocket " . $version; - if (mail($mailaddr, $subject, $content . $headers, - "From: Automatic Bug Reports <".$mailaddr.">\r\n". - "Content-Type: text/plain; charset=utf-8")) { - - // Success - OpenRocket recognizes status code 202 - header("HTTP/1.0 202 Accepted"); - echo "202 Accepted: Bug report successfully sent."; -// echo "\nContent:\n$content"; - - } else { - - // Sending mail failed - header("HTTP/1.0 503 Service Unavailable"); - echo "503 Service Unavailable: Unable to send bug report."; - - } - -} else { - - // Bad request - header("HTTP/1.0 400 Bad Request"); - echo "400 Bad Request: Illegal request.\n"; - -} - -?> \ No newline at end of file diff --git a/core/web/html/actions/testbugreport.html b/core/web/html/actions/testbugreport.html deleted file mode 100644 index 28d7e9a2..00000000 --- a/core/web/html/actions/testbugreport.html +++ /dev/null @@ -1,25 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> - <title>Bug report test - - - - -
-

Version:

-

Test bug report content:

-

-

-

A successful submission should result in a 202 Accepted response.

-

Please do not abuse.

-
- - - diff --git a/core/web/html/actions/updates.php b/core/web/html/actions/updates.php deleted file mode 100644 index 83b20e5c..00000000 --- a/core/web/html/actions/updates.php +++ /dev/null @@ -1,226 +0,0 @@ - $value) { - if (substr($name, 0, 5) == 'HTTP_') { - $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; - } - } - return $headers; - } -} - - -// Parse + validate headers -$orid = ""; -$orversion = ""; -$oros = ""; -$orjava = ""; -$orcountry = ""; -$orcores = ""; -$orlocale = ""; -foreach (getallheaders() as $header => $value) { - if (preg_match("/^[a-zA-Z0-9 !$%&()*+,.\\/:=?@_~-]{1,40}$/", $value)) { - $h = strtolower($header); - if ($h == 'x-openrocket-version') { - $orversion = $value; - } else if ($h == 'x-openrocket-id') { - $orid = $value; - } else if ($h == 'x-openrocket-os') { - $oros = $value; - } else if ($h == 'x-openrocket-java') { - $orjava = $value; - } else if ($h == 'x-openrocket-country') { - $orcountry = $value; - } else if ($h == 'x-openrocket-cpus') { - $orcores = $value; - } else if ($h == 'x-openrocket-locale') { - $orlocale = $value; - } - } -} - -// Log the request -if ((strlen($orversion) > 0 || strlen($orid) > 0 || strlen($oros) > 0 - || strlen($orjava) > 0 || strlen($orcountry) > 0 - || strlen($orcores) > 0 || strlen($orlocale) > 0) && - (strlen($orversion) < 20 && strlen($orid) < 50 && strlen($oros) < 50 - && strlen($orjava) < 50 && strlen($orcountry) < 50) - && strlen($orcores) < 10 && strlen($orlocale) < 20) { - - $file = $logfiles . gmdate("Y-m"); - $line = gmdate("Y-m-d H:i:s") . ";" . $orid . ";" . $orversion . - ";" . $oros . ";" . $orjava . ";" . $orcountry . ";" . $orcores . - ";" . $orlocale . "\n"; - - $fp = fopen($file, 'a'); - if ($fp != FALSE) { - fwrite($fp, $line); - fclose($fp); - } -} - - -// Set HTTP content-type header -// No charset allowed for 0.9.4 -//header("Content-type: text/plain; charset=utf-8"); -header("Content-type: text/plain"); - -/* - * Currently all old versions are handled manually. - * Update checking was introduced in OpenRocket 0.9.4 - * - * We ignore "pre" versions, they are handled exacly like - * their non-pre counterparts. - */ -$version = $_GET["version"]; -$updates = ""; - -$unstable = "12.09"; -$stable = "1.0.0"; - -if (preg_match("/^12.03$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "5: Fractional inch unit\n" . - "4: Printing centering rings\n" . - "4: Translations to Czech and Polish\n" . - ""; -} else if (preg_match("/^1\.1\.9$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "5: Configurable stage separation\n" . - "4: Freeform fin import from images\n" . - "4: Translations to Italian and Russian\n" . - ""; -} else if (preg_match("/^1\.1\.8$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "6: Additional template printing\n" . - "5: Geodetic computations\n" . - "5: Configurable stage separation\n" . - "5: Guided tours\n" . - "4: Freeform fin import from images\n" . - "4: Translations to Italian and Russian\n" . - "4: Bug fixes\n" . - ""; -} else if (preg_match("/^1\.1\.7$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "8: Writing RKT files\n" . - "6: Additional template printing\n" . - "5: Geodetic computations\n" . - "5: Configurable stage separation\n" . - "5: Guided tours\n" . - "4: Freeform fin import from images\n" . - "4: Translations to Italian and Russian\n" . - "4: Bug fixes\n" . - ""; -} else if (preg_match("/^1\.1\.6$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "8: Automatic rocket design optimization\n" . - "6: Additional template printing\n" . - "5: Geodetic computations\n" . - ""; -} else if (preg_match("/^1\.1\.5$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "8: Automatic rocket design optimization\n" . - "6: Initial localization support\n" . - "6: Additional template printing\n" . - "5: Geodetic computations\n" . - "5: Scaling support\n" . - "4: Bug fixes\n" . - ""; -} else if (preg_match("/^1\.1\.4$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "8: Automatic rocket design optimization\n" . - "6: Initial localization support\n" . - "5: Fixes to printing system\n" . - "5: Scaling support\n" . - ""; -} else if (preg_match("/^1\.1\.3$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "8: Automatic rocket design optimization\n" . - "7: Initial printing support\n" . - "6: Initial localization support\n" . - "5: Scaling support\n" . - "4: Bug fixes\n" . - ""; -} else if (preg_match("/^1\.1\.[12]$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "8: Automatic rocket design optimization\n" . - "6: Initial printing support\n" . - "5: Initial drag-and-drop support\n" . - "5: Initial localization support\n" . - "5: Scaling support\n" . - "4: Bug fixes\n" . - ""; -} else if (preg_match("/^1\.1\.0$/", $version)) { - $updates = "Version: " . $unstable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "8: Automatic rocket design optimization\n" . - "6: Initial printing support\n" . - "6: Initial localization support\n" . - "6: Enhanced motor selection\n" . - "5: Rewritten simulation code\n" . - "5: Drag-and-drop support\n" . - "4: Bug fixes\n" . - ""; -} else if (preg_match("/^0\.9\.6/", $version)) { - $updates = "Version: " . $stable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "6: Hundreds of new thrustcurves\n" . - "5: Bug fixes\n" . - ""; -} else if (preg_match("/^0\.9\.[45]/", $version)) { - $updates = "Version: " . $stable . "\n" . - "10: 3D design view\n" . - "9: Component presets\n" . - "8: Writing RKT files\n" . - "7: Hundreds of new thrustcurves\n" . - "6: Aerodynamic computation updates\n" . - "5: Numerous bug fixes" . - ""; -} - - -if (strlen($updates) == 0) { - - // No updates available - header("HTTP/1.0 204 No Content"); - -} else { - - header("HTTP/1.0 200 OK"); - echo $updates; - -} - -?> \ No newline at end of file diff --git a/core/web/html/alternative.css b/core/web/html/alternative.css deleted file mode 100644 index 3d2dc089..00000000 --- a/core/web/html/alternative.css +++ /dev/null @@ -1,519 +0,0 @@ - -body { - margin: 0; - padding: 0; - background-color: black; - background-image: url(starfield.jpg); -} - -#iewarn { - width: 100%; - font-size: 140%; - background-color: #fa0; - text-align: center; - padding: 2em 2em; - border-top: solid 1px black; - border-bottom: solid 1px black; -} - -h1 { - margin: 0.75em 1.7em 1.25em 120px; - color: #bbf; - text-align: right; -} - -h2 { - margin-top: 1.5em; - border-bottom: dotted 2px #f99; -} -/* TODO: Change to direct next element */ -div.content h2:first-child { - margin-top: 0em; -} - -h3 { - margin-top: 1.5em; - border-bottom: dotted 1px #99f; -} - - -a { - text-decoration: none; - color: #00B; -} -a:hover { - color: #44c; -} - - -div.icon { - position: absolute; - width: 194px; - height: 214px; - left: 0px; - top: -178px; - background: url('icon.png') no-repeat; -} -div.icon a { - display: block; - position: absolute; - left: 0px; - right: 25px; - top: 0px; - bottom: 0px; -/* border: solid 1px red; */ -} - - -div.menucontainer { - position: absolute; - top: 90px; - left: 0px; - z-index: 100; -} - -div.menu { - position: absolute; - left: 20px; - top: 95px; - width: 170px; - margin: 0; - padding: 0 0; - background: #c1d0db url(menubg.png) repeat-x; - z-index: 200; - border: solid 1px black; - -moz-border-radius: 12px; - -webkit-border-radius: 12px; - -khtml-border-radius: 12px; - border-radius: 12px; -} -div.menu ul { - position: relative; - list-style: none; - margin: 0; - padding: 0 0; -} - -div.menu li { - display: block; - left: 0; - right: 0; - margin: 0; - text-align: center; -} - -div.menu li a { - display: block; - left: 0; - right: 0; - font-style: normal; - text-decoration: none; - color: #00d; - padding: 0.65em 1em; - outline: none; -} - -div.menu li:first-child a { - padding: 0.5em 0 !important; - font-size: 160% !important; - font-weight: normal !important; - color: #003 !important; - background-color: transparent !important; - text-shadow: #666 1px 1px 3px; -} - -div.menu li a:hover { - background-color: #eeb6b6; - -moz-border-radius: 12px; - -webkit-border-radius: 12px; - -khtml-border-radius: 12px; - border-radius: 12px; -} - - - -div.menu div.logo { - position: absolute; - top: 100%; - left: -2px; - margin-top: 15px; - width: 100%; -} - -div.menu div.logo img { - display: block; - margin: 0 auto; -} - - -.page_index div.menu a[href="index.html"], -.page_features div.menu a[href="features.html"], -.page_screenshots div.menu a[href="screenshots.html"], -.page_download div.menu a[href="download.html"], -.page_documentation div.menu a[href="documentation.html"], -.page_getinvolved div.menu a[href="getinvolved.html"], -.page_contact div.menu a[href="contact.html"], -.page_report div.menu a[href="report.html"], -.page_license div.menu a[href="license.html"] { - font-weight: bold; - font-size: 110%; -} - - -.content { - margin: 0em 2em 1em 130px; - padding: 2em 2em 2em 80px; - min-height: 27em; - background-color: white; - position: relative; - border: 2px solid #666; - min-height: 530px; -} - - -.content div.tl, .content div.tr, .content div.bl, .content div.br { - position: absolute; - width: 10px; - height: 10px; - background: url('whitebox.png') no-repeat; -} -.content div.tl { - top: -10px; - left: -10px; - background-position: 0px 0px; -} -.content div.tr { - top: -10px; - right: -10px; - background-position: -50px 0px; -} -.content div.bl { - bottom: -10px; - left: -10px; - background-position: 0px -50px; -} -.content div.br { - bottom: -10px; - right: -10px; - background-position: -50px -50px; -} - -.content div.t, .content div.b { - position: absolute; - height: 10px; - left: 0px; - right: 0px; - background: url('whitebox-vertical.png') repeat-x; -} -.content div.t { - top: -10px; -} -.content div.b { - bottom: -10px; - background-position: 0px -50px; -} - -.content div.l, .content div.r { - position: absolute; - width: 10px; - top: 0px; - bottom: 0px; - background: url('whitebox-horizontal.png') repeat-y; -} -.content div.l { - left: -10px; -} -.content div.r { - right: -10px; - background-position: -50px 0px; -} - - - -img { - border: 0px; - outline: none; - font-size: 70%; -} - -.smallshot { - float: left; - margin-top:2em; - text-align: center; - font-style: italic; - margin-right: 2em; -} -.smallshot.last { - margin-right: 0; -} -.clear { - clear:both; -} - - - - -a.help { - margin-left: 1em; - font-size: smaller; - font-style: italic; -} - - -pre.quote { - margin: 0.5em 2em; - padding: 1em; - border: dashed 1px #888; - background-color: #ddd; - display: inline-block; -} - -p.quote { - margin: 2em; -} - -hr { - margin: 2em 0em; -} - -.right { - float: right; - margin: 0; -} - -li { - margin-top: 0.5em; -} - - -p.download { - margin: 2em; -} -p.download a { - font-size: 140%; - font-style: italic; - padding: 0.5em; - border: dashed 1px red; - background-color: #89cbe0; - outline: none; -} -p.download a:hover { - color: #00F; - background-color: #ee9494; -} -p.download a:focus { - background-color: #8fd5eb; -} - -div.valid { - float: right; - margin-right: 2em; -} - - - -ol.toc { - list-style-type: none; -} - -dt+dt { - margin-top: 0.5em; -} -dd { - margin-top: 0.2em; - margin-bottom: 1.4em; -} - - -div.downloadbox { - position: relative; - width: 175px; - height: 80px; - background: transparent url('greenbox.png') no-repeat; - text-align: left; -} - -div.downloadbox a.main { - position: absolute; - left: 0px; - right: 0px; - top: 0px; - bottom: 0px; - - color: #a0ff4b; - font-family: Arial, sans-serif; - - padding: 10px 12px; - text-shadow: #666 1px 1px 1px; -} -div.downloadbox a.main span { - font-size: 90%; -} -div.downloadbox a.main:hover { - text-shadow: #000 1px 1px 1px; -} - -div.downloadbox a strong { - display: block; - margin-bottom: 3px; - color: white; - font-weight: bold; - font-size: larger; -} -div.downloadbox a:hover strong { - text-shadow: #666 1px 1px 1px; -} - - -div.downloadbox .alternative { - position: absolute; - bottom: 0; - left: 0; - right: 0; - margin: 0; - padding: 0 10px 10px 10px; - font-size: 11px; - font-family: Arial, sans-serif; - color: #244506; -} -div.downloadbox .alternative a { - color: #244506; -} -div.downloadbox .alternative a+a { - text-align: right; -} -div.downloadbox .alternative a:hover { - color: black; -} -/* -.page_index div.downloadbox { - width: 195px; - margin: 0.5em 0 1em 50px; -} -*/ -.rightpane { - width: 210px; - float: right; - clear: both; - margin: 0 0 0 30px; - text-align: center; -} -.rightpane div { - margin: 2em auto; -} - -.rightpane div.downloadbox { - margin: 0 auto 2em auto; -} -.rightpane div.screenshot { - font-size: smaller; - font-style: italic; - text-align: center; -} -.rightpane div.support { - margin-bottom: 0; - text-align: center; -} - -.page_download div.support { - margin: 20px 0; -} - -.rightimg { - width: 210px; - float: right; - clear: both; - margin: 2em 0 2em 30px; - font-size: smaller; - font-style: italic; - text-align: center; -} -.rightimg img { - display: block; - margin-bottom: 1em; -} - - - -div.news .date { - font-weight: bold; -} - -.page_download div.contentholder { - margin-right: 15em; -} -.page_download div.news { - background-color: white; - padding-left: 3em; - float: right; - width: 18em; - font-size: x-small; -} -.page_download div.news h2 { - border-bottom: none; - margin-bottom: 1em; -} -.page_download div.news .date { - display: block; -} -.page_download div.downloadbox { - margin-left: auto; - margin-right: auto; -} - - -li.spacer { - margin-top: 1.5em; - margin-bottom: 1.5em; -} - -.screenshots { - background-color: white; - padding-left: 3em; - float: right; - width: 270px; - font-size: x-small; -} -.smallshotconst { - width: 270px; - height: 220px; - margin: 0em 1em; - text-align: center; - font-style: italic; -} -.smallshotconst em { - font-style: normal; -} - - - -pre.license { - width: 46em; - margin: 1em auto; -} - - -.note { - font-size: 80%; -} - -.spacing { - margin-top: 2em; - margin-bottom: 2em; -} - -dl { - margin: 0 2em; -} - -span.command { - white-space: nowrap; - font-family: monospace; - border: solid 1px #ddd; - background-color: #eee; - padding: 1px 3px; -} - -.center { - text-align: center; -} \ No newline at end of file diff --git a/core/web/html/android_logo.png b/core/web/html/android_logo.png deleted file mode 100644 index 198f79c9..00000000 Binary files a/core/web/html/android_logo.png and /dev/null differ diff --git a/core/web/html/border-radius.htc b/core/web/html/border-radius.htc deleted file mode 100644 index c3ae104c..00000000 --- a/core/web/html/border-radius.htc +++ /dev/null @@ -1,143 +0,0 @@ ---Do not remove this if you are using-- -Original Author: Remiz Rahnas -Original Author URL: http://www.htmlremix.com -Published date: 2008/09/24 - -Changes by Nick Fetchak: -- IE8 standards mode compatibility -- VML elements now positioned behind original box rather than inside of it - should be less prone to breakage -Published date : 2009/11/18 - - - - - diff --git a/core/web/html/cc-by-nc-nd-80x15.png b/core/web/html/cc-by-nc-nd-80x15.png deleted file mode 100644 index 072f8cda..00000000 Binary files a/core/web/html/cc-by-nc-nd-80x15.png and /dev/null differ diff --git a/core/web/html/cc-by-sa-80x15.png b/core/web/html/cc-by-sa-80x15.png deleted file mode 100644 index c67509f1..00000000 Binary files a/core/web/html/cc-by-sa-80x15.png and /dev/null differ diff --git a/core/web/html/contact.html b/core/web/html/contact.html deleted file mode 100644 index a878d4bf..00000000 --- a/core/web/html/contact.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - OpenRocket — Support and contact information - - - - - - - - -

Support and contact information for OpenRocket

-
-

Mailing lists

-

OpenRocket currently has two mailing lists for - intrested users:

-
-
- OpenRocket-announce -   - (archives) -
-
Announcements of new OpenRocket versions and - developments. This list is moderated.
-
- OpenRocket-devel -   - (archives) -
-
Discussion related to OpenRocket development, documentation - and upcoming features.
-
-

You are welcome to join the development mailing list if you are - interested in contributing something to OpenRocket or simply want - hear about and discuss future development. Note that support - requests should be sent to the - support - forums instead!

-

Unsubscribing from the lists can be performed - in the above links as well. Please do not send unsubscription - requests to the list.

-

Support forums

-

The official support forum for OpenRocket is the - Rocketry - Electronics and Software forum at - The Rocketry Forum.

-

Please ask any questions on using OpenRocket on that forum, - where others can answer as well and gain knowledge from the - answers.

-

Contact information

-

The main developer of OpenRocket is Sampo Niskanen. His contact - information can be found below.

-

Support requests should be sent to - the support - forums.
- -

Email:    - sampo.niskanen@iki.fi

-

WWW:    - http://www.iki.fi/sampo.niskanen/

-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/documentation.html b/core/web/html/documentation.html deleted file mode 100644 index c4e340b4..00000000 --- a/core/web/html/documentation.html +++ /dev/null @@ -1,122 +0,0 @@ - - - - OpenRocket — Documentation - - - - - - - - -

Documentation for OpenRocket

-
-

User documentation

-

Unfortunately no user's guide currently exists for OpenRocket. - Some documentation is available in the - OpenRocket - wiki pages, including a stub - User's - guide and a section of - frequently - asked questions.

-

If you would like to help, please extend the documentation!

-

Technical documentation

-

OpenRocket was originally written as the Master's thesis of - Sampo Niskanen at Helsinki University of Technology. This thesis - is being extended and updated as the OpenRocket technical - documentation. Below is the latest technical documentation and - the original Master's thesis.

-
-

- CC BY-SA - OpenRocket technical documentation (2011-07-18) -    (PDF 1.4MB) -

-

- CC BY-NC-ND - Development of an Open Source model rocket simulation software (Master's thesis) -    (PDF 1.3MB) -

-
-

The technical documentation is licensed under a - Creative Commons Attribution-ShareAlike License - while the Master's thesis is licensed under a - Attribution-NonCommercial-NoDerivs - License. -

-

Table of contents:

-
    -
  1. 1. Introduction
  2. -
  3. 2. Basics of model rocket flight
  4. -
  5. 3. Aerodynamic properties of model rockets
  6. -
  7. 4. Flight simulation
  8. -
  9. 5. The OpenRocket simulation software
  10. -
  11. 6. Comparison with experimental data
  12. -
  13. 7. Conclusion
  14. -
-
    -
  1. A. Nose cone and transition geometries
  2. -
  3. B. Transonic wave drag of nose cones
  4. -
  5. C. Streamer drag coefficient estimation
  6. -
-

Resources

-

A list of useful technical rocketry resources is available in - the "Resources" - wiki page, including links to Barrowman's original report and - thesis, extensions for the Barrowman method, experimental rocket - data etc.

-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/download.html b/core/web/html/download.html deleted file mode 100644 index a99f29d2..00000000 --- a/core/web/html/download.html +++ /dev/null @@ -1,167 +0,0 @@ - - - - OpenRocket — Download - - - - - - - - -

Download OpenRocket

-
-
-

Recent news:

-

16.9.2012: Version 12.09 is - released!

-

This version contains a huge number of new features by many contributors:

-
    -
  • 3D rocket design view
  • -
  • Component Presets
  • -
  • Custom expressions in simulations
  • -
  • Printing for centering ring and clustered centering ring components
  • -
  • Support simple arthmatic in dimension entry
  • -
  • Support deploying recovery device at stage separation
  • -
  • Support for fractional inches (1/64) for unit length
  • -
  • Added preference for windspeed units separately
  • -
  • Added "most recently used files" in File Menu
  • -
  • Improved printed accurracy in fin marking guide
  • -
  • Calibration rulers added to printed templates
  • -
  • Translations in Czech and Polish, numerous updates
  • -
-

10.3.2012: Version 12.03 for desktop - and Android is released!

-

In this release the version numbering scheme has been changed. - From now on the version number is YY.MM indicating the - year and month of the release. Bug fix releases are indicated by - an added ".1".

-

This also marks the first release for Android devices. In this - first release you can open files and examine existing simulations, - stability data and motor files. The Android port is thanks to - work by Kevin Ruland.

-

Enhancements in the desktop version include saving designs in RKT - format thanks to Doug Pedrick, freeform fin set import form images - by Jason Blood, configurable stage separation - events, guided help tours and displaying the computed motor - designation class. The application has also been translated to - Italian by Mauro Biasutti and Russian by the Sky Dart Team.

-
-
-

Ready packages

-

These are packages ready for use and are the recommended - download for normal users. They are pre-packaged with motor - thrust curves from - thrustcurve.org.

-

OpenRocket requires Java version 6 or - later. The Sun Java Runtime is recommended.

-

Desktop version

-

This is the latest version of the desktop version of - OpenRocket. It contains the latest and greatest features, and - runs on any system supporting Java.

-
- -
-
- Support This Project -
- -

OpenRocket can be started in most graphical environments (including - Windows) by double-clicking the package icon. No installation is - required.

-

From the command line OpenRocket can be started by - java -jar OpenRocket-12.09.jar

-

Android version

-

The Android version allows opening OpenRocket files, viewing - simulations and motors. Later versions will allow running - simulations as well.

-

The Android version is thanks to the fantastic work by Kevin - Ruland.

-
- -
-
-

Installation:

-
    -
  1. Go to SettingsApplications and - check Unknown sources.
  2. -
  3. Download OpenRocket-Android-12.03.apk - on your device and accept installation.
  4. -
-
-
-
-

Source code and older versions

-

Source packages and older versions of - OpenRocket are available in the - SourceForge repository.

-

Alternatively, the most recent development version can be - obtained from the - SVN - repository. It can be retrieved simply using the command

-
$ svn co https://openrocket.svn.sourceforge.net/svnroot/openrocket/trunk OpenRocket
-

The above URL may be used to connect to the repository with - other Subversion clients as well.

-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/favicon.ico b/core/web/html/favicon.ico deleted file mode 100644 index 09c23f8f..00000000 Binary files a/core/web/html/favicon.ico and /dev/null differ diff --git a/core/web/html/features.html b/core/web/html/features.html deleted file mode 100644 index f774c063..00000000 --- a/core/web/html/features.html +++ /dev/null @@ -1,182 +0,0 @@ - - - - OpenRocket — Features and screenshots - - - - - - - - -

Features of OpenRocket

-
-

Current features

- -

General

-
    -
  • Fully cross-platform, written in Java
  • -
  • Fully documented simulation - methods
  • -
  • Open Source, source code available under the - GNU GPL
  • -
-

User interface

-
    -
  • Easy-to-use user interface for - rocket design
  • -
  • Real-time view of CG and CP position
  • -
  • Real-time flight altitude, velocity and - acceleration information from a continuous simulation - performed in the background
  • -
  • Zoomable schematic view of rocket from the side or rear, - with rotation around the center axis
  • -
-

Design

-
    -
  • A multitude of available components to - choose from
  • -
  • Trapezoidal, elliptical - and free-form fins supported
  • -
  • Support for canted fins (roll - stabilization)
  • -
  • Staging and clustering support
  • -
  • Automatic calculation of component mass and CG based on - shape and density
  • -
  • Ability to override mass and CG of - components or stages separately
  • -
-

Simulation and analysis

-
    -
  • Full six degree of freedom simulation
  • -
  • Rocket stability computed using extended Barrowman - method
  • -
  • Automatic design optimization — you - can optimize any number of rocket parameters for flight - altitude, maximum velocity or a number of other values
  • -
  • Realistic wind modeling
  • -
  • Analysis of the effect of separate - components on the stability, drag and roll - characteristics of the rocket
  • -
  • Fully configurable plotting, with - various preset configurations
  • -
  • Simulation data can be exported to - CSV - files for further analysis
  • -
  • Simulation listeners allowing custom-made - code to interact with the rocket during flight simulation
  • -
-

Planned future features

-

OpenRocket is under constant work in the free time of the - developers. You can have a sneak preview on what has been - planned by checking the - TODO-file - in the SVN repository.

-

Below are a few major features that are under consideration:

-
    -
  • Aerodynamic computation using - CFD - (help needed!)
  • -
  • Better support for supersonic simulation - (help needed!)
  • -
  • 3D view of the rocket design - (help - needed!)
  • -
  • Printing and saving figures, simulation data and designs
  • -
  • Support for ready-made component databases
  • -
  • Customized support for hybrid rocket motors and water - rockets
  • -
  • Importing and plotting actual flight data from altimeters
  • -
  • Rocket flight animation
  • -
  • A "wizard" for creating new rocket designs
  • -
  • More ideas are listed in the - TODO-file!
  • -
-

If you want to help make OpenRocket the best rocket simulator, - don't hesitate to Get involved!

-
-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/getinvolved.html b/core/web/html/getinvolved.html deleted file mode 100644 index 91023aed..00000000 --- a/core/web/html/getinvolved.html +++ /dev/null @@ -1,138 +0,0 @@ - - - - OpenRocket — Get involved! - - - - - - - - -

Get involved in OpenRocket development

-
-

How can I help OpenRocket?

-

OpenRocket is an Open Source project, meaning that the source - code is freely available and anybody can help make the software - better. The program is mainly developed by Sampo Niskanen in - his free time. Help is very much appreciated. You don't even - need coding skills, as there are other things to do as well.

-

Below are a few suggestions of areas that would need help. If - you'd like to participate, please - join - the development mailing list and introduce your ideas there.

- -

Java development

-

Below are a few ideas about what kind of input developers can - provide or features that could be implemented. For more - information see the feature roadmap in the distribution - TODO-file.

-
    -
  • 3D visualization of the rocket during design and flight - (Help needed!) -
  • -
  • Printing of designs, simulation results, fin planforms - etc
  • -
  • Memory profiling and leakage reduction
  • -
  • Writing RockSim design files
  • -
  • UI enhancements, for example zooming plots etc.
  • -
-

Aerodynamic computation methods

-

There is still work to be done in the aerodynamic computation - methods of OpenRocket. At least the following items need - help. I will gladly provide help in creating and even - implementing the computational methods.

-
    -
  • Simulating rockets at supersonic velocities (drag - coefficient and CG position).
  • -
  • Support for external pods and tube fins
  • -
  • CFD - methods for simulation
  • -
-

Documentation tasks

-

Contributions to the - OpenRocket - User's guide are dearly needed. Below are examples of - topics.

-

(Unfortunately the SourceForge wiki currently does - not support public write access to the wiki. If you'd like to - contribute, please contact me and I - will provide you write access.)

-
    -
  • Getting started guide
  • -
  • How to make staged and clustered designs
  • -
  • Using mass/CG overrides for simulation accuracy
  • -
  • Using simulations
  • -
  • Effect of the simulation parameters
  • -
  • Simulation method limitations
  • -
  • Using simulation listeners (including examples)
  • -
-

Other

-
    -
  • Translating OpenRocket to your language
  • -
  • Creating good and interesting example designs that - demonstrate some OpenRocket features.
  • -
  • Hosting a place to share rocket designs with other - enthusiasts.
  • -
  • Giving input and suggestions on how to make OpenRocket - better.
  • -
-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/icon.png b/core/web/html/icon.png deleted file mode 100644 index 3f81fdf8..00000000 Binary files a/core/web/html/icon.png and /dev/null differ diff --git a/core/web/html/index-manual.html b/core/web/html/index-manual.html deleted file mode 100644 index 358b5418..00000000 --- a/core/web/html/index-manual.html +++ /dev/null @@ -1,168 +0,0 @@ - - - - OpenRocket - - - - - - - - -

OpenRocket — an Open Source model rocket simulator

- - - - -
- -

Introduction

- -

OpenRocket is a Free, fully featured model - rocket simulator written in Java. It can be used to design and - simulate rockets before actually building and flying them. -

-

OpenRocket features a full six-degree-of-freedom simulation, - realistic wind modeling, a multitude of different components - including free-form fins and canted fins, clustering and - staging. Read more about its features. -

-

Best of all, OpenRocket is Open Source—its source code is - freely available to study and extend. Anybody wishing to - contribute to the project can do so according to the - GNU GPL. Simply - download the source code - and start hacking, or get the ready - package to begin designing and simulating. -

-

OpenRocket is still considered to be beta - software—there will still be bugs and occasional - problems. If you encounter problems, please - report them so they can be fixed. -

- - -
- - -

News

- -

28.11.2009: Version 0.9.5 is - released!

- -

This release fixes a serious bug in 0.9.4 that - prevented adding a tube coupler and centering ring to the same - body tube, in addition to a few smaller additions. Users of - 0.9.4 should upgrade immediately!

- -

24.11.2009: Version 0.9.4 is - released!

- -

This version adds support for through-the-wall fin tabs, - attaching components to coupler tubes, material editing, automatic - update checking, in addition to fixing numerous bugs.

- -

1.9.2009: Version 0.9.3 is - released!

- -

This version includes lots of bug fixes and new features including - data exporting, showing flight events in plots, example rocket designs, - splitting clustered inner tubes and automated bug reporting.

- -

13.7.2009: Version 0.9.2 is - released!

- -

This version includes bug fixes for imperial unit - conversions and UI improvements for motor selection. - All users of imperial units should upgrade!

- -

9.6.2009: The - Master's thesis for which OpenRocket - was written for is now available!

- -

At the same time version 0.9.1 was - released. This release fixes various - file handling bugs and adds small UI enhancements.

- -

24.5.2009: First version 0.9.0 - released!

- -
-
-
-
-
-
-
-
- -
- - -
-

Valid XHTML 1.0! - Valid CSS! -

-
- - - - - - - - - diff --git a/core/web/html/index.html b/core/web/html/index.html deleted file mode 100644 index f2bfdce5..00000000 --- a/core/web/html/index.html +++ /dev/null @@ -1,266 +0,0 @@ - - - - OpenRocket - - - - - - - - -

OpenRocket — an Open Source model rocket simulator

-
-

Introduction

- -

OpenRocket is a free, fully featured model - rocket simulator that allows you to design and simulate your - rockets before actually building and flying them.

-

The main features include:

-
    -
  • Six-degree-of-freedom flight simulation
  • -
  • Automatic design optimization
  • -
  • Realtime simulated altitude, velocity and acceleration display
  • -
  • Staging and clustering support
  • -
  • Cross-platform (Java-based)
  • -
-

Read more about its features and see screenshots. -

-

OpenRocket is an Open Source project licensed under the - GNU GPL. This means that the - software is free to use for whatever purposes, and the source - code is also available for studying and extending. -

-

OpenRocket needs help to become even better. Implementing - features, writing documentation and creating example designs are - just a few ways of helping. If you are interested in helping - make OpenRocket the best rocket simulator out there, please - Get involved! -

-
-
-

News

-

16.9.2012: Version 12.09 is - released!

-

This version contains a huge number of new features by many contributors:

-
    -
  • 3D rocket design view
  • -
  • Component Presets
  • -
  • Custom expressions in simulations
  • -
  • Printing for centering ring and clustered centering ring components
  • -
  • Support simple arthmatic in dimension entry
  • -
  • Support deploying recovery device at stage separation
  • -
  • Support for fractional inches (1/64) for unit length
  • -
  • Added preference for windspeed units separately
  • -
  • Added "most recently used files" in File Menu
  • -
  • Improved printed accurracy in fin marking guide
  • -
  • Calibration rulers added to printed templates
  • -
  • Translations in Czech and Polish, numerous updates
  • -
-

10.3.2012: Version 12.03 for desktop - and Android is released!

-

In this release the version numbering scheme has been changed. - From now on the version number is YY.MM indicating the - year and month of the release. Bug fix releases are indicated by - an added ".1".

-

This also marks the first release for Android devices. In this - first release you can open files and examine existing simulations, - stability data and motor files. The Android port is thanks to - work by Kevin Ruland.

-

Enhancements in the desktop version include saving designs in RKT - format thanks to Doug Pedrick, freeform fin set import form images - by Jason Blood, configurable stage separation - events, guided help tours and displaying the computed motor - designation class. The application has also been translated to - Italian by Mauro Biasutti and Russian by the Sky Dart Team.

-

24.11.2011: Version 1.1.9 is - released!

-

For this version Richard Graham has implemented geodetic - computation methods, which take into account the curvature of the - Earth and the coriolis effect. The computation method is selected - by the Geodetic calculations option in the simulation - options. It's not (yet) a full spherical computation model, but - should be accurate enough for almost all sub-orbital needs.

-

Doug Pedrick has also enhanced the printing system with the - ability to print fin positioning guides, transition templates and - nose cone profiles. Other smaller enhancements and bug fixes are - also included.

-

25.8.2011: Version 1.1.8 is - released!

-

This release contains bug fixes to the optimization methods. - It also contains a workaround to a JRE bug that prevents running - OpenRocket on some builds of Java 7.

-

The web pages have also been somewhat updated and Boris du Reau has - created a separate site - for coordinating the localization efforts for OpenRocket.

-

12.8.2011: Version 1.1.7 is - released!

-

This release includes automatic rocket design optimization - support (AnalyzeRocket optimization). - You can optimize any amount of rocket parameters for apogee - altitude, maximum velocity or a number of different values.

-

While the automatic optimization is a powerful tool, it is very - easy to optimize against particulars of the simulation methods, - instead of true physical phenomena. Always keep common sense at - hand and take the results with a grain of salt.

-

22.7.2011: Version 1.1.6 is - released!

-

This release includes initial localization support and - translations to French, German and Spanish. This is thanks to the - great work of Boris du Reau, and the teams from Tripoli France, - Tripoli Spain and ERIG e.V. If you prefer to use some other - language than the system default, you can select the language on - the "Options" tab of the preferences dialog.

-

The release also includes design scaling support and numerous bug - fixes.

-

10.6.2011: Version 1.1.5 is - released!

-

This release includes updates to the printing system which fixes - printing on Windows.

-

5.3.2011: Version 1.1.4 is - released!

-

This release includes initial printing support, thanks to Doug - Pedrick. Printing still has a few issues on some platforms. - Various bugs have also been fixed.

-

6.10.2010: Version 1.1.3 is - released!

-

This release includes support for moving and copying components - in the component tree using drag-and-drop. Use normal DnD for - moving, and control-drag for copy. This release also fixes a - severe bug in the undo system.

-

7.9.2010: A bug-fix version 1.1.2 is - released!

-

This release fixes a severe bug in 1.1.1 that prevented adding stages - to rocket designs. Users are recommended to upgrade.

-

3.9.2010: Version 1.1.1 is - released!

-

For this release a major part of the simulator code has been - rewritten for better flexibility in future development. It also - includes a vastly improved thrust curve selection dialog, the - possibility to loading user-defined thrust curves and better - startup times than previous releases.

-

Simulation listeners written for older versions of OpenRocket - are not compatible with this release.

-

21.3.2010: Version 1.1.0 is - released!

-

This release includes the first support for loading RockSim - rocket design files (.RKT), thanks to contributions by Doug - Pedrick. It's also the kick-off of the 1.1 development branch of - OpenRocket.

-

10.3.2010: Version 1.0.0 is - released!

-

This release includes several hundred new thrustcurves from - thrustcurve.org and some - bug fixes. It is also a stable milestone, after which development - on larger features will be started in a 1.1 branch. Look out - for it! :-)

-

17.2.2010: Version 0.9.6 is - released!

-

This release updates the aerodynamic calculation methods to be - more in line with the Barrowman method and enhances the simulation - time step selection, in addition to fixing numerous bugs.

-

28.11.2009: Version 0.9.5 is - released!

-

This release fixes a serious bug in 0.9.4 that - prevented adding a tube coupler and centering ring to the same - body tube, in addition to a few smaller additions. Users of - 0.9.4 should upgrade immediately!

-

24.11.2009: Version 0.9.4 is - released!

-

This version adds support for through-the-wall fin tabs, - attaching components to coupler tubes, material editing, automatic - update checking, in addition to fixing numerous bugs.

-

1.9.2009: Version 0.9.3 is - released!

-

This version includes lots of bug fixes and new features including - data exporting, showing flight events in plots, example rocket designs, - splitting clustered inner tubes and automated bug reporting.

-

13.7.2009: Version 0.9.2 is - released!

-

This version includes bug fixes for imperial unit - conversions and UI improvements for motor selection. - All users of imperial units should upgrade!

-

9.6.2009: The - Master's thesis for which OpenRocket - was written for is now available!

-

At the same time version 0.9.1 was - released. This release fixes various - file handling bugs and adds small UI enhancements.

-

24.5.2009: First version 0.9.0 - released!

-
-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/java_logo.png b/core/web/html/java_logo.png deleted file mode 100644 index 1666deb5..00000000 Binary files a/core/web/html/java_logo.png and /dev/null differ diff --git a/core/web/html/layout.css b/core/web/html/layout.css deleted file mode 100644 index 34954ee4..00000000 --- a/core/web/html/layout.css +++ /dev/null @@ -1,591 +0,0 @@ - -body { - margin: 0; - padding: 0; - background-color: black; - background-image: url(starfield.jpg); -} - -#iewarn { - width: 100%; - font-size: 140%; - background-color: #fa0; - text-align: center; - padding: 2em 2em; - border-top: solid 1px black; - border-bottom: solid 1px black; -} - -h1 { - margin: 0.75em 1.7em 1.25em 120px; - color: #bbf; - text-align: right; -} - -h2 { - margin-top: 1.5em; - border-bottom: dotted 2px #f99; -} -/* TODO: Change to direct next element */ -div.content h2:first-child { - margin-top: 0em; -} - -h3 { - margin-top: 1.5em; - border-bottom: dotted 1px #99f; -} - -h3.minor, h4.minor, h5.minor { - font-size: 100%; - border-bottom: none; -} - - -a { - text-decoration: none; - color: #00B; -} -a:hover { - color: #44c; -} - - -div.icon { - position: absolute; - width: 194px; - height: 214px; - left: 0px; - top: -178px; - background: url('icon.png') no-repeat; -} -div.icon a { - display: block; - position: absolute; - left: 0px; - right: 25px; - top: 0px; - bottom: 0px; -/* border: solid 1px red; */ -} - - -div.menucontainer { - position: absolute; - top: 90px; - left: 0px; - z-index: 100; -} - -div.menu { - position: absolute; - left: 20px; - top: 95px; - width: 170px; - margin: 0; - padding: 0 0; - - background: url("menubg.png") repeat-x scroll 0 -35px #C1D0DB; - - z-index: 200; - border: solid 1px black; - -moz-border-radius: 12px; - -webkit-border-radius: 12px; - -khtml-border-radius: 12px; - border-radius: 12px; - -moz-box-shadow: 0px 1px 10px 0px rgba(0,0,0,0.5); - -webkit-box-shadow: 0px 1px 10px 0px rgba(0,0,0,0.5); - box-shadow: 0px 1px 10px 0px rgba(0,0,0,0.5); -} -div.menu ul { - position: relative; - list-style: none; - margin: 0; - padding: 0 0; -} - -div.menu li { - display: block; - left: 0; - right: 0; - margin: 0; - text-align: center; -} - -div.menu li a { - display: block; - left: 0; - right: 0; - font-style: normal; - text-decoration: none; - color: #00d; - padding: 0.65em 1em; - outline: none; - border: 1px solid transparent; -} - -div.menu li:first-child a { - padding: 0.5em 0 !important; - font-size: 160% !important; - font-weight: normal !important; - color: #003 !important; - background-color: transparent !important; - border: 1px solid transparent !important; - text-shadow: #666 1px 1px 3px; -} - -div.menu li a:hover { - /* Copied below */ - background-color: #eeb6b6; - background-color: rgba(255,240,240,0.5); - border: 1px solid rgba(0,0,0,0.3); - -moz-border-radius: 12px; - -webkit-border-radius: 12px; - -khtml-border-radius: 12px; - border-radius: 12px; -} - - - -div.menu div.logo { - position: absolute; - top: 100%; - left: -2px; - margin-top: 15px; - width: 100%; -} - -div.menu div.logo img { - display: block; - margin: 0 auto; -} - - -.page_features div.menu a[href="features.html"], -.page_screenshots div.menu a[href="screenshots.html"], -.page_download div.menu a[href="download.html"], -.page_documentation div.menu a[href="documentation.html"], -.page_getinvolved div.menu a[href="getinvolved.html"], -.page_contact div.menu a[href="contact.html"], -.page_report div.menu a[href="report.html"], -.page_license div.menu a[href="license.html"] { - font-weight: bold; - background-color: transparent; - background-color: rgba(255,240,240,0.2); - border: 1px solid rgba(0,0,255,0.15); - -moz-border-radius: 12px; - -webkit-border-radius: 12px; - -khtml-border-radius: 12px; - border-radius: 12px; -} -.page_features div.menu a[href="features.html"]:hover, -.page_screenshots div.menu a[href="screenshots.html"]:hover, -.page_download div.menu a[href="download.html"]:hover, -.page_documentation div.menu a[href="documentation.html"]:hover, -.page_getinvolved div.menu a[href="getinvolved.html"]:hover, -.page_contact div.menu a[href="contact.html"]:hover, -.page_report div.menu a[href="report.html"]:hover, -.page_license div.menu a[href="license.html"]:hover { - /* Copied above */ - background-color: #eeb6b6; - background-color: rgba(255,240,240,0.5); - border: 1px solid rgba(0,0,0,0.3); - -moz-border-radius: 12px; - -webkit-border-radius: 12px; - -khtml-border-radius: 12px; - border-radius: 12px; -} - - -.content { - margin: 0em 2em 1em 130px; - padding: 2em 2em 2em 95px; - min-height: 27em; - background-color: white; - position: relative; - *border: 2px solid #666; - min-height: 530px; - - -moz-border-radius: 7px; - -webkit-border-radius: 7px; - border-radius: 7px; - - -moz-box-shadow: 0px 0px 8px 5px white; - -webkit-box-shadow: 0px 0px 8px 5px white; - box-shadow: 0px 0px 8px 5px white; -} - - -.gradientbutton { - display: inline-block; - width: 200px; - height: 100px; - - border-top: 2px solid #6f2; - border-left: 1px solid #4c1; - border-right: 1px solid #380; - border-bottom: 2px solid #360; - - background-color: #5c2; - - -moz-border-radius: 10px; - -webkit-border-radius: 10px; - border-radius: 10px; - - background-image: -webkit-gradient( - linear, - left bottom, - left top, - color-stop(0.08, rgb(55,146,14)), - color-stop(0.9, rgb(102,221,17)) - ); - background-image: -moz-linear-gradient( - center bottom, - rgb(55,146,14) 8%, - rgb(102,221,17) 90% - ); -/* - background: -moz-linear-gradient(center bottom , #0B5CE2 30%, #2678FF 65%) repeat scroll 0 0; -/** */ -} - - - -img { - border: 0px; - outline: none; - font-size: 70%; -} - -.smallshot { - float: left; - margin-top:2em; - text-align: center; - font-style: italic; - margin-right: 2em; -} -.smallshot.last { - margin-right: 0; -} -.clear { - clear:both; -} - - - - -a.help { - margin-left: 1em; - font-size: smaller; - font-style: italic; -} - - -pre.quote { - margin: 0.5em 2em; - padding: 1em; - border: dashed 1px #888; - background-color: #ddd; - display: inline-block; -} - -p.quote { - margin: 2em; -} - -div.separated { - padding: 0.5em; -} - -hr { - margin: 2em 0em; -} - -.left { - float: left; - margin: 0; -} - -.right { - float: right; - margin: 0; -} - -li { - margin-top: 0.5em; -} - - -p.download { - margin: 2em; -} -p.download a { - font-size: 140%; - font-style: italic; - padding: 0.5em; - border: dashed 1px red; - background-color: #89cbe0; - outline: none; -} -p.download a:hover { - color: #00F; - background-color: #ee9494; -} -p.download a:focus { - background-color: #8fd5eb; -} - -div.valid { - float: right; - margin-right: 2em; -} - - - -ol.toc { - list-style-type: none; -} - -dt+dt { - margin-top: 0.5em; -} -dd { - margin-top: 0.2em; - margin-bottom: 1.4em; -} - - -div.downloadbox { - position: relative; - width: 180px; - height: 80px; - text-align: left; - - border-top: 2px solid #6e2; - border-left: 1px solid #4c1; - border-right: 1px solid #380; - border-bottom: 2px solid #360; - - -moz-box-shadow: 1px 1px 4px 0px #333; - -webkit-box-shadow: 1px 1px 4px 0px #333; - box-shadow: 1px 1px 4px 0px #333; - - - background-color: #5c2; - - -moz-border-radius: 10px; - -webkit-border-radius: 10px; - border-radius: 10px; - - background-image: -webkit-gradient( - linear, - left bottom, - left top, - color-stop(0.08, rgb(55,156,14)), - color-stop(0.9, rgb(102,221,17)) - ); - background-image: -moz-linear-gradient( - center bottom, - rgb(55,156,14) 8%, - rgb(102,221,17) 90% - ); - - white-space: nowrap; -} - -div.downloadbox a.main { - position: absolute; - left: 0px; - right: 0px; - top: 0px; - bottom: 0px; - - color: #a0ff4b; - font-family: Arial, sans-serif; - - padding: 8px 12px; - text-shadow: #666 1px 1px 1px; -} -div.downloadbox a.main span { - font-size: 90%; -} -div.downloadbox a.main:hover { - text-shadow: #000 1px 1px 1px; -} - -div.downloadbox a strong { - display: block; - margin-bottom: 3px; - color: white; - font-weight: bold; - font-size: larger; -} -div.downloadbox a:hover strong { - text-shadow: #666 1px 1px 1px; -} - - -div.downloadbox .alternative { - position: absolute; - bottom: 0; - left: 0; - right: 0; - margin: 0; - padding: 0 10px 10px 10px; - font-size: 11px; - font-family: Arial, sans-serif; - color: #244506; -} -div.downloadbox .alternative a { - color: #244506; -} -div.downloadbox .alternative a+a { - text-align: right; -} -div.downloadbox .alternative a:hover { - color: black; -} -/* -.page_index div.downloadbox { - width: 195px; - margin: 0.5em 0 1em 50px; -} -*/ -.rightpane { - width: 210px; - float: right; - clear: both; - margin: 0 0 0 30px; - text-align: center; -} -.rightpane div { - margin: 2em auto; -} - -.rightpane div.downloadbox { - margin: 0 auto 2em auto; -} -.rightpane div.screenshot { - font-size: smaller; - font-style: italic; - text-align: center; -} -.rightpane div.support { - margin-bottom: 0; - text-align: center; -} - -.page_download div.support { - margin: 20px 0; -} - -.rightimg { - width: 210px; - float: right; - clear: both; - margin: 2em 0 2em 30px; - font-size: smaller; - font-style: italic; - text-align: center; -} -.rightimg img { - display: block; - margin-bottom: 1em; -} - - - -div.news .date { - font-weight: bold; -} - -.page_download div.contentholder { - margin-right: 15em; -} -.page_download div.news { - background-color: white; - padding-left: 3em; - float: right; - width: 18em; - font-size: x-small; -} -.page_download div.news h2 { - border-bottom: none; - margin-bottom: 1em; -} -.page_download div.news .date { - display: block; -} -.page_download div.downloadbox { - margin-left: auto; - margin-right: auto; -} - - -li.spacer { - margin-top: 1.5em; - margin-bottom: 1.5em; -} - -.screenshots { - background-color: white; - padding-left: 3em; - float: right; - width: 270px; - font-size: x-small; -} -.smallshotconst { - width: 270px; - height: 220px; - margin: 0em 1em; - text-align: center; - font-style: italic; -} -.smallshotconst em { - font-style: normal; -} - - - -pre.license { - width: 46em; - margin: 1em auto; -} - - -.note { - font-size: 80%; -} - -.spacing { - margin-top: 2em; - margin-bottom: 2em; -} - -dl { - margin: 0 2em; -} - -span.command { - white-space: nowrap; - font-family: monospace; - border: solid 1px #ddd; - background-color: #eee; - padding: 1px 3px; -} - -.center { - text-align: center; -} - -span.licenseimage { - display: block; - float: left; - width: 100px; - margin-left: 10px; - margin-top: 2px; -} - -.instructions { - margin-left: 100px; -} \ No newline at end of file diff --git a/core/web/html/license.html b/core/web/html/license.html deleted file mode 100644 index 3bb00857..00000000 --- a/core/web/html/license.html +++ /dev/null @@ -1,773 +0,0 @@ - - - - OpenRocket — License - - - - - - - - -

OpenRocket license

-
-

The license text is available also in the simulator under - Help → License and in the file - LICENSE.TXT.

-
-
-OpenRocket - A model rocket simulator
-
-Copyright (C) 2007-2012 Sampo Niskanen and others
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 3 of the License, or (at
-your option) any later version.
-
-This program is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License (below) for more details.
-
-
-Additional permission under GNU GPL version 3 section 7:
-
-The licensors grant additional permission to package this Program, or
-any covered work, along with any non-compilable data files (such as
-thrust curves or component databases) and convey the resulting work.
-
-
-------------------------------------------------------------------------
-
-
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-			    Preamble
-
-  The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
-  The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works.  By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.  We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors.  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
-  To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights.  Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received.  You must make sure that they, too, receive
-or can get the source code.  And you must show them these terms so they
-know their rights.
-
-  Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
-  For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software.  For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
-  Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so.  This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software.  The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable.  Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products.  If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
-  Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary.  To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-		       TERMS AND CONDITIONS
-
-  0. Definitions.
-
-  "This License" refers to version 3 of the GNU General Public License.
-
-  "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
- 
-  "The Program" refers to any copyrightable work licensed under this
-License.  Each licensee is addressed as "you".  "Licensees" and
-"recipients" may be individuals or organizations.
-
-  To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy.  The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
-  A "covered work" means either the unmodified Program or a work based
-on the Program.
-
-  To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy.  Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
-  To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies.  Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
-  An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License.  If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
-  1. Source Code.
-
-  The "source code" for a work means the preferred form of the work
-for making modifications to it.  "Object code" means any non-source
-form of a work.
-
-  A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
-  The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form.  A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
-  The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities.  However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work.  For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
-  The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
-  The Corresponding Source for a work in source code form is that
-same work.
-
-  2. Basic Permissions.
-
-  All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met.  This License explicitly affirms your unlimited
-permission to run the unmodified Program.  The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work.  This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
-  You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force.  You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright.  Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
-  Conveying under any other circumstances is permitted solely under
-the conditions stated below.  Sublicensing is not allowed; section 10
-makes it unnecessary.
-
-  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-  No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
-  When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
-  4. Conveying Verbatim Copies.
-
-  You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
-  You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
-  5. Conveying Modified Source Versions.
-
-  You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
-    a) The work must carry prominent notices stating that you modified
-    it, and giving a relevant date.
-
-    b) The work must carry prominent notices stating that it is
-    released under this License and any conditions added under section
-    7.  This requirement modifies the requirement in section 4 to
-    "keep intact all notices".
-
-    c) You must license the entire work, as a whole, under this
-    License to anyone who comes into possession of a copy.  This
-    License will therefore apply, along with any applicable section 7
-    additional terms, to the whole of the work, and all its parts,
-    regardless of how they are packaged.  This License gives no
-    permission to license the work in any other way, but it does not
-    invalidate such permission if you have separately received it.
-
-    d) If the work has interactive user interfaces, each must display
-    Appropriate Legal Notices; however, if the Program has interactive
-    interfaces that do not display Appropriate Legal Notices, your
-    work need not make them do so.
-
-  A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit.  Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
-  6. Conveying Non-Source Forms.
-
-  You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
-    a) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by the
-    Corresponding Source fixed on a durable physical medium
-    customarily used for software interchange.
-
-    b) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by a
-    written offer, valid for at least three years and valid for as
-    long as you offer spare parts or customer support for that product
-    model, to give anyone who possesses the object code either (1) a
-    copy of the Corresponding Source for all the software in the
-    product that is covered by this License, on a durable physical
-    medium customarily used for software interchange, for a price no
-    more than your reasonable cost of physically performing this
-    conveying of source, or (2) access to copy the
-    Corresponding Source from a network server at no charge.
-
-    c) Convey individual copies of the object code with a copy of the
-    written offer to provide the Corresponding Source.  This
-    alternative is allowed only occasionally and noncommercially, and
-    only if you received the object code with such an offer, in accord
-    with subsection 6b.
-
-    d) Convey the object code by offering access from a designated
-    place (gratis or for a charge), and offer equivalent access to the
-    Corresponding Source in the same way through the same place at no
-    further charge.  You need not require recipients to copy the
-    Corresponding Source along with the object code.  If the place to
-    copy the object code is a network server, the Corresponding Source
-    may be on a different server (operated by you or a third party)
-    that supports equivalent copying facilities, provided you maintain
-    clear directions next to the object code saying where to find the
-    Corresponding Source.  Regardless of what server hosts the
-    Corresponding Source, you remain obligated to ensure that it is
-    available for as long as needed to satisfy these requirements.
-
-    e) Convey the object code using peer-to-peer transmission, provided
-    you inform other peers where the object code and Corresponding
-    Source of the work are being offered to the general public at no
-    charge under subsection 6d.
-
-  A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
-  A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling.  In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage.  For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product.  A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
-  "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source.  The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
-  If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information.  But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
-  The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed.  Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
-  Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
-  7. Additional Terms.
-
-  "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law.  If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
-  When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it.  (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.)  You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
-  Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
-    a) Disclaiming warranty or limiting liability differently from the
-    terms of sections 15 and 16 of this License; or
-
-    b) Requiring preservation of specified reasonable legal notices or
-    author attributions in that material or in the Appropriate Legal
-    Notices displayed by works containing it; or
-
-    c) Prohibiting misrepresentation of the origin of that material, or
-    requiring that modified versions of such material be marked in
-    reasonable ways as different from the original version; or
-
-    d) Limiting the use for publicity purposes of names of licensors or
-    authors of the material; or
-
-    e) Declining to grant rights under trademark law for use of some
-    trade names, trademarks, or service marks; or
-
-    f) Requiring indemnification of licensors and authors of that
-    material by anyone who conveys the material (or modified versions of
-    it) with contractual assumptions of liability to the recipient, for
-    any liability that these contractual assumptions directly impose on
-    those licensors and authors.
-
-  All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10.  If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term.  If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
-  If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
-  Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
-  8. Termination.
-
-  You may not propagate or modify a covered work except as expressly
-provided under this License.  Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
-  However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
-  Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
-  Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License.  If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
-  9. Acceptance Not Required for Having Copies.
-
-  You are not required to accept this License in order to receive or
-run a copy of the Program.  Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance.  However,
-nothing other than this License grants you permission to propagate or
-modify any covered work.  These actions infringe copyright if you do
-not accept this License.  Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
-  10. Automatic Licensing of Downstream Recipients.
-
-  Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License.  You are not responsible
-for enforcing compliance by third parties with this License.
-
-  An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations.  If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
-  You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License.  For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
-  11. Patents.
-
-  A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based.  The
-work thus licensed is called the contributor's "contributor version".
-
-  A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version.  For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
-  Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
-  In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement).  To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
-  If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients.  "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-  
-  If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
-  A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License.  You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
-  Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
-  12. No Surrender of Others' Freedom.
-
-  If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all.  For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
-  13. Use with the GNU Affero General Public License.
-
-  Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work.  The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
-  14. Revised Versions of this License.
-
-  The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-  Each version is given a distinguishing version number.  If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation.  If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
-  If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
-  Later license versions may give you additional or different
-permissions.  However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
-  15. Disclaimer of Warranty.
-
-  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. Limitation of Liability.
-
-  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
-  17. Interpretation of Sections 15 and 16.
-
-  If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
-		     END OF TERMS AND CONDITIONS
-
-	    How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software: you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation, either version 3 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
-  If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
-    <program>  Copyright (C) <year>  <name of author>
-    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
-  You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
-  The GNU General Public License does not permit incorporating your program
-into proprietary programs.  If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.  But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
-    
-
-
-
-

Valid XHTML 1.0! -

-
- - - - - - diff --git a/core/web/html/menubg.png b/core/web/html/menubg.png deleted file mode 100644 index 535ef97d..00000000 Binary files a/core/web/html/menubg.png and /dev/null differ diff --git a/core/web/html/project-support.jpg b/core/web/html/project-support.jpg deleted file mode 100644 index 5d15550f..00000000 Binary files a/core/web/html/project-support.jpg and /dev/null differ diff --git a/core/web/html/robots.txt b/core/web/html/robots.txt deleted file mode 100644 index 91d9f610..00000000 --- a/core/web/html/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ - -User-agent: * -Disallow: /actions/ - diff --git a/core/web/html/screenshots.html b/core/web/html/screenshots.html deleted file mode 100644 index d424922a..00000000 --- a/core/web/html/screenshots.html +++ /dev/null @@ -1,108 +0,0 @@ - - - - OpenRocket—Screenshots - - - - - - - - -

Screenshots of OpenRocket

- - - - - -
-

Valid XHTML 1.0! - Valid CSS! -

-
- - - - - - - - - diff --git a/core/web/html/shots-small/dialog-analysis.jpg b/core/web/html/shots-small/dialog-analysis.jpg deleted file mode 100644 index 570c4846..00000000 Binary files a/core/web/html/shots-small/dialog-analysis.jpg and /dev/null differ diff --git a/core/web/html/shots-small/dialog-edit.jpg b/core/web/html/shots-small/dialog-edit.jpg deleted file mode 100644 index c2dc593d..00000000 Binary files a/core/web/html/shots-small/dialog-edit.jpg and /dev/null differ diff --git a/core/web/html/shots-small/dialog-plot-options.jpg b/core/web/html/shots-small/dialog-plot-options.jpg deleted file mode 100644 index ad977ab9..00000000 Binary files a/core/web/html/shots-small/dialog-plot-options.jpg and /dev/null differ diff --git a/core/web/html/shots-small/dialog-plot.jpg b/core/web/html/shots-small/dialog-plot.jpg deleted file mode 100644 index d0fc66db..00000000 Binary files a/core/web/html/shots-small/dialog-plot.jpg and /dev/null differ diff --git a/core/web/html/shots-small/main.jpg b/core/web/html/shots-small/main.jpg deleted file mode 100644 index 7fcd9464..00000000 Binary files a/core/web/html/shots-small/main.jpg and /dev/null differ diff --git a/core/web/html/shots/dialog-analysis.png b/core/web/html/shots/dialog-analysis.png deleted file mode 100644 index b71f1aa8..00000000 Binary files a/core/web/html/shots/dialog-analysis.png and /dev/null differ diff --git a/core/web/html/shots/dialog-edit.png b/core/web/html/shots/dialog-edit.png deleted file mode 100644 index 9107859e..00000000 Binary files a/core/web/html/shots/dialog-edit.png and /dev/null differ diff --git a/core/web/html/shots/dialog-plot-options.png b/core/web/html/shots/dialog-plot-options.png deleted file mode 100644 index ca627fa3..00000000 Binary files a/core/web/html/shots/dialog-plot-options.png and /dev/null differ diff --git a/core/web/html/shots/dialog-plot.png b/core/web/html/shots/dialog-plot.png deleted file mode 100644 index 225dca81..00000000 Binary files a/core/web/html/shots/dialog-plot.png and /dev/null differ diff --git a/core/web/html/shots/main.png b/core/web/html/shots/main.png deleted file mode 100644 index 2b9af491..00000000 Binary files a/core/web/html/shots/main.png and /dev/null differ diff --git a/core/web/html/starfield.jpg b/core/web/html/starfield.jpg deleted file mode 100644 index a19fd5c4..00000000 Binary files a/core/web/html/starfield.jpg and /dev/null differ diff --git a/core/web/html/techdoc.pdf b/core/web/html/techdoc.pdf deleted file mode 100644 index ffb4aada..00000000 Binary files a/core/web/html/techdoc.pdf and /dev/null differ diff --git a/core/web/html/thesis.pdf b/core/web/html/thesis.pdf deleted file mode 100644 index e82acf65..00000000 Binary files a/core/web/html/thesis.pdf and /dev/null differ diff --git a/core/web/html/valid-xhtml10.png b/core/web/html/valid-xhtml10.png deleted file mode 100644 index b81de916..00000000 Binary files a/core/web/html/valid-xhtml10.png and /dev/null differ diff --git a/core/web/html/vcss.gif b/core/web/html/vcss.gif deleted file mode 100644 index 020c75a7..00000000 Binary files a/core/web/html/vcss.gif and /dev/null differ diff --git a/core/web/html/whitebox-horizontal.png b/core/web/html/whitebox-horizontal.png deleted file mode 100644 index 894cf80a..00000000 Binary files a/core/web/html/whitebox-horizontal.png and /dev/null differ diff --git a/core/web/html/whitebox-vertical.png b/core/web/html/whitebox-vertical.png deleted file mode 100644 index 5c4c92ec..00000000 Binary files a/core/web/html/whitebox-vertical.png and /dev/null differ diff --git a/core/web/html/whitebox.png b/core/web/html/whitebox.png deleted file mode 100644 index e5acdb2a..00000000 Binary files a/core/web/html/whitebox.png and /dev/null differ diff --git a/core/web/htp.rsp b/core/web/htp.rsp deleted file mode 100644 index bf79bac5..00000000 --- a/core/web/htp.rsp +++ /dev/null @@ -1 +0,0 @@ -htp/ diff --git a/core/web/htp/body.htt b/core/web/htp/body.htt deleted file mode 100644 index 00649d57..00000000 --- a/core/web/htp/body.htt +++ /dev/null @@ -1,71 +0,0 @@ - - - - <use title> - - - - - - - - - - - - -
-

Valid XHTML 1.0! -

-
- - - - - - - - - diff --git a/core/web/htp/contact.htp b/core/web/htp/contact.htp deleted file mode 100644 index cea23f88..00000000 --- a/core/web/htp/contact.htp +++ /dev/null @@ -1,76 +0,0 @@ - - - - - -

Support and contact information for OpenRocket

- -
- -

Mailing lists

- -

OpenRocket currently has two mailing lists for - intrested users:

- -
-
- OpenRocket-announce -   - (archives) -
-
Announcements of new OpenRocket versions and - developments. This list is moderated.
- -
- OpenRocket-devel -   - (archives) -
-
Discussion related to OpenRocket development, documentation - and upcoming features.
-
- -

You are welcome to join the development mailing list if you are - interested in contributing something to OpenRocket or simply want - hear about and discuss future development. Note that support - requests should be sent to the - support - forums instead!

- -

Unsubscribing from the lists can be performed - in the above links as well. Please do not send unsubscription - requests to the list.

- - -

Support forums

- -

The official support forum for OpenRocket is the - Rocketry - Electronics and Software forum at - The Rocketry Forum.

- -

Please ask any questions on using OpenRocket on that forum, - where others can answer as well and gain knowledge from the - answers.

- -

Contact information

- -

The main developer of OpenRocket is Sampo Niskanen. His contact - information can be found below.

- -

Support requests should be sent to - the support - forums.
- - -

Email:    - sampo.niskanen@iki.fi

- -

WWW:    - http://www.iki.fi/sampo.niskanen/

- - -
-
diff --git a/core/web/htp/documentation.htp b/core/web/htp/documentation.htp deleted file mode 100644 index 1731f3f3..00000000 --- a/core/web/htp/documentation.htp +++ /dev/null @@ -1,82 +0,0 @@ - - - - - -

Documentation for OpenRocket

- -
- -

User documentation

- -

Unfortunately no user's guide currently exists for OpenRocket. - Some documentation is available in the - OpenRocket - wiki pages, including a stub - User's - guide and a section of - frequently - asked questions.

- -

If you would like to help, please extend the documentation!

- - -

Technical documentation

- -

OpenRocket was originally written as the Master's thesis of - Sampo Niskanen at Helsinki University of Technology. This thesis - is being extended and updated as the OpenRocket technical - documentation. Below is the latest technical documentation and - the original Master's thesis.

- -
-

- CC BY-SA - OpenRocket technical documentation (2011-07-18) -    (PDF 1.4MB) -

- -

- CC BY-NC-ND - Development of an Open Source model rocket simulation software (Master's thesis) -    (PDF 1.3MB) -

-
- -

The technical documentation is licensed under a - Creative Commons Attribution-ShareAlike License - while the Master's thesis is licensed under a - Attribution-NonCommercial-NoDerivs - License. -

- - -

Table of contents:

-
    -
  1. 1. Introduction
  2. -
  3. 2. Basics of model rocket flight
  4. -
  5. 3. Aerodynamic properties of model rockets
  6. -
  7. 4. Flight simulation
  8. -
  9. 5. The OpenRocket simulation software
  10. -
  11. 6. Comparison with experimental data
  12. -
  13. 7. Conclusion
  14. -
-
    -
  1. A. Nose cone and transition geometries
  2. -
  3. B. Transonic wave drag of nose cones
  4. -
  5. C. Streamer drag coefficient estimation
  6. -
- - - -

Resources

- -

A list of useful technical rocketry resources is available in - the "Resources" - wiki page, including links to Barrowman's original report and - thesis, extensions for the Barrowman method, experimental rocket - data etc.

- - -
-
diff --git a/core/web/htp/download.htp b/core/web/htp/download.htp deleted file mode 100644 index aed535f1..00000000 --- a/core/web/htp/download.htp +++ /dev/null @@ -1,90 +0,0 @@ - - - - - -

Download OpenRocket

- -
- - - - - -
-

Ready packages

- -

These are packages ready for use and are the recommended - download for normal users. They are pre-packaged with motor - thrust curves from - thrustcurve.org.

- -

OpenRocket requires Java version 6 or - later. The Sun Java Runtime is recommended.

- -

Desktop version

- -

This is the latest version of the desktop version of - OpenRocket. It contains the latest and greatest features, and - runs on any system supporting Java.

- -
- -
-
- Support This Project -
- - - - -

OpenRocket can be started in most graphical environments (including - Windows) by double-clicking the package icon. No installation is - required.

- -

From the command line OpenRocket can be started by - java -jar OpenRocket-.jar

- -

Android version

- -

The Android version allows opening OpenRocket files, viewing - simulations and motors. Later versions will allow running - simulations as well.

- -

The Android version is thanks to the fantastic work by Kevin - Ruland.

- -
- -
-
-

Installation:

-
    -
  1. Go to SettingsApplications and - check Unknown sources.
  2. -
  3. Download OpenRocket-Android-.apk - on your device and accept installation.
  4. - -
-
- -
-
- -

Source code and older versions

- -

Source packages and older versions of - OpenRocket are available in the - SourceForge repository.

- -

Alternatively, the most recent development version can be - obtained from the - SVN - repository. It can be retrieved simply using the command

-
$ svn co https://openrocket.svn.sourceforge.net/svnroot/openrocket/trunk OpenRocket
-

The above URL may be used to connect to the repository with - other Subversion clients as well.

- - -
-
diff --git a/core/web/htp/features.htp b/core/web/htp/features.htp deleted file mode 100644 index 9fc341e4..00000000 --- a/core/web/htp/features.htp +++ /dev/null @@ -1,144 +0,0 @@ - - - - - -

Features of OpenRocket

- -
- -

Current features

- - - -

General

- -
    -
  • Fully cross-platform, written in Java
  • -
  • Fully documented simulation - methods
  • -
  • Open Source, source code available under the - GNU GPL
  • -
- -

User interface

-
    -
  • Easy-to-use user interface for - rocket design
  • -
  • Real-time view of CG and CP position
  • -
  • Real-time flight altitude, velocity and - acceleration information from a continuous simulation - performed in the background
  • -
  • Zoomable schematic view of rocket from the side or rear, - with rotation around the center axis
  • -
- -

Design

- -
    -
  • A multitude of available components to - choose from
  • -
  • Trapezoidal, elliptical - and free-form fins supported
  • -
  • Support for canted fins (roll - stabilization)
  • -
  • Staging and clustering support
  • -
  • Automatic calculation of component mass and CG based on - shape and density
  • -
  • Ability to override mass and CG of - components or stages separately
  • -
- -

Simulation and analysis

- -
    -
  • Full six degree of freedom simulation
  • -
  • Rocket stability computed using extended Barrowman - method
  • -
  • Automatic design optimization — you - can optimize any number of rocket parameters for flight - altitude, maximum velocity or a number of other values
  • -
  • Realistic wind modeling
  • -
  • Analysis of the effect of separate - components on the stability, drag and roll - characteristics of the rocket
  • -
  • Fully configurable plotting, with - various preset configurations
  • -
  • Simulation data can be exported to - CSV - files for further analysis
  • -
  • Simulation listeners allowing custom-made - code to interact with the rocket during flight simulation
  • -
- - -

Planned future features

- -

OpenRocket is under constant work in the free time of the - developers. You can have a sneak preview on what has been - planned by checking the - TODO-file - in the SVN repository.

- -

Below are a few major features that are under consideration:

- -
    -
  • Aerodynamic computation using - CFD - (help needed!)
  • -
  • Better support for supersonic simulation - (help needed!)
  • -
  • 3D view of the rocket design - (help - needed!)
  • -
  • Printing and saving figures, simulation data and designs
  • -
  • Support for ready-made component databases
  • -
  • Customized support for hybrid rocket motors and water - rockets
  • -
  • Importing and plotting actual flight data from altimeters
  • -
  • Rocket flight animation
  • -
  • A "wizard" for creating new rocket designs
  • -
  • More ideas are listed in the - TODO-file!
  • -
- -

If you want to help make OpenRocket the best rocket simulator, - don't hesitate to Get involved!

- -
- - -
-
diff --git a/core/web/htp/getinvolved.htp b/core/web/htp/getinvolved.htp deleted file mode 100644 index 8654be88..00000000 --- a/core/web/htp/getinvolved.htp +++ /dev/null @@ -1,101 +0,0 @@ - - - - - -

Get involved in OpenRocket development

- -
- -

How can I help OpenRocket?

- -

OpenRocket is an Open Source project, meaning that the source - code is freely available and anybody can help make the software - better. The program is mainly developed by Sampo Niskanen in - his free time. Help is very much appreciated. You don't even - need coding skills, as there are other things to do as well.

- -

Below are a few suggestions of areas that would need help. If - you'd like to participate, please - join - the development mailing list and introduce your ideas there.

- - - - -

Java development

- -

Below are a few ideas about what kind of input developers can - provide or features that could be implemented. For more - information see the feature roadmap in the distribution - TODO-file.

- -
    -
  • 3D visualization of the rocket during design and flight - (Help needed!) -
  • -
  • Printing of designs, simulation results, fin planforms - etc
  • -
  • Memory profiling and leakage reduction
  • -
  • Writing RockSim design files
  • -
  • UI enhancements, for example zooming plots etc.
  • -
- -

Aerodynamic computation methods

- -

There is still work to be done in the aerodynamic computation - methods of OpenRocket. At least the following items need - help. I will gladly provide help in creating and even - implementing the computational methods.

- -
    -
  • Simulating rockets at supersonic velocities (drag - coefficient and CG position).
  • -
  • Support for external pods and tube fins
  • -
  • CFD - methods for simulation
  • -
- -

Documentation tasks

- -

Contributions to the - OpenRocket - User's guide are dearly needed. Below are examples of - topics.

- -

(Unfortunately the SourceForge wiki currently does - not support public write access to the wiki. If you'd like to - contribute, please contact me and I - will provide you write access.)

- - -
    -
  • Getting started guide
  • -
  • How to make staged and clustered designs
  • -
  • Using mass/CG overrides for simulation accuracy
  • -
  • Using simulations
  • -
  • Effect of the simulation parameters
  • -
  • Simulation method limitations
  • -
  • Using simulation listeners (including examples)
  • -
- - -

Other

- -
    -
  • Translating OpenRocket to your language
  • -
  • Creating good and interesting example designs that - demonstrate some OpenRocket features.
  • -
  • Hosting a place to share rocket designs with other - enthusiasts.
  • -
  • Giving input and suggestions on how to make OpenRocket - better.
  • -
- -
-
diff --git a/core/web/htp/htp.def b/core/web/htp/htp.def deleted file mode 100644 index 5e6d4bcc..00000000 --- a/core/web/htp/htp.def +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - diff --git a/core/web/htp/htp.rsp b/core/web/htp/htp.rsp deleted file mode 100644 index 81f6beb0..00000000 --- a/core/web/htp/htp.rsp +++ /dev/null @@ -1,8 +0,0 @@ --XML -NOIMGXY -index.htp ../html/index.html -features.htp ../html/features.html -download.htp ../html/download.html -documentation.htp ../html/documentation.html -license.htp ../html/license.html -contact.htp ../html/contact.html -getinvolved.htp ../html/getinvolved.html diff --git a/core/web/htp/index.htp b/core/web/htp/index.htp deleted file mode 100644 index f91ac6b8..00000000 --- a/core/web/htp/index.htp +++ /dev/null @@ -1,65 +0,0 @@ - - - - - -

OpenRocket — an Open Source model rocket simulator

- -
- -

Introduction

- -
- - - - -
- Support This Project -
- -
- -

OpenRocket is a free, fully featured model - rocket simulator that allows you to design and simulate your - rockets before actually building and flying them.

- -

The main features include:

- -
    -
  • Six-degree-of-freedom flight simulation
  • -
  • Automatic design optimization
  • -
  • Realtime simulated altitude, velocity and acceleration display
  • -
  • Staging and clustering support
  • -
  • Cross-platform (Java-based)
  • -
- -

Read more about its features and see screenshots. -

-

OpenRocket is an Open Source project licensed under the - GNU GPL. This means that the - software is free to use for whatever purposes, and the source - code is also available for studying and extending. -

-

OpenRocket needs help to become even better. Implementing - features, writing documentation and creating example designs are - just a few ways of helping. If you are interested in helping - make OpenRocket the best rocket simulator out there, please - Get involved! -

- - -
- - - - -
-
- diff --git a/core/web/htp/license.htp b/core/web/htp/license.htp deleted file mode 100644 index 3835cbb0..00000000 --- a/core/web/htp/license.htp +++ /dev/null @@ -1,722 +0,0 @@ - - - - - -

OpenRocket license

- -
- -

The license text is available also in the simulator under - Help → License and in the file - LICENSE.TXT.

- -
- -
-OpenRocket - A model rocket simulator
-
-Copyright (C) 2007-2012 Sampo Niskanen and others
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 3 of the License, or (at
-your option) any later version.
-
-This program is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License (below) for more details.
-
-
-Additional permission under GNU GPL version 3 section 7:
-
-The licensors grant additional permission to package this Program, or
-any covered work, along with any non-compilable data files (such as
-thrust curves or component databases) and convey the resulting work.
-
-
-------------------------------------------------------------------------
-
-
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-			    Preamble
-
-  The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
-  The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works.  By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.  We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors.  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
-  To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights.  Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received.  You must make sure that they, too, receive
-or can get the source code.  And you must show them these terms so they
-know their rights.
-
-  Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
-  For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software.  For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
-  Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so.  This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software.  The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable.  Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products.  If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
-  Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary.  To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-		       TERMS AND CONDITIONS
-
-  0. Definitions.
-
-  "This License" refers to version 3 of the GNU General Public License.
-
-  "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
- 
-  "The Program" refers to any copyrightable work licensed under this
-License.  Each licensee is addressed as "you".  "Licensees" and
-"recipients" may be individuals or organizations.
-
-  To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy.  The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
-  A "covered work" means either the unmodified Program or a work based
-on the Program.
-
-  To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy.  Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
-  To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies.  Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
-  An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License.  If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
-  1. Source Code.
-
-  The "source code" for a work means the preferred form of the work
-for making modifications to it.  "Object code" means any non-source
-form of a work.
-
-  A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
-  The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form.  A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
-  The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities.  However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work.  For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
-  The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
-  The Corresponding Source for a work in source code form is that
-same work.
-
-  2. Basic Permissions.
-
-  All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met.  This License explicitly affirms your unlimited
-permission to run the unmodified Program.  The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work.  This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
-  You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force.  You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright.  Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
-  Conveying under any other circumstances is permitted solely under
-the conditions stated below.  Sublicensing is not allowed; section 10
-makes it unnecessary.
-
-  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-  No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
-  When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
-  4. Conveying Verbatim Copies.
-
-  You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
-  You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
-  5. Conveying Modified Source Versions.
-
-  You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
-    a) The work must carry prominent notices stating that you modified
-    it, and giving a relevant date.
-
-    b) The work must carry prominent notices stating that it is
-    released under this License and any conditions added under section
-    7.  This requirement modifies the requirement in section 4 to
-    "keep intact all notices".
-
-    c) You must license the entire work, as a whole, under this
-    License to anyone who comes into possession of a copy.  This
-    License will therefore apply, along with any applicable section 7
-    additional terms, to the whole of the work, and all its parts,
-    regardless of how they are packaged.  This License gives no
-    permission to license the work in any other way, but it does not
-    invalidate such permission if you have separately received it.
-
-    d) If the work has interactive user interfaces, each must display
-    Appropriate Legal Notices; however, if the Program has interactive
-    interfaces that do not display Appropriate Legal Notices, your
-    work need not make them do so.
-
-  A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit.  Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
-  6. Conveying Non-Source Forms.
-
-  You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
-    a) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by the
-    Corresponding Source fixed on a durable physical medium
-    customarily used for software interchange.
-
-    b) Convey the object code in, or embodied in, a physical product
-    (including a physical distribution medium), accompanied by a
-    written offer, valid for at least three years and valid for as
-    long as you offer spare parts or customer support for that product
-    model, to give anyone who possesses the object code either (1) a
-    copy of the Corresponding Source for all the software in the
-    product that is covered by this License, on a durable physical
-    medium customarily used for software interchange, for a price no
-    more than your reasonable cost of physically performing this
-    conveying of source, or (2) access to copy the
-    Corresponding Source from a network server at no charge.
-
-    c) Convey individual copies of the object code with a copy of the
-    written offer to provide the Corresponding Source.  This
-    alternative is allowed only occasionally and noncommercially, and
-    only if you received the object code with such an offer, in accord
-    with subsection 6b.
-
-    d) Convey the object code by offering access from a designated
-    place (gratis or for a charge), and offer equivalent access to the
-    Corresponding Source in the same way through the same place at no
-    further charge.  You need not require recipients to copy the
-    Corresponding Source along with the object code.  If the place to
-    copy the object code is a network server, the Corresponding Source
-    may be on a different server (operated by you or a third party)
-    that supports equivalent copying facilities, provided you maintain
-    clear directions next to the object code saying where to find the
-    Corresponding Source.  Regardless of what server hosts the
-    Corresponding Source, you remain obligated to ensure that it is
-    available for as long as needed to satisfy these requirements.
-
-    e) Convey the object code using peer-to-peer transmission, provided
-    you inform other peers where the object code and Corresponding
-    Source of the work are being offered to the general public at no
-    charge under subsection 6d.
-
-  A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
-  A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling.  In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage.  For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product.  A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
-  "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source.  The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
-  If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information.  But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
-  The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed.  Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
-  Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
-  7. Additional Terms.
-
-  "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law.  If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
-  When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it.  (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.)  You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
-  Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
-    a) Disclaiming warranty or limiting liability differently from the
-    terms of sections 15 and 16 of this License; or
-
-    b) Requiring preservation of specified reasonable legal notices or
-    author attributions in that material or in the Appropriate Legal
-    Notices displayed by works containing it; or
-
-    c) Prohibiting misrepresentation of the origin of that material, or
-    requiring that modified versions of such material be marked in
-    reasonable ways as different from the original version; or
-
-    d) Limiting the use for publicity purposes of names of licensors or
-    authors of the material; or
-
-    e) Declining to grant rights under trademark law for use of some
-    trade names, trademarks, or service marks; or
-
-    f) Requiring indemnification of licensors and authors of that
-    material by anyone who conveys the material (or modified versions of
-    it) with contractual assumptions of liability to the recipient, for
-    any liability that these contractual assumptions directly impose on
-    those licensors and authors.
-
-  All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10.  If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term.  If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
-  If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
-  Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
-  8. Termination.
-
-  You may not propagate or modify a covered work except as expressly
-provided under this License.  Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
-  However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
-  Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
-  Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License.  If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
-  9. Acceptance Not Required for Having Copies.
-
-  You are not required to accept this License in order to receive or
-run a copy of the Program.  Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance.  However,
-nothing other than this License grants you permission to propagate or
-modify any covered work.  These actions infringe copyright if you do
-not accept this License.  Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
-  10. Automatic Licensing of Downstream Recipients.
-
-  Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License.  You are not responsible
-for enforcing compliance by third parties with this License.
-
-  An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations.  If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
-  You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License.  For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
-  11. Patents.
-
-  A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based.  The
-work thus licensed is called the contributor's "contributor version".
-
-  A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version.  For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
-  Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
-  In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement).  To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
-  If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients.  "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-  
-  If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
-  A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License.  You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
-  Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
-  12. No Surrender of Others' Freedom.
-
-  If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all.  For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
-  13. Use with the GNU Affero General Public License.
-
-  Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work.  The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
-  14. Revised Versions of this License.
-
-  The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-  Each version is given a distinguishing version number.  If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation.  If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
-  If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
-  Later license versions may give you additional or different
-permissions.  However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
-  15. Disclaimer of Warranty.
-
-  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. Limitation of Liability.
-
-  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
-  17. Interpretation of Sections 15 and 16.
-
-  If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
-		     END OF TERMS AND CONDITIONS
-
-	    How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software: you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation, either version 3 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
-  If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
-    <program>  Copyright (C) <year>  <name of author>
-    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
-  You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
-  The GNU General Public License does not permit incorporating your program
-into proprietary programs.  If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.  But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
-    
- -
- - -
-
diff --git a/core/web/htp/news.htp b/core/web/htp/news.htp deleted file mode 100644 index 538c9136..00000000 --- a/core/web/htp/news.htp +++ /dev/null @@ -1,215 +0,0 @@ - -
- - -

- -

News

-
- - - -

16.9.2012: Version 12.09 is - released!

- -

This version contains a huge number of new features by many contributors:

- -
    -
  • 3D rocket design view
  • -
  • Component Presets
  • -
  • Custom expressions in simulations
  • -
  • Printing for centering ring and clustered centering ring components
  • -
  • Support simple arthmatic in dimension entry
  • -
  • Support deploying recovery device at stage separation
  • -
  • Support for fractional inches (1/64) for unit length
  • -
  • Added preference for windspeed units separately
  • -
  • Added "most recently used files" in File Menu
  • -
  • Improved printed accurracy in fin marking guide
  • -
  • Calibration rulers added to printed templates
  • -
  • Translations in Czech and Polish, numerous updates
  • -
- - -

10.3.2012: Version 12.03 for desktop - and Android is released!

- -

In this release the version numbering scheme has been changed. - From now on the version number is YY.MM indicating the - year and month of the release. Bug fix releases are indicated by - an added ".1".

- -

This also marks the first release for Android devices. In this - first release you can open files and examine existing simulations, - stability data and motor files. The Android port is thanks to - work by Kevin Ruland.

- -

Enhancements in the desktop version include saving designs in RKT - format thanks to Doug Pedrick, freeform fin set import form images - by Jason Blood, configurable stage separation - events, guided help tours and displaying the computed motor - designation class. The application has also been translated to - Italian by Mauro Biasutti and Russian by the Sky Dart Team.

- - - - - -

24.11.2011: Version 1.1.9 is - released!

- -

For this version Richard Graham has implemented geodetic - computation methods, which take into account the curvature of the - Earth and the coriolis effect. The computation method is selected - by the Geodetic calculations option in the simulation - options. It's not (yet) a full spherical computation model, but - should be accurate enough for almost all sub-orbital needs.

- -

Doug Pedrick has also enhanced the printing system with the - ability to print fin positioning guides, transition templates and - nose cone profiles. Other smaller enhancements and bug fixes are - also included.

- -

25.8.2011: Version 1.1.8 is - released!

- -

This release contains bug fixes to the optimization methods. - It also contains a workaround to a JRE bug that prevents running - OpenRocket on some builds of Java 7.

- -

The web pages have also been somewhat updated and Boris du Reau has - created a separate site - for coordinating the localization efforts for OpenRocket.

- - -

12.8.2011: Version 1.1.7 is - released!

- -

This release includes automatic rocket design optimization - support (AnalyzeRocket optimization). - You can optimize any amount of rocket parameters for apogee - altitude, maximum velocity or a number of different values.

- -

While the automatic optimization is a powerful tool, it is very - easy to optimize against particulars of the simulation methods, - instead of true physical phenomena. Always keep common sense at - hand and take the results with a grain of salt.

- -

22.7.2011: Version 1.1.6 is - released!

- -

This release includes initial localization support and - translations to French, German and Spanish. This is thanks to the - great work of Boris du Reau, and the teams from Tripoli France, - Tripoli Spain and ERIG e.V. If you prefer to use some other - language than the system default, you can select the language on - the "Options" tab of the preferences dialog.

- -

The release also includes design scaling support and numerous bug - fixes.

- -

10.6.2011: Version 1.1.5 is - released!

- -

This release includes updates to the printing system which fixes - printing on Windows.

- -

5.3.2011: Version 1.1.4 is - released!

- -

This release includes initial printing support, thanks to Doug - Pedrick. Printing still has a few issues on some platforms. - Various bugs have also been fixed.

- -

6.10.2010: Version 1.1.3 is - released!

- -

This release includes support for moving and copying components - in the component tree using drag-and-drop. Use normal DnD for - moving, and control-drag for copy. This release also fixes a - severe bug in the undo system.

- -

7.9.2010: A bug-fix version 1.1.2 is - released!

- -

This release fixes a severe bug in 1.1.1 that prevented adding stages - to rocket designs. Users are recommended to upgrade.

- -

3.9.2010: Version 1.1.1 is - released!

- -

For this release a major part of the simulator code has been - rewritten for better flexibility in future development. It also - includes a vastly improved thrust curve selection dialog, the - possibility to loading user-defined thrust curves and better - startup times than previous releases.

- -

Simulation listeners written for older versions of OpenRocket - are not compatible with this release.

- -

21.3.2010: Version 1.1.0 is - released!

- -

This release includes the first support for loading RockSim - rocket design files (.RKT), thanks to contributions by Doug - Pedrick. It's also the kick-off of the 1.1 development branch of - OpenRocket.

- -

10.3.2010: Version 1.0.0 is - released!

- -

This release includes several hundred new thrustcurves from - thrustcurve.org and some - bug fixes. It is also a stable milestone, after which development - on larger features will be started in a 1.1 branch. Look out - for it! :-)

- -

17.2.2010: Version 0.9.6 is - released!

- -

This release updates the aerodynamic calculation methods to be - more in line with the Barrowman method and enhances the simulation - time step selection, in addition to fixing numerous bugs.

- -

28.11.2009: Version 0.9.5 is - released!

- -

This release fixes a serious bug in 0.9.4 that - prevented adding a tube coupler and centering ring to the same - body tube, in addition to a few smaller additions. Users of - 0.9.4 should upgrade immediately!

- -

24.11.2009: Version 0.9.4 is - released!

- -

This version adds support for through-the-wall fin tabs, - attaching components to coupler tubes, material editing, automatic - update checking, in addition to fixing numerous bugs.

- -

1.9.2009: Version 0.9.3 is - released!

- -

This version includes lots of bug fixes and new features including - data exporting, showing flight events in plots, example rocket designs, - splitting clustered inner tubes and automated bug reporting.

- -

13.7.2009: Version 0.9.2 is - released!

- -

This version includes bug fixes for imperial unit - conversions and UI improvements for motor selection. - All users of imperial units should upgrade!

- -

9.6.2009: The - Master's thesis for which OpenRocket - was written for is now available!

- -

At the same time version 0.9.1 was - released. This release fixes various - file handling bugs and adds small UI enhancements.

- -

24.5.2009: First version 0.9.0 - released!

- -
- -
diff --git a/core/web/update-html.sh b/core/web/update-html.sh deleted file mode 100755 index ea98bd71..00000000 --- a/core/web/update-html.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -htp @ || exit 1 -scp html/*.html plaa,openrocket@web.sourceforge.net:htdocs/ diff --git a/debian/changelog b/debian/changelog index 1e2c8d12..d5c8193e 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,12 +1,19 @@ +openrocket (13.05-1) unstable; urgency=low + + * new upstream version + * re-package as an installer to make tracking upstream tractable + + -- Bdale Garbee Sun, 18 Aug 2013 00:12:58 +0200 + openrocket (12.09-1) unstable; urgency=low - * new upstream versions + * new upstream version -- Bdale Garbee Sun, 16 Sep 2012 16:30:14 -0600 openrocket (12.03-1) unstable; urgency=low - * new upstream versions + * new upstream version -- Bdale Garbee Sun, 18 Mar 2012 23:58:34 +0100 diff --git a/debian/compat b/debian/compat index 7f8f011e..ec635144 100644 --- a/debian/compat +++ b/debian/compat @@ -1 +1 @@ -7 +9 diff --git a/debian/control b/debian/control index 27662e7b..9a631ebf 100644 --- a/debian/control +++ b/debian/control @@ -2,15 +2,15 @@ Source: openrocket Section: science Priority: optional Maintainer: Bdale Garbee -Build-Depends: debhelper (>= 7.0.50~), openjdk-6-jdk, ant, ant-optional, libjcommon-java, libjfreechart-java, libmiglayout-java, junit4, libitext5-java, netpbm -Standards-Version: 3.9.3 +Build-Depends: debhelper (>= 9) +Standards-Version: 3.9.4 Homepage: http://openrocket.sourceforge.net/ Vcs-Git: git://git.gag.com/debian/openrocket Vcs-Browser: http://git.gag.com/?p=debian/openrocket Package: openrocket Architecture: all -Depends: ${shlibs:Depends}, ${misc:Depends}, openjdk-6-jre | sun-java6-jre, libjcommon-java, libjfreechart-java, libmiglayout-java, libitext5-java +Depends: wget, default-jre, ${misc:Depends}, ${shlibs:Depends} Description: Model Rocket Simulator OpenRocket is a free, fully featured model rocket simulator that allows you to design and simulate your rockets before actually building and @@ -19,3 +19,6 @@ Description: Model Rocket Simulator OpenRocket features a full six-degree-of-freedom simulation, realistic wind modeling, a multitude of different components including free-form and canted fins, clustering and staging. + . + This package therefore downloads the pre-built OpenRocket .jar file from + the upstream site and installs it. diff --git a/debian/copyright b/debian/copyright index 1b0af634..207046bf 100644 --- a/debian/copyright +++ b/debian/copyright @@ -1,35 +1,25 @@ -This work was packaged for Debian by: - - Bdale Garbee on Sat, 13 Mar 2010 15:25:12 -0700 - -It was downloaded from: - - http://openrocket.sourceforge.net/ - -Upstream Author: - - Sampo Niskanen +This package was constructed by Bdale Garbee on +Sun, 18 Aug 2013 00:38:27 +0200, starting with code from the +flashplugin-nonfree installer maintained by Bart Martens . Copyright: - Copyright (C) 2007-2011 Sampo Niskanen + Copyright (C) 2006-2012 Bart Martens + Copyright (C) 2013 Bdale Garbee License: - GPL version 3 with additional permission under section 7: - - The licensors grant additional permission to package this Program, or - any covered work, along with any non-compilable data files (such as - thrust curves or component databases) and convey the resulting work. - -The Debian packaging is: + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 as + published by the Free Software Foundation. - Copyright (C) 2010 Bdale Garbee + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -and is also licensed under the GPL version 3, -see "/usr/share/common-licenses/GPL-3". + You should have received a copy of the GNU General Public License + along with this program. If not, see . -The source distribution and binary packages also contain rocket motor -performance data files from thrustcurve.org. These carry various copyright -assertions, but all are made available for public use with no distribution -restrictions. +On Debian systems, the complete text of the GNU General Public License +version 2 can be found in `/usr/share/common-licenses/GPL-2'. diff --git a/debian/dirs b/debian/dirs index 93fa6610..5b9eca5c 100644 --- a/debian/dirs +++ b/debian/dirs @@ -1,4 +1,2 @@ +usr/lib/openrocket usr/bin -usr/share/applications -usr/share/java -usr/share/pixmaps diff --git a/debian/docs b/debian/docs deleted file mode 100644 index 06ad6c08..00000000 --- a/debian/docs +++ /dev/null @@ -1,3 +0,0 @@ -core/fileformat.txt -core/README.TXT -core/TODO diff --git a/debian/gbp.conf b/debian/gbp.conf deleted file mode 100644 index 15b1cbac..00000000 --- a/debian/gbp.conf +++ /dev/null @@ -1,46 +0,0 @@ -# Configuration file for git-buildpackage and friends - -[DEFAULT] -# the default build command: -#builder = debuild -i\.git/ -I.git -# the default clean command: -#cleaner = debuild clean -# the default branch for upstream sources: -upstream-branch = upstream -# the default branch for the debian patch: -debian-branch = debian -# the default tag formats used: -#upstream-tag = upstream/%(version)s -#debian-tag = debian/%(version)s -# use pristine-tar: -pristine-tar = True - -# Options only affecting git-buildpackage -[git-buildpackage] -#upstream-branch = dfsgclean -# uncomment this to automatically GPG sign tags -#sign-tags = True -# keyid to GPG sign tags with -#keyid = 0xdeadbeef -# push to a remote repository after a successful tag: -posttag = git push --mirror -# use this for more svn-buildpackage like behaviour: -export-dir = ../build-area/openrocket/ -#tarball-dir = ../tarballs/ - -# Options only affecting git-import-orig -[git-import-orig] -#upstream-branch = newupstream -#debian-branch = dfsgclean -#filter = .svn - -# Options only affecting git-import-dsc -[git-import-dsc] -#upstream-branch = svn-upstream -#filter = [ 'CVS', '.cvsignore' ] - -# Options only affecting git-dch -[git-dch] -#git-log = --no-merges -#snapshot-number = snapshot + 1 - diff --git a/debian/install b/debian/install new file mode 100644 index 00000000..f6d10bd0 --- /dev/null +++ b/debian/install @@ -0,0 +1,3 @@ +update-openrocket usr/sbin/ +debian/lintian/openrocket usr/share/lintian/overrides/ +debian/reportbug/script usr/share/bug/openrocket/ diff --git a/debian/lintian/openrocket b/debian/lintian/openrocket new file mode 100644 index 00000000..769d3c4e --- /dev/null +++ b/debian/lintian/openrocket @@ -0,0 +1 @@ +openrocket: package-contains-empty-directory usr/lib/openrocket/ diff --git a/debian/manpages b/debian/manpages new file mode 100644 index 00000000..7acecef4 --- /dev/null +++ b/debian/manpages @@ -0,0 +1 @@ +debian/update-flashplugin-nonfree.8 diff --git a/debian/menu b/debian/menu deleted file mode 100644 index 46fa39af..00000000 --- a/debian/menu +++ /dev/null @@ -1,6 +0,0 @@ -?package(openrocket): \ - needs="X11" \ - section="Applications/Editors" \ - title="openrocket" \ - command="/usr/bin/openrocket" \ - icon="/usr/share/pixmaps/openrocket.png" diff --git a/debian/openrocket.1 b/debian/openrocket.1 deleted file mode 100644 index 02ebce51..00000000 --- a/debian/openrocket.1 +++ /dev/null @@ -1,38 +0,0 @@ -.\" Hey, EMACS: -*- nroff -*- -.\" First parameter, NAME, should be all caps -.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection -.\" other parameters are allowed: see man(7), man(1) -.TH OPENROCKET 1 "March 13, 2010" -.\" Please adjust this date whenever revising the manpage. -.\" -.\" Some roff macros, for reference: -.\" .nh disable hyphenation -.\" .hy enable hyphenation -.\" .ad l left justify -.\" .ad b justify to both left and right margins -.\" .nf disable filling -.\" .fi enable filling -.\" .br insert line break -.\" .sp insert n+1 empty lines -.\" for manpage-specific macros, see man(7) -.SH NAME -openrocket \- model rocket design and simulation -.SH SYNOPSIS -.B openrocket -.SH DESCRIPTION -\fBopenrocket\fP is a free, fully featured model rocket simulator that allows -you to design and simulate your rockets before actually building and -flying them. - -\fBopenrocket\fP features a full six-degree-of-freedom simulation, realistic -wind modeling, a multitude of different components including free-form -and canted fins, clustering and staging. - -.SH SEE ALSO -This program is documented fully at -http://openrocket.sourceforge.net/documentation.html -.SH AUTHOR -openrocket was written by Sampo Niskanen. -.PP -This manual page was written by Bdale Garbee -for the Debian project (and may be used by others). diff --git a/debian/openrocket.desktop b/debian/openrocket.desktop deleted file mode 100644 index bbbc7e80..00000000 --- a/debian/openrocket.desktop +++ /dev/null @@ -1,10 +0,0 @@ -[Desktop Entry] -Type=Application -Name=OpenRocket -GenericName=Rocket Design and Simulation -Comment=Design and simulate model rockets -Icon=/usr/share/pixmaps/openrocket.xpm -Exec=/usr/bin/openrocket %f -Terminal=false -MimeType=text/plain; -Categories=Development;Science; diff --git a/debian/patches/debian-build.source.diff b/debian/patches/debian-build.source.diff deleted file mode 100644 index cd650675..00000000 --- a/debian/patches/debian-build.source.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/core/resources/build.properties b/core/resources/build.properties -index d12cc3a..4897a42 100644 ---- a/core/resources/build.properties -+++ b/core/resources/build.properties -@@ -8,9 +8,9 @@ build.version=12.03 - # distribution (Debian, Fedora etc.), this should be changed appropriately! - # This is included in bug reports to identify the source of the software. - --build.source=default -+build.source=Debian - - - # Whether checking for updates is enabled by default. - --build.checkupdates=true -+build.checkupdates=false diff --git a/debian/patches/series b/debian/patches/series deleted file mode 100644 index 2a882d49..00000000 --- a/debian/patches/series +++ /dev/null @@ -1,3 +0,0 @@ -debian-build.source.diff -use-system-libs.diff -skip-unittest.diff diff --git a/debian/patches/skip-unittest.diff b/debian/patches/skip-unittest.diff deleted file mode 100644 index 212500f8..00000000 --- a/debian/patches/skip-unittest.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/core/build.xml b/core/build.xml -index 30f62d2..eab61f8 100644 ---- a/core/build.xml -+++ b/core/build.xml -@@ -114,7 +114,7 @@ - - - -- -+ - - - diff --git a/debian/patches/use-system-libs.diff b/debian/patches/use-system-libs.diff deleted file mode 100644 index 0ea303c2..00000000 --- a/debian/patches/use-system-libs.diff +++ /dev/null @@ -1,64 +0,0 @@ -diff --git a/core/build.xml b/core/build.xml -index 0e57a6b..0a3c045 100644 ---- a/core/build.xml -+++ b/core/build.xml -@@ -13,7 +13,6 @@ - - - -- - - - -@@ -27,7 +26,12 @@ - - - -- -+ -+ -+ -+ -+ -+ - - - -@@ -36,7 +40,7 @@ - - - -- -+ - - - -@@ -68,11 +72,8 @@ - - - -+ - -- -- -- -- - - - -@@ -88,7 +89,7 @@ - - - -- -+ - - - -@@ -212,4 +213,4 @@ ${nonascii} - - - -- -\ No newline at end of file -+ diff --git a/debian/postinst b/debian/postinst new file mode 100644 index 00000000..e530d130 --- /dev/null +++ b/debian/postinst @@ -0,0 +1,23 @@ +#!/bin/sh + +set -e + +case "$1" in + configure) + update-openrocket --install --fast || true + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 + + diff --git a/debian/postrm b/debian/postrm new file mode 100644 index 00000000..c297c6fc --- /dev/null +++ b/debian/postrm @@ -0,0 +1,13 @@ +#!/bin/sh + +set -e + +if [ "$1" = "purge" ] +then + rm -rf /var/cache/openrocket/* +fi + +#DEBHELPER# + +exit 0 + diff --git a/debian/prerm b/debian/prerm new file mode 100644 index 00000000..18d489ab --- /dev/null +++ b/debian/prerm @@ -0,0 +1,23 @@ +#!/bin/sh + +set -e + +case "$1" in + remove|upgrade|deconfigure) + update-openrocket --uninstall || true + ;; + + failed-upgrade) + ;; + + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 + + diff --git a/debian/reportbug/script b/debian/reportbug/script new file mode 100755 index 00000000..d28ec87a --- /dev/null +++ b/debian/reportbug/script @@ -0,0 +1,22 @@ +#!/bin/sh + +set +e + +PATH=/usr/sbin:/usr/bin:/sbin:/bin + +take_a_peek() { + + cat /etc/debian_version 2>&1 | sed -e "s,^,Debian version: ," + + dpkg --print-architecture 2>&1 | sed -e "s,^,Architecture: ," + + dpkg-query -W -f='${Version}\n' openrocket 2>&1 | sed -e "s,^,Package version: ," + + unzip -p /usr/lib/openrocket/*.jar ReleaseNotes | head -1 | awk '{ print "Installed OpenRocket version: ",$2 }' + + echo "MD5 checksums:" + md5sum /usr/lib/openrocket/*.jar 2>&1 | sed -e "s,^,\t," + +} +take_a_peek >&3 2>&1 + diff --git a/debian/rules b/debian/rules index 4b02b074..553d9b00 100755 --- a/debian/rules +++ b/debian/rules @@ -1,33 +1,7 @@ #!/usr/bin/make -f -# -*- makefile -*- -# Sample debian/rules that uses debhelper. -# This file was originally written by Joey Hess and Craig Small. -# As a special exception, when this file is copied by dh-make into a -# dh-make output file, you may use that output file without restriction. -# This special exception was added by Craig Small in version 0.37 of dh-make. -# Uncomment this to turn on verbose mode. -#export DH_VERBOSE=1 +export DH_VERBOSE=1 %: - dh $@ + dh $@ -override_dh_auto_build: - ant -f core/build.xml dist-bin - -override_dh_auto_install: - cp core/build/jar/* `pwd`/debian/openrocket/usr/share/java/ - printf '#!/bin/sh\nexec java -jar /usr/share/java/%s "$$@"\n' \ - "`/bin/ls core/build/jar`" > \ - `pwd`/debian/openrocket/usr/bin/openrocket - -override_dh_installman: - dh_installman debian/openrocket.1 - -override_dh_install: - install -o root -g root -m 644 core/resources/pix/icon/icon-032.png \ - debian/openrocket/usr/share/pixmaps/openrocket.png - pngtopnm < core/resources/pix/icon/icon-032.png | ppmtoxpm > \ - debian/openrocket/usr/share/pixmaps/openrocket.xpm - install -o root -g root -m 644 debian/openrocket.desktop \ - debian/openrocket/usr/share/applications diff --git a/debian/source/format b/debian/source/format index 163aaf8d..89ae9db8 100644 --- a/debian/source/format +++ b/debian/source/format @@ -1 +1 @@ -3.0 (quilt) +3.0 (native) diff --git a/debian/update-openrocket.8 b/debian/update-openrocket.8 new file mode 100644 index 00000000..5ad40f69 --- /dev/null +++ b/debian/update-openrocket.8 @@ -0,0 +1,41 @@ +.TH UPDATE-OPENROCKET 8 + +.SH NAME +update-openrocket \- program to get the newest OpenRocket + +.SH SYNOPSIS +.B update-openrocket +.RI --install +.br +.B update-openrocket +.RI --uninstall + +.SH DESCRIPTION +The program +.B update-openrocket +takes care of +downloading and installing the latest version of OpenRocket from SourceForge. +.PP +The program +.B update-openrocket +is used in the +.B postinst +and +.B prerm +scripts of the Debian package, +but this program can also be run manually by root. + +.SH OPTIONS +.TP +.B \-\-install +To install OpenRocket. +.TP +.B \-\-uninstall +To remove OpenRocket. +.TP +.B \-\-verbose +Produce detailed information about what's happening. +.TP +.B \-\-quiet +Produce no informational output. + diff --git a/update-openrocket b/update-openrocket new file mode 100755 index 00000000..53850fba --- /dev/null +++ b/update-openrocket @@ -0,0 +1,221 @@ +#!/bin/sh + +# Copyright (C) 2006-2012 Bart Martens +# Copyright (C) 2013 Bdale Garbee +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +set -e + +return_0() { + return 0 +} + +trap "return_0" 0 + +die_hard() { + echo "ERROR: $1" >&2 + exit 1 +} + +[ `whoami` = "root" ] || die_hard "must be root" + +show_usage() { + echo "Usage:" + echo " update-openrocket --install" + echo " update-openrocket --uninstall" + echo " update-openrocket --status" + echo "Additional options:" + echo " --verbose" + echo " --quiet" + exit 1 +} + +getopt_temp=`getopt -o iusfvq --long install,uninstall,status,fast,verbose,quiet -n 'update-openrocket' -- "$@"` || show_usage +eval set -- "$getopt_temp" || show_usage + +ACTION=none +fast=no +verbose=no +quiet=no + +while [ true ] +do + case "$1" in + -i|--install) + ACTION="--install" + shift + ;; + -u|--uninstall) + ACTION="--uninstall" + shift + ;; + -s|--status) + ACTION="--status" + shift + ;; + -f|--fast) + fast=yes + shift + ;; + -v|--verbose) + verbose=yes + shift + ;; + -q|--quiet) + quiet=yes + shift + ;; + --) + shift + break + ;; + *) + echo "Internal error!" + exit 1 + ;; + esac +done + +[ "$ACTION" != "none" -a $# -eq 0 ] || show_usage +[ "$quiet" != "yes" ] || verbose=no + +[ "$verbose" != "yes" ] || echo "options : $getopt_temp" + +UNPACKDIR=`mktemp -d /tmp/openrocket.XXXXXXXXXX` || die_hard "mktemp failed" +echo "$UNPACKDIR" | grep -q "^/tmp/openrocket\." || die_hard "paranoia" +cd "$UNPACKDIR" || die_hard "cd failed" + +[ "$verbose" != "yes" ] || echo "temporary directory: $UNPACKDIR" + +do_cleanup() { + [ "$verbose" != "yes" ] || echo "cleaning up temporary directory $UNPACKDIR ..." + cd / + echo "$UNPACKDIR" | grep -q "^/tmp/openrocket\." || die_hard "paranoia" + rm -rf "$UNPACKDIR" +} + +die_hard_with_a_cleanup() { + return_0 + do_cleanup + die_hard "$1" +} + +trap "die_hard_with_a_cleanup interrupted" INT + +cachedir=/var/cache/openrocket + +wgetquiet=' -q ' +wgetfast='-t 3 -T 15 ' +wgetalways=' -nd -P . ' +wgetprogress=' -v --progress=dot:default ' + +get_installed_version() { + + installed=`unzip -p /usr/lib/openrocket/*.jar ReleaseNotes | head -1 | awk '{ print $2 }'` +} + +get_download_url() { + url=`wget -qO - http://openrocket.sourceforge.net | grep https | grep download | awk -F\" '{ print $4 }'` +} + +get_upstream_version() { + get_download_url + upstream=`echo $url | awk -F/ '{ print $8 }'` +} + +case "$ACTION" in + + --install) + [ "$verbose" != "yes" ] || echo "selected action = $ACTION" + + get_installed_version + [ "$verbose" != "yes" ] || echo "installed version = $installed" + + get_upstream_version + [ "$verbose" != "yes" ] || echo "upstream version = $upstream" + + if [ "$installed" != "" -a "$upstream" != "" -a "$installed" = "$upstream" ] + then + + [ "$verbose" != "yes" ] || echo "upstream version $upstream is already installed" + + else + + wgetoptions="$wgetquiet $wgetalways" + [ "$verbose" != "yes" ] || wgetoptions="$wgetalways $wgetprogress" + [ "$fast" != "yes" ] || wgetoptions="$wgetoptions $wgetfast" + [ "$verbose" != "yes" ] || echo "wgetoptions=$wgetoptions" + + [ "$verbose" != "yes" ] || echo "downloading $url..." + + HOME=/root \ + wget $wgetoptions $url \ + || die_hard_with_a_cleanup "wget failed to download $downloadurl" + + targetdir=/usr/lib/openrocket + + [ "$verbose" != "yes" ] || echo "removing old .jar files from $targetdir ..." + rm -f $targetdir/*.jar + + [ "$verbose" != "yes" ] || echo "moving download to $targetdir ..." + mv -f download $targetdir/OpenRocket-$upstream.jar + + [ "$verbose" != "yes" ] || ( get_installed_version && echo "create /usr/bin/openrocket wrapper" ) + + echo "#!/bin/sh" > /usr/bin/openrocket + echo "exec java -jar /usr/lib/openrocket/OpenRocket-$upstream.jar \"\$@\"" >> /usr/bin/openrocket + + [ "$verbose" != "yes" ] || ( get_installed_version && echo "OpenRocket version: $installed" ) + + fi # end if installed != upstream + + [ "$verbose" != "yes" ] || echo "end of action $ACTION" + + ;; + + --uninstall) + [ "$verbose" != "yes" ] || echo "selected action = $ACTION" + + [ "$verbose" != "yes" ] || echo "removing files ..." + rm -f /usr/lib/openrocket/*.jar + + [ "$verbose" != "yes" ] || echo "end of action $ACTION" + + ;; + + --status) + [ "$verbose" != "yes" ] || echo "selected action = $ACTION" + + get_installed_version + echo "OpenRocket version installed on this system : $installed" + get_upstream_version + echo "OpenRocket version available on upstream site: $upstream" + + [ "$verbose" != "yes" ] || echo "end of action $ACTION" + + ;; + + *) + + do_cleanup + show_usage + + ;; + +esac + +do_cleanup + +[ "$verbose" != "yes" ] || echo "end of update-openrocket" +