From: Bdale Garbee Date: Sun, 16 Sep 2012 22:26:50 +0000 (-0600) Subject: Merge commit '42b2e5ca519766e37ce6941ba4faecc9691cc403' into upstream X-Git-Tag: upstream/12.09 X-Git-Url: https://git.gag.com/?a=commitdiff_plain;h=9349577cdfdff682b2aabd6daa24fdc3a7449b58;hp=30ba0a882f0c061176ba14dbf86d3d6fad096c02;p=debian%2Fopenrocket Merge commit '42b2e5ca519766e37ce6941ba4faecc9691cc403' into upstream Conflicts: android/libs/android-support-v4.jar --- diff --git a/android-libraries/ActionBarSherlock/.classpath b/android-libraries/ActionBarSherlock/.classpath new file mode 100644 index 00000000..8531be10 --- /dev/null +++ b/android-libraries/ActionBarSherlock/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/.project b/android-libraries/ActionBarSherlock/.project new file mode 100644 index 00000000..cbcf5a22 --- /dev/null +++ b/android-libraries/ActionBarSherlock/.project @@ -0,0 +1,33 @@ + + + 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 new file mode 100644 index 00000000..c4a75f32 --- /dev/null +++ b/android-libraries/ActionBarSherlock/AndroidManifest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/android-libraries/ActionBarSherlock/bin/actionbarsherlock.jar b/android-libraries/ActionBarSherlock/bin/actionbarsherlock.jar new file mode 100644 index 00000000..02f36678 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/actionbarsherlock.jar 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 new file mode 100644 index 00000000..07a0de98 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$Implementation.class 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 new file mode 100644 index 00000000..ba2cfcab Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeFinishedListener.class 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 new file mode 100644 index 00000000..3ccc3b16 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnActionModeStartedListener.class 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 new file mode 100644 index 00000000..d0ffc34a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreateOptionsMenuListener.class 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 new file mode 100644 index 00000000..7bf337c5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnCreatePanelMenuListener.class 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 new file mode 100644 index 00000000..03609bbb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnMenuItemSelectedListener.class 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 new file mode 100644 index 00000000..4076b48e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnOptionsItemSelectedListener.class 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 new file mode 100644 index 00000000..b9704c8e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPrepareOptionsMenuListener.class 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 new file mode 100644 index 00000000..4e022428 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock$OnPreparePanelListener.class differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock.class new file mode 100644 index 00000000..3e4437f8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/ActionBarSherlock.class differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/BuildConfig.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/BuildConfig.class new file mode 100644 index 00000000..f3ea991b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/BuildConfig.class 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 new file mode 100644 index 00000000..79d19d6d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$attr.class 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 new file mode 100644 index 00000000..a9853b12 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$bool.class 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 new file mode 100644 index 00000000..92c994f9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$color.class 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 new file mode 100644 index 00000000..1423fa8c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$dimen.class 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 new file mode 100644 index 00000000..d1d77adb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$drawable.class 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 new file mode 100644 index 00000000..cb66e602 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$id.class 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 new file mode 100644 index 00000000..2a1eb05f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$integer.class 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 new file mode 100644 index 00000000..2e28b63a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$layout.class 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 new file mode 100644 index 00000000..cf862a46 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$string.class 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 new file mode 100644 index 00000000..b8c2a02a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$style.class 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 new file mode 100644 index 00000000..ce1bf2ac Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R$styleable.class differ diff --git a/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R.class b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R.class new file mode 100644 index 00000000..a9c24203 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/R.class 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 new file mode 100644 index 00000000..19f2d713 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$LayoutParams.class 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 new file mode 100644 index 00000000..377c6cbd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnMenuVisibilityListener.class 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 new file mode 100644 index 00000000..e7631ef1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$OnNavigationListener.class 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 new file mode 100644 index 00000000..2c612f7c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$Tab.class 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 new file mode 100644 index 00000000..d3c82802 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar$TabListener.class 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 new file mode 100644 index 00000000..95cae968 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/ActionBar.class 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 new file mode 100644 index 00000000..0e5cc235 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockActivity.class 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 new file mode 100644 index 00000000..b235aed1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockDialogFragment.class 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 new file mode 100644 index 00000000..3e60b010 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockExpandableListActivity.class 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 new file mode 100644 index 00000000..5fe7b56e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragment.class 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 new file mode 100644 index 00000000..e7f20aa5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockFragmentActivity.class 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 new file mode 100644 index 00000000..ccea5880 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListActivity.class 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 new file mode 100644 index 00000000..20d394d4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockListFragment.class 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 new file mode 100644 index 00000000..d8af5912 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/app/SherlockPreferenceActivity.class 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 new file mode 100644 index 00000000..40b3c68d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$1.class 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 new file mode 100644 index 00000000..2015aba0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat$ActionModeCallbackWrapper.class 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 new file mode 100644 index 00000000..1d77c593 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockCompat.class 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 new file mode 100644 index 00000000..e0514eb7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeCallbackWrapper.class 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 new file mode 100644 index 00000000..85099923 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative$ActionModeWrapper.class 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 new file mode 100644 index 00000000..4180bec1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ActionBarSherlockNative.class 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 new file mode 100644 index 00000000..453d4a23 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/ResourcesCompat.class 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 new file mode 100644 index 00000000..2869fb12 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$1.class 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 new file mode 100644 index 00000000..ceab0c41 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$2.class 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 new file mode 100644 index 00000000..a49e0510 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$ActionModeImpl.class 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 new file mode 100644 index 00000000..f0947b4b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl$TabImpl.class 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 new file mode 100644 index 00000000..eba5fc17 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarImpl.class 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 new file mode 100644 index 00000000..0ce995af Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper$TabWrapper.class 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 new file mode 100644 index 00000000..686d2bb6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/app/ActionBarWrapper.class 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 new file mode 100644 index 00000000..e47ad311 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator$AnimatorListener.class 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 new file mode 100644 index 00000000..281a4520 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.class 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 new file mode 100644 index 00000000..ae4b8657 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.class 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 new file mode 100644 index 00000000..aaedb90e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$1.class 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 new file mode 100644 index 00000000..d144adcb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$AnimatorSetListener.class 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 new file mode 100644 index 00000000..5cbbc681 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Builder.class 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 new file mode 100644 index 00000000..5e076406 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Dependency.class 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 new file mode 100644 index 00000000..9f09b675 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$DependencyListener.class 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 new file mode 100644 index 00000000..f94b2b61 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet$Node.class 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 new file mode 100644 index 00000000..7ffd50ff Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.class 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 new file mode 100644 index 00000000..2d950bc3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.class 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 new file mode 100644 index 00000000..b3f70f87 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.class 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 new file mode 100644 index 00000000..515af5da Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.class 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 new file mode 100644 index 00000000..86bf0f67 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.class 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 new file mode 100644 index 00000000..56d147a7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$FloatKeyframe.class 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 new file mode 100644 index 00000000..aa36b75a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$IntKeyframe.class 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 new file mode 100644 index 00000000..69995146 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe$ObjectKeyframe.class 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 new file mode 100644 index 00000000..168f790d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.class 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 new file mode 100644 index 00000000..58317c43 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.class 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 new file mode 100644 index 00000000..32cefbfd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.class 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 new file mode 100644 index 00000000..be6568f8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$FloatPropertyValuesHolder.class 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 new file mode 100644 index 00000000..4427b091 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder$IntPropertyValuesHolder.class 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 new file mode 100644 index 00000000..483a115b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.class 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 new file mode 100644 index 00000000..6b090a67 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.class 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 new file mode 100644 index 00000000..6f04d6bc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$1.class 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 new file mode 100644 index 00000000..c38e111f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$2.class 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 new file mode 100644 index 00000000..90b41d76 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$3.class 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 new file mode 100644 index 00000000..fea2a587 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$4.class 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 new file mode 100644 index 00000000..7fad8e7f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$5.class 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 new file mode 100644 index 00000000..a3b14ccc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimationHandler.class 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 new file mode 100644 index 00000000..b5bcde23 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator$AnimatorUpdateListener.class 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 new file mode 100644 index 00000000..24581f1a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.class 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 new file mode 100644 index 00000000..c05ca82f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.class 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 new file mode 100644 index 00000000..2838e4dd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.class 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 new file mode 100644 index 00000000..664c61bd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.class 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 new file mode 100644 index 00000000..46b2f34e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.class 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 new file mode 100644 index 00000000..747aa2b3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.class 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 new file mode 100644 index 00000000..c7111d03 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/ActionProviderWrapper.class 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 new file mode 100644 index 00000000..546d29f8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/StandaloneActionMode.class 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 new file mode 100644 index 00000000..64f7c21b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.class 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 new file mode 100644 index 00000000..a0db78b2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.class 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 new file mode 100644 index 00000000..984fbada Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenu.class 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 new file mode 100644 index 00000000..1b120bf7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItem.class 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 new file mode 100644 index 00000000..8d7071d3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.class 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 new file mode 100644 index 00000000..728c15c9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$ActionButtonSubmenu.class 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 new file mode 100644 index 00000000..061492e2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$HasPermanentMenuKey.class 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 new file mode 100644 index 00000000..503b009d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OpenOverflowRunnable.class 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 new file mode 100644 index 00000000..4b31f642 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowMenuButton.class 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 new file mode 100644 index 00000000..01507fb1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$OverflowPopup.class 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 new file mode 100644 index 00000000..37d158d0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$PopupPresenterCallback.class 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 new file mode 100644 index 00000000..5008ae82 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState$1.class 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 new file mode 100644 index 00000000..115ca101 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter$SavedState.class 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 new file mode 100644 index 00000000..6dbc5200 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.class 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 new file mode 100644 index 00000000..bd4e448e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$ActionMenuChildView.class 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 new file mode 100644 index 00000000..50d67fcb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView$LayoutParams.class 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 new file mode 100644 index 00000000..a84ab5cb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ActionMenuView.class 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 new file mode 100644 index 00000000..b6f25ad0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.class 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 new file mode 100644 index 00000000..c190507c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/ListMenuItemView.class 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 new file mode 100644 index 00000000..48c1cb93 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$Callback.class 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 new file mode 100644 index 00000000..fd0e5d07 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder$ItemInvoker.class 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 new file mode 100644 index 00000000..9395c4d9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuBuilder.class 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 new file mode 100644 index 00000000..4ecae954 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemImpl.class 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 new file mode 100644 index 00000000..8dad1823 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper$1.class 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 new file mode 100644 index 00000000..72db4048 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.class 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 new file mode 100644 index 00000000..2ce6f8c4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$ExpandedIndexObserver.class 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 new file mode 100644 index 00000000..4a6e4c9a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper$MenuAdapter.class 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 new file mode 100644 index 00000000..ad6557a1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.class 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 new file mode 100644 index 00000000..15e9b40b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter$Callback.class 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 new file mode 100644 index 00000000..c6ab90ed Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuPresenter.class 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 new file mode 100644 index 00000000..5f30df61 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView$ItemView.class 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 new file mode 100644 index 00000000..fbf5f9a2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuView.class 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 new file mode 100644 index 00000000..aba5f4aa Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/MenuWrapper.class 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 new file mode 100644 index 00000000..e71c67dd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.class 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 new file mode 100644 index 00000000..bda99e96 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.class 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 new file mode 100644 index 00000000..22b352b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$1.class 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 new file mode 100644 index 00000000..7360e62d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView$VisibilityAnimListener.class 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 new file mode 100644 index 00000000..4f9e7ae7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/AbsActionBarView.class 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 new file mode 100644 index 00000000..c4d56c54 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContainer.class 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 new file mode 100644 index 00000000..b9e15900 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView$1.class 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 new file mode 100644 index 00000000..a1ee08e5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarContextView.class 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 new file mode 100644 index 00000000..964edb3b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$1.class 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 new file mode 100644 index 00000000..3a996aeb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$2.class 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 new file mode 100644 index 00000000..e8b210b7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$3.class 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 new file mode 100644 index 00000000..1922d890 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$ExpandedActionViewMenuPresenter.class 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 new file mode 100644 index 00000000..094326d5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$HomeView.class 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 new file mode 100644 index 00000000..a7ba80c7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState$1.class 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 new file mode 100644 index 00000000..fb4c07bc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView$SavedState.class 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 new file mode 100644 index 00000000..0be7be63 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ActionBarView.class 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 new file mode 100644 index 00000000..1465ae4f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingButton.class 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 new file mode 100644 index 00000000..4b95130d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/CapitalizingTextView.class 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 new file mode 100644 index 00000000..5d6d2e80 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.class 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 new file mode 100644 index 00000000..bce39568 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$RecycleBin.class 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 new file mode 100644 index 00000000..b7f5fd40 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState$1.class 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 new file mode 100644 index 00000000..4ab7e256 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner$SavedState.class 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 new file mode 100644 index 00000000..3381ced0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAbsSpinner.class 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 new file mode 100644 index 00000000..70d41eb8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterContextMenuInfo.class 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 new file mode 100644 index 00000000..27169b1e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$AdapterDataSetObserver.class 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 new file mode 100644 index 00000000..de5845ec Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemLongClickListener.class 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 new file mode 100644 index 00000000..aa2f8535 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$OnItemSelectedListener.class 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 new file mode 100644 index 00000000..ea5e114f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView$SelectionNotifier.class 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 new file mode 100644 index 00000000..96c541aa Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsAdapterView.class 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 new file mode 100644 index 00000000..6f20f856 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsLinearLayout.class 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 new file mode 100644 index 00000000..69efaa42 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$1.class 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 new file mode 100644 index 00000000..b2720332 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$DropDownListView.class 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 new file mode 100644 index 00000000..4a81a4c9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ListSelectorHider.class 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 new file mode 100644 index 00000000..ec726ae0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupDataSetObserver.class 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 new file mode 100644 index 00000000..13db2149 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupScrollListener.class 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 new file mode 100644 index 00000000..cbdfee54 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$PopupTouchInterceptor.class 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 new file mode 100644 index 00000000..77b61129 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow$ResizePopupRunnable.class 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 new file mode 100644 index 00000000..cf7938fe Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsListPopupWindow.class 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 new file mode 100644 index 00000000..ca6f3b75 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$AccessibilityEventSender.class 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 new file mode 100644 index 00000000..4fc92e77 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$RefreshProgressRunnable.class 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 new file mode 100644 index 00000000..1ffe42b6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState$1.class 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 new file mode 100644 index 00000000..344299f0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar$SavedState.class 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 new file mode 100644 index 00000000..1dfd7f39 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsProgressBar.class 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 new file mode 100644 index 00000000..464dd5b3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropDownAdapter.class 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 new file mode 100644 index 00000000..302265b6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup$1.class 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 new file mode 100644 index 00000000..5b646122 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$DropdownPopup.class 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 new file mode 100644 index 00000000..b4b1e9c4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner$SpinnerPopup.class 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 new file mode 100644 index 00000000..af41e52a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsSpinner.class 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 new file mode 100644 index 00000000..5f358247 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/IcsView.class 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 new file mode 100644 index 00000000..65980f24 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$1.class 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 new file mode 100644 index 00000000..00dd3041 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabAdapter.class 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 new file mode 100644 index 00000000..71ff8a54 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabClickListener.class 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 new file mode 100644 index 00000000..0910edf7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$TabView.class 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 new file mode 100644 index 00000000..51d073d2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView$VisibilityAnimListener.class 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 new file mode 100644 index 00000000..9553dff5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.class 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 new file mode 100644 index 00000000..c122c6d3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode$Callback.class 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 new file mode 100644 index 00000000..cc64b67a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionMode.class 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 new file mode 100644 index 00000000..48f981ac Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider$SubUiVisibilityListener.class 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 new file mode 100644 index 00000000..1699a0fc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/ActionProvider.class 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 new file mode 100644 index 00000000..e33c6664 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/CollapsibleActionView.class 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 new file mode 100644 index 00000000..917380a1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Menu.class 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 new file mode 100644 index 00000000..87ae93fd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$InflatedOnMenuItemClickListener.class 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 new file mode 100644 index 00000000..0c03c6ca Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater$MenuState.class 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 new file mode 100644 index 00000000..ce2200ce Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuInflater.class 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 new file mode 100644 index 00000000..c9055243 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnActionExpandListener.class 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 new file mode 100644 index 00000000..67695aff Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem$OnMenuItemClickListener.class 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 new file mode 100644 index 00000000..647b3331 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/MenuItem.class 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 new file mode 100644 index 00000000..6bb94ff1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/SubMenu.class 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 new file mode 100644 index 00000000..7dfe3560 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window$Callback.class 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 new file mode 100644 index 00000000..13353f82 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/view/Window.class 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 new file mode 100644 index 00000000..10861aa2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityChooserModelClient.class 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 new file mode 100644 index 00000000..f1aec6dc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivityResolveInfo.class 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 new file mode 100644 index 00000000..3c1a4ee8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$ActivitySorter.class 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 new file mode 100644 index 00000000..f462a6fc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$DefaultSorter.class 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 new file mode 100644 index 00000000..7de936f7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoricalRecord.class 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 new file mode 100644 index 00000000..5a7e018d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader$1.class 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 new file mode 100644 index 00000000..d08e2aed Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryLoader.class 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 new file mode 100644 index 00000000..4a0ff822 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$HistoryPersister.class 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 new file mode 100644 index 00000000..151d2d57 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$OnChooseActivityListener.class 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 new file mode 100644 index 00000000..5a8476b3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor$1.class 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 new file mode 100644 index 00000000..1e98dd25 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel$SerialExecutor.class 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 new file mode 100644 index 00000000..d933174f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserModel.class 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 new file mode 100644 index 00000000..9e35e283 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$1.class 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 new file mode 100644 index 00000000..895599e8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$2.class 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 new file mode 100644 index 00000000..41aceb93 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$3.class 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 new file mode 100644 index 00000000..9c059969 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$ActivityChooserViewAdapter.class 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 new file mode 100644 index 00000000..806c9a55 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$Callbacks.class 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 new file mode 100644 index 00000000..a42d8f25 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView$SetActivated.class 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 new file mode 100644 index 00000000..f457429e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ActivityChooserView.class 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 new file mode 100644 index 00000000..25d140b5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$OnShareTargetSelectedListener.class 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 new file mode 100644 index 00000000..6fb964b3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareAcitivityChooserModelPolicy.class 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 new file mode 100644 index 00000000..acbf8a67 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider$ShareMenuItemOnMenuItemClickListener.class 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 new file mode 100644 index 00000000..51329f7b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/classes/com/actionbarsherlock/widget/ShareActionProvider.class differ diff --git a/android-libraries/ActionBarSherlock/bin/jarlist.cache b/android-libraries/ActionBarSherlock/bin/jarlist.cache new file mode 100644 index 00000000..1b5ec3f9 --- /dev/null +++ b/android-libraries/ActionBarSherlock/bin/jarlist.cache @@ -0,0 +1,3 @@ +# 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 new file mode 100644 index 00000000..42bb3664 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..d12d923c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png 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 new file mode 100644 index 00000000..612889a4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png 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 new file mode 100644 index 00000000..9a80fb7b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..2b4a61ab Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..75d3269b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png 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 new file mode 100644 index 00000000..ca7df22e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png 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 new file mode 100644 index 00000000..b110188b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..95c76e3d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_light_holo.9.png 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 new file mode 100644 index 00000000..d6b96349 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png 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 new file mode 100644 index 00000000..20d7080b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..1dc40c9b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png 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 new file mode 100644 index 00000000..48bc5369 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..46fcf718 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..2adaa18e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..629911f0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..11c79406 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png 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 new file mode 100644 index 00000000..720f52d3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png 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 new file mode 100644 index 00000000..6e4332fb Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..ac9f39b4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png 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 new file mode 100644 index 00000000..932b70a9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..f4ddedfd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..fc2e90a8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png 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 new file mode 100644 index 00000000..2d8352bf Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png 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 new file mode 100644 index 00000000..365e83e5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png 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 new file mode 100644 index 00000000..0a42fb2b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png 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 new file mode 100644 index 00000000..8051417d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png 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 new file mode 100644 index 00000000..c9065de5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__dialog_full_holo_light.9.png 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 new file mode 100644 index 00000000..9deb8f03 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png 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 new file mode 100644 index 00000000..5b29b1cc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_ab_back_holo_light.png 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 new file mode 100644 index 00000000..bd2d459b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png 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 new file mode 100644 index 00000000..c6c30a10 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_cab_done_holo_light.png 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 new file mode 100644 index 00000000..cb6ebdaf Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png 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 new file mode 100644 index 00000000..48d47284 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png 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 new file mode 100644 index 00000000..f5c51305 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png 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 new file mode 100644 index 00000000..7c12c576 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__ic_menu_share_holo_light.png 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 new file mode 100644 index 00000000..4da70ac7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_activated_holo.9.png 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 new file mode 100644 index 00000000..a57e66ac Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_dark.9.png 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 new file mode 100644 index 00000000..75bd2d7d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_divider_holo_light.9.png 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 new file mode 100644 index 00000000..f9587289 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_focused_holo.9.png 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 new file mode 100644 index 00000000..4da70ac7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_longpressed_holo.9.png 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 new file mode 100644 index 00000000..d3e72411 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..d3e72411 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..cb128962 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..233da8e3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..29ad572b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png 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 new file mode 100644 index 00000000..612b8872 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png 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 new file mode 100644 index 00000000..6cde0bd6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png 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 new file mode 100644 index 00000000..82af131a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_bg_holo_light.9.png 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 new file mode 100644 index 00000000..15f110b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png 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 new file mode 100644 index 00000000..15f110b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_primary_holo_light.9.png 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 new file mode 100644 index 00000000..4bf430f1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png 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 new file mode 100644 index 00000000..4bf430f1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png 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 new file mode 100644 index 00000000..919c328b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_inner_holo.png 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 new file mode 100644 index 00000000..ad987cb4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_48_outer_holo.png 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 new file mode 100644 index 00000000..9ae770c1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png 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 new file mode 100644 index 00000000..e932deee Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png 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 new file mode 100644 index 00000000..5caed9d4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..55abe710 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..88742927 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..a071008e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png 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 new file mode 100644 index 00000000..8747bfc5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..6893b36b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..1e6ab9aa Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png 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 new file mode 100644 index 00000000..4dfaac80 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_holo.9.png 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 new file mode 100644 index 00000000..4060199b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png 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 new file mode 100644 index 00000000..86304e5a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png 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 new file mode 100644 index 00000000..bcfa0581 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-hdpi/ic_launcher.png 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 new file mode 100644 index 00000000..dd7c05b0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-ldpi/ic_launcher.png 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 new file mode 100644 index 00000000..c2fef9ad Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..54c82238 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png 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 new file mode 100644 index 00000000..baa52989 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png 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 new file mode 100644 index 00000000..fed7fa6a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..d582d390 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..735c0490 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png 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 new file mode 100644 index 00000000..1071e098 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png 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 new file mode 100644 index 00000000..a9f2be43 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..a51dc9bc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_light_holo.9.png 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 new file mode 100644 index 00000000..89eccd47 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png 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 new file mode 100644 index 00000000..fa4ca757 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..f2f6fc79 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png 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 new file mode 100644 index 00000000..6584f956 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..f3a769b2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..06010e92 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..ff64b454 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..b1ac62c7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png 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 new file mode 100644 index 00000000..f2924247 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png 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 new file mode 100644 index 00000000..b1d51c67 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..10b0432b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png 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 new file mode 100644 index 00000000..96329958 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..0837e7d2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..0a71f49f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png 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 new file mode 100644 index 00000000..4e4e5165 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png 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 new file mode 100644 index 00000000..a6c5c8fd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png 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 new file mode 100644 index 00000000..9da38a32 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png 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 new file mode 100644 index 00000000..58d8dc1d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png 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 new file mode 100644 index 00000000..f5a473b2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__dialog_full_holo_light.9.png 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 new file mode 100644 index 00000000..7290c5c8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png 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 new file mode 100644 index 00000000..7d944d3a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_ab_back_holo_light.png 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 new file mode 100644 index 00000000..3382680c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png 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 new file mode 100644 index 00000000..f11b21f4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_cab_done_holo_light.png 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 new file mode 100644 index 00000000..3b4e7462 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png 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 new file mode 100644 index 00000000..aa5ea4fd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png 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 new file mode 100644 index 00000000..00e499c8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png 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 new file mode 100644 index 00000000..240d4069 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__ic_menu_share_holo_light.png 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 new file mode 100644 index 00000000..92030f26 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_activated_holo.9.png 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 new file mode 100644 index 00000000..a57e66ac Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_dark.9.png 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 new file mode 100644 index 00000000..75bd2d7d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_divider_holo_light.9.png 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 new file mode 100644 index 00000000..7c9fdbf1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_focused_holo.9.png 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 new file mode 100644 index 00000000..92030f26 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_longpressed_holo.9.png 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 new file mode 100644 index 00000000..d6717c1f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..d6717c1f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..9428f21a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..80cd8e61 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..99cf362c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png 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 new file mode 100644 index 00000000..50636873 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png 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 new file mode 100644 index 00000000..efe935f2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png 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 new file mode 100644 index 00000000..8672828a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_bg_holo_light.9.png 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 new file mode 100644 index 00000000..333dda5a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png 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 new file mode 100644 index 00000000..333dda5a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_primary_holo_light.9.png 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 new file mode 100644 index 00000000..29ffde6a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png 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 new file mode 100644 index 00000000..29ffde6a Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png 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 new file mode 100644 index 00000000..ff1dc7f5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_inner_holo.png 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 new file mode 100644 index 00000000..0b113bf9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_48_outer_holo.png 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 new file mode 100644 index 00000000..6c63dd4b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png 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 new file mode 100644 index 00000000..3928d0d0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png 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 new file mode 100644 index 00000000..f7219e89 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..ede8b34c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..e4de3f63 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..334ec168 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png 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 new file mode 100644 index 00000000..8d9531e4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..0f504f82 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..bce0e08e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png 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 new file mode 100644 index 00000000..dd022de2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_holo.9.png 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 new file mode 100644 index 00000000..2852fb5d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png 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 new file mode 100644 index 00000000..d2716b33 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png 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 new file mode 100644 index 00000000..85848ff4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-mdpi/ic_launcher.png 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 new file mode 100644 index 00000000..d01fae99 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..5fc7d87f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png 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 new file mode 100644 index 00000000..f6cbc621 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png 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 new file mode 100644 index 00000000..f395cbde Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..6e6b999b Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..ca2e57bd Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png 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 new file mode 100644 index 00000000..a57c1b53 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png 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 new file mode 100644 index 00000000..2c4dd4f9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..27d6c8b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png 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 new file mode 100644 index 00000000..58263065 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png 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 new file mode 100644 index 00000000..3e722238 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..d2d77540 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png 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 new file mode 100644 index 00000000..140518f8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..97a6bd57 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..3069943f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..920d2b58 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..dfe74064 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png 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 new file mode 100644 index 00000000..959ca7af Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png 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 new file mode 100644 index 00000000..df972124 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..79201882 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png 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 new file mode 100644 index 00000000..1801d343 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..b3d3e199 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..1bf70ca2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png 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 new file mode 100644 index 00000000..100d3166 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png 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 new file mode 100644 index 00000000..58bdedd2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png 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 new file mode 100644 index 00000000..66d9d8dc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png 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 new file mode 100644 index 00000000..86e24585 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png 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 new file mode 100644 index 00000000..b4058439 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png 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 new file mode 100644 index 00000000..bfc1c660 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png 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 new file mode 100644 index 00000000..87a5a420 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png 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 new file mode 100644 index 00000000..fd5f4161 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png 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 new file mode 100644 index 00000000..0ccab808 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png 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 new file mode 100644 index 00000000..ef9792a4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png 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 new file mode 100644 index 00000000..3f275ad1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png 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 new file mode 100644 index 00000000..4492c498 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png 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 new file mode 100644 index 00000000..a61854b4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png 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 new file mode 100644 index 00000000..c6cbc4d6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_activated_holo.9.png 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 new file mode 100644 index 00000000..c1692f8e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png 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 new file mode 100644 index 00000000..e190cfc4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_divider_holo_light.9.png 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 new file mode 100644 index 00000000..9059f3e5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_focused_holo.9.png 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 new file mode 100644 index 00000000..c6cbc4d6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_longpressed_holo.9.png 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 new file mode 100644 index 00000000..8acdbf45 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..8acdbf45 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..0117091f Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..4f123024 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..d9108065 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png 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 new file mode 100644 index 00000000..68494e75 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png 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 new file mode 100644 index 00000000..b8a964bc Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png 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 new file mode 100644 index 00000000..380f8d1e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png 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 new file mode 100644 index 00000000..a6bd0ce7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png 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 new file mode 100644 index 00000000..a6bd0ce7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png 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 new file mode 100644 index 00000000..058c512c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png 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 new file mode 100644 index 00000000..058c512c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png 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 new file mode 100644 index 00000000..662036ca Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_inner_holo.png 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 new file mode 100644 index 00000000..6d33f314 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_48_outer_holo.png 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 new file mode 100644 index 00000000..487c06b3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png 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 new file mode 100644 index 00000000..3724097e Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png 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 new file mode 100644 index 00000000..b7088e1d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..8e91ab97 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..e16fead1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..475dfcd9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png 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 new file mode 100644 index 00000000..3b6ec51d Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..6e829720 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..140ebfde Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png 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 new file mode 100644 index 00000000..a94f0984 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_holo.9.png 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 new file mode 100644 index 00000000..25ec789c Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png 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 new file mode 100644 index 00000000..c5ed3cb9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png 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 new file mode 100644 index 00000000..916901e9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/bin/res/drawable-xhdpi/ic_launcher.png differ diff --git a/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/BuildConfig.java b/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/BuildConfig.java new file mode 100644 index 00000000..ceb2ab07 --- /dev/null +++ b/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/BuildConfig.java @@ -0,0 +1,6 @@ +/** 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 new file mode 100644 index 00000000..b48b6242 --- /dev/null +++ b/android-libraries/ActionBarSherlock/gen/com/actionbarsherlock/R.java @@ -0,0 +1,2813 @@ +/* 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 new file mode 100644 index 00000000..1fbeba09 Binary files /dev/null and b/android-libraries/ActionBarSherlock/libs/android-support-v4.jar differ diff --git a/android-libraries/ActionBarSherlock/proguard-project.txt b/android-libraries/ActionBarSherlock/proguard-project.txt new file mode 100644 index 00000000..f2fe1559 --- /dev/null +++ b/android-libraries/ActionBarSherlock/proguard-project.txt @@ -0,0 +1,20 @@ +# 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 new file mode 100644 index 00000000..f28bc833 --- /dev/null +++ b/android-libraries/ActionBarSherlock/project.properties @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 00000000..ea7459aa --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_dark.xml @@ -0,0 +1,20 @@ + + + + + + + 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 new file mode 100644 index 00000000..0edb33b4 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_disable_only_holo_light.xml @@ -0,0 +1,21 @@ + + + + + + + + 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 new file mode 100644 index 00000000..2bcfd0b6 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_dark.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + 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 new file mode 100644 index 00000000..198384fe --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/color/abs__primary_text_holo_light.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..769463b3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..88f11dcb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_inverse_holo.9.png 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 new file mode 100644 index 00000000..73050476 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_solid_light_holo.9.png 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 new file mode 100644 index 00000000..712a551e Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..bf3b9438 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_bottom_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..6c141577 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_dark.9.png 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 new file mode 100644 index 00000000..f4ff16be Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_share_pack_holo_light.9.png 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 new file mode 100644 index 00000000..cbbaec58 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..af917e5b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_light_holo.9.png 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 new file mode 100644 index 00000000..2d59f354 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_solid_shadow_holo.9.png 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 new file mode 100644 index 00000000..0520e5a2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..e3e3f93b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_solid_light_holo.9.png 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 new file mode 100644 index 00000000..1e395722 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..a16db853 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_stacked_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..0eff695d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..219b170f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ab_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..b0dc31fb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_dark.9.png 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 new file mode 100644 index 00000000..4bc2683b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_default_holo_light.9.png 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 new file mode 100644 index 00000000..4af38fb7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..d32f74cf Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_focused_holo_light.9.png 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 new file mode 100644 index 00000000..66adffed Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..caeff9c3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__btn_cab_done_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..1d836f65 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_dark.9.png 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 new file mode 100644 index 00000000..5818666d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_bottom_holo_light.9.png 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 new file mode 100644 index 00000000..564fb34b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_dark.9.png 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 new file mode 100644 index 00000000..ae21b760 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__cab_background_top_holo_light.9.png 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 new file mode 100644 index 00000000..79e56f52 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_dark.9.png 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 new file mode 100644 index 00000000..e029f210 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__dialog_full_holo_light.9.png 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 new file mode 100644 index 00000000..897a1c11 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_dark.png 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 new file mode 100644 index 00000000..0c89f714 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_ab_back_holo_light.png 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 new file mode 100644 index 00000000..d8662e3f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_dark.png 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 new file mode 100644 index 00000000..ed03f620 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_cab_done_holo_light.png 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 new file mode 100644 index 00000000..2abc4580 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png 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 new file mode 100644 index 00000000..bb6aef1d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_moreoverflow_normal_holo_light.png 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 new file mode 100644 index 00000000..6f747c8f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_dark.png 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 new file mode 100644 index 00000000..682b2fde Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__ic_menu_share_holo_light.png 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 new file mode 100644 index 00000000..4ea7afa0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_activated_holo.9.png 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 new file mode 100644 index 00000000..986ab0b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_dark.9.png 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 new file mode 100644 index 00000000..0279e17a Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_divider_holo_light.9.png 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 new file mode 100644 index 00000000..516f5c73 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_focused_holo.9.png 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 new file mode 100644 index 00000000..4ea7afa0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_longpressed_holo.9.png 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 new file mode 100644 index 00000000..5654cd69 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..5654cd69 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..f6fd30dc Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..ca8e9a27 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__list_selector_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..4d3d2085 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_dark.9.png 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 new file mode 100644 index 00000000..924a99d1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__menu_dropdown_panel_holo_light.9.png 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 new file mode 100644 index 00000000..310c368e Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_dark.9.png 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 new file mode 100644 index 00000000..70cb7fc7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_bg_holo_light.9.png 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 new file mode 100644 index 00000000..1c269205 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_dark.9.png 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 new file mode 100644 index 00000000..1c269205 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_primary_holo_light.9.png 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 new file mode 100644 index 00000000..40d0d164 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_dark.9.png 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 new file mode 100644 index 00000000..40d0d164 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__progress_secondary_holo_light.9.png 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 new file mode 100644 index 00000000..c8358e9c Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_inner_holo.png 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 new file mode 100644 index 00000000..f62f74bb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_48_outer_holo.png 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 new file mode 100644 index 00000000..eb28ff9a Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_dark.9.png 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 new file mode 100644 index 00000000..d281adb5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_default_holo_light.9.png 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 new file mode 100644 index 00000000..b2985860 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..4215396d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..a280eabf Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..f8d619b4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_focused_holo_light.9.png 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 new file mode 100644 index 00000000..955a2f34 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..6c22e223 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__spinner_ab_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..673e3bf1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_focused_holo.9.png 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 new file mode 100644 index 00000000..d57df98b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_holo.9.png 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 new file mode 100644 index 00000000..6278eef4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_selected_pressed_holo.9.png 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 new file mode 100644 index 00000000..aadc6f87 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/abs__tab_unselected_pressed_holo.9.png differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-hdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 00000000..96a442e5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-hdpi/ic_launcher.png differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-ldpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-ldpi/ic_launcher.png new file mode 100644 index 00000000..99238729 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-ldpi/ic_launcher.png 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 new file mode 100644 index 00000000..b2293670 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..c65f443e Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_inverse_holo.9.png 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 new file mode 100644 index 00000000..0706c8af Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_solid_light_holo.9.png 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 new file mode 100644 index 00000000..d814d02d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..b139c8e4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_bottom_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..ed4ba34e Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_dark.9.png 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 new file mode 100644 index 00000000..8f10bd52 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_share_pack_holo_light.9.png 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 new file mode 100644 index 00000000..743d00b6 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..17c1fb92 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_light_holo.9.png 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 new file mode 100644 index 00000000..ddfc8e3d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_solid_shadow_holo.9.png 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 new file mode 100644 index 00000000..007a4b23 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..ad6e1a4d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_solid_light_holo.9.png 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 new file mode 100644 index 00000000..0ad6c888 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..19b50abc Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_stacked_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..ad980b13 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..60e6c527 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ab_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..5461b9c0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_dark.9.png 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 new file mode 100644 index 00000000..5dc6f804 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_default_holo_light.9.png 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 new file mode 100644 index 00000000..a70b53c5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..c7a9896b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_focused_holo_light.9.png 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 new file mode 100644 index 00000000..85d7aadd Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..f7b01e01 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__btn_cab_done_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..d8f1c8bd Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_dark.9.png 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 new file mode 100644 index 00000000..31e49894 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_bottom_holo_light.9.png 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 new file mode 100644 index 00000000..7c2cbe53 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_dark.9.png 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 new file mode 100644 index 00000000..30cbdc17 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__cab_background_top_holo_light.9.png 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 new file mode 100644 index 00000000..fb3660ea Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_dark.9.png 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 new file mode 100644 index 00000000..f18050ea Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__dialog_full_holo_light.9.png 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 new file mode 100644 index 00000000..df2d3d15 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_dark.png 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 new file mode 100644 index 00000000..b2aa9c26 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_ab_back_holo_light.png 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 new file mode 100644 index 00000000..a17b6a78 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_dark.png 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 new file mode 100644 index 00000000..b28b3b54 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_cab_done_holo_light.png 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 new file mode 100644 index 00000000..ba704b67 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png 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 new file mode 100644 index 00000000..01d68169 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_moreoverflow_normal_holo_light.png 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 new file mode 100644 index 00000000..6bf21e30 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_dark.png 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 new file mode 100644 index 00000000..70fe31aa Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__ic_menu_share_holo_light.png 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 new file mode 100644 index 00000000..3bf8e036 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_activated_holo.9.png 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 new file mode 100644 index 00000000..986ab0b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_dark.9.png 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 new file mode 100644 index 00000000..0279e17a Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_divider_holo_light.9.png 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 new file mode 100644 index 00000000..7c0599e3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_focused_holo.9.png 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 new file mode 100644 index 00000000..3bf8e036 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_longpressed_holo.9.png 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 new file mode 100644 index 00000000..6e77525d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..6e77525d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..92da2f0d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..42cb6463 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__list_selector_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..460ec46e Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_dark.9.png 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 new file mode 100644 index 00000000..e84adf2d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__menu_dropdown_panel_holo_light.9.png 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 new file mode 100644 index 00000000..3d946e54 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_dark.9.png 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 new file mode 100644 index 00000000..4bb22f0e Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_bg_holo_light.9.png 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 new file mode 100644 index 00000000..ab8ec698 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_dark.9.png 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 new file mode 100644 index 00000000..ab8ec698 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_primary_holo_light.9.png 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 new file mode 100644 index 00000000..7274274b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_dark.9.png 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 new file mode 100644 index 00000000..7274274b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__progress_secondary_holo_light.9.png 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 new file mode 100644 index 00000000..9458668f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_inner_holo.png 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 new file mode 100644 index 00000000..4ce73edc Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_48_outer_holo.png 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 new file mode 100644 index 00000000..29aff4d4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_dark.9.png 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 new file mode 100644 index 00000000..4055f705 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_default_holo_light.9.png 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 new file mode 100644 index 00000000..ea4ee042 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..f74c02b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..09a2992c Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..6536ee63 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_focused_holo_light.9.png 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 new file mode 100644 index 00000000..202b5b72 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..6de0ba88 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__spinner_ab_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..c9972e74 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_focused_holo.9.png 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 new file mode 100644 index 00000000..587337ca Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_holo.9.png 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 new file mode 100644 index 00000000..155c4fc7 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_selected_pressed_holo.9.png 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 new file mode 100644 index 00000000..b1223fe3 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/abs__tab_unselected_pressed_holo.9.png differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-mdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 00000000..359047df Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-mdpi/ic_launcher.png 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 new file mode 100644 index 00000000..6bcbdb83 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable-v11/abs__progress_medium_holo.xml @@ -0,0 +1,34 @@ + + + + + + + + + + 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 new file mode 100644 index 00000000..57533469 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..7e6c047d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_inverse_holo.9.png 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 new file mode 100644 index 00000000..8155fe84 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_solid_light_holo.9.png 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 new file mode 100644 index 00000000..6cee9a12 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..fa4d76af Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_bottom_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..55099d49 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_dark.9.png 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 new file mode 100644 index 00000000..3c4701fc Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_share_pack_holo_light.9.png 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 new file mode 100644 index 00000000..6622cbad Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..c4272978 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_light_holo.9.png 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 new file mode 100644 index 00000000..d0df29d8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_solid_shadow_holo.9.png 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 new file mode 100644 index 00000000..a0d9c1b9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_dark_holo.9.png 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 new file mode 100644 index 00000000..d36f99fe Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_solid_light_holo.9.png 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 new file mode 100644 index 00000000..5ad475dc Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..6ade5eeb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_stacked_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..719b9234 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_dark_holo.9.png 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 new file mode 100644 index 00000000..6da264db Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ab_transparent_light_holo.9.png 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 new file mode 100644 index 00000000..7ef2db75 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_dark.9.png 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 new file mode 100644 index 00000000..2283b4c0 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_default_holo_light.9.png 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 new file mode 100644 index 00000000..6d2039e2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..3c909b51 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_focused_holo_light.9.png 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 new file mode 100644 index 00000000..131d1030 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..3e7dcdfd Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__btn_cab_done_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..0bd09806 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_dark.9.png 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 new file mode 100644 index 00000000..43ed26d4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_bottom_holo_light.9.png 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 new file mode 100644 index 00000000..6b315798 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_dark.9.png 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 new file mode 100644 index 00000000..df0121bb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__cab_background_top_holo_light.9.png 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 new file mode 100644 index 00000000..f4970ad1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_dark.9.png 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 new file mode 100644 index 00000000..172fc3b5 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__dialog_full_holo_light.9.png 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 new file mode 100644 index 00000000..8ded62fb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_dark.png 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 new file mode 100644 index 00000000..517e9f72 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_ab_back_holo_light.png 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 new file mode 100644 index 00000000..2e06dd01 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_dark.png 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 new file mode 100644 index 00000000..bb19810b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_cab_done_holo_light.png 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 new file mode 100644 index 00000000..a92fb1d4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_dark.png 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 new file mode 100644 index 00000000..930ca8d9 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_moreoverflow_normal_holo_light.png 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 new file mode 100644 index 00000000..45a0f1da Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_dark.png 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 new file mode 100644 index 00000000..528e554a Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__ic_menu_share_holo_light.png 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 new file mode 100644 index 00000000..eda10e61 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_activated_holo.9.png 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 new file mode 100644 index 00000000..e62f011d Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_dark.9.png 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 new file mode 100644 index 00000000..65061c0f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_divider_holo_light.9.png 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 new file mode 100644 index 00000000..690cb1eb Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_focused_holo.9.png 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 new file mode 100644 index 00000000..eda10e61 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_longpressed_holo.9.png 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 new file mode 100644 index 00000000..e4b33935 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..e4b33935 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..88726b69 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..c6a7d4d8 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__list_selector_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..e2aff72f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_dark.9.png 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 new file mode 100644 index 00000000..93066c84 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__menu_dropdown_panel_holo_light.9.png 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 new file mode 100644 index 00000000..345f5d30 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_dark.9.png 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 new file mode 100644 index 00000000..c843ef3a Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_bg_holo_light.9.png 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 new file mode 100644 index 00000000..c6c3f1ec Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_dark.9.png 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 new file mode 100644 index 00000000..c6c3f1ec Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_primary_holo_light.9.png 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 new file mode 100644 index 00000000..205b66e2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_dark.9.png 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 new file mode 100644 index 00000000..205b66e2 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__progress_secondary_holo_light.9.png 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 new file mode 100644 index 00000000..19517c4b Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_inner_holo.png 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 new file mode 100644 index 00000000..14143c51 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_48_outer_holo.png 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 new file mode 100644 index 00000000..d8929fcd Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_dark.9.png 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 new file mode 100644 index 00000000..9174c4e4 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_default_holo_light.9.png 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 new file mode 100644 index 00000000..3015d307 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_dark.9.png 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 new file mode 100644 index 00000000..126637d1 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_disabled_holo_light.9.png 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 new file mode 100644 index 00000000..d45c7a86 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_dark.9.png 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 new file mode 100644 index 00000000..29036b90 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_focused_holo_light.9.png 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 new file mode 100644 index 00000000..2cb34d7f Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_dark.9.png 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 new file mode 100644 index 00000000..82f752fd Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__spinner_ab_pressed_holo_light.9.png 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 new file mode 100644 index 00000000..03cfb094 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_focused_holo.9.png 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 new file mode 100644 index 00000000..e4229f26 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_holo.9.png 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 new file mode 100644 index 00000000..e862cb12 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_selected_pressed_holo.9.png 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 new file mode 100644 index 00000000..f1eb6732 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/abs__tab_unselected_pressed_holo.9.png differ diff --git a/android-libraries/ActionBarSherlock/res/drawable-xhdpi/ic_launcher.png b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 00000000..71c6d760 Binary files /dev/null and b/android-libraries/ActionBarSherlock/res/drawable-xhdpi/ic_launcher.png 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 new file mode 100644 index 00000000..85c2c021 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_dark.xml @@ -0,0 +1,20 @@ + + + + + + + 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 new file mode 100644 index 00000000..85c2c021 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__activated_background_holo_light.xml @@ -0,0 +1,20 @@ + + + + + + + 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 new file mode 100644 index 00000000..cab89628 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_dark.xml @@ -0,0 +1,24 @@ + + + + + + + + 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 new file mode 100644 index 00000000..42ba8a0d --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__btn_cab_done_holo_light.xml @@ -0,0 +1,24 @@ + + + + + + + + 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 new file mode 100644 index 00000000..2588a492 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_dark.xml @@ -0,0 +1,18 @@ + + + + + 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 new file mode 100644 index 00000000..e2078c96 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__ic_menu_moreoverflow_holo_light.xml @@ -0,0 +1,18 @@ + + + + + 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 new file mode 100644 index 00000000..d99b7a42 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_dark.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..da5fb2e8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__item_background_holo_light.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..b2ce4f0f --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_dark.xml @@ -0,0 +1,20 @@ + + + + + + + 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 new file mode 100644 index 00000000..d7e31b1d --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_background_transition_holo_light.xml @@ -0,0 +1,20 @@ + + + + + + + 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 new file mode 100644 index 00000000..08b8b12f --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_dark.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..ada490bf --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__list_selector_holo_light.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..bd19140a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_dark.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..321f07c8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_horizontal_holo_light.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/drawable/abs__progress_medium_holo.xml b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_medium_holo.xml new file mode 100644 index 00000000..6d4814f8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__progress_medium_holo.xml @@ -0,0 +1,34 @@ + + + + + + + + + + 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 new file mode 100644 index 00000000..4af5e22a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_dark.xml @@ -0,0 +1,25 @@ + + + + + + + + + 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 new file mode 100644 index 00000000..b7850847 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__spinner_ab_holo_light.xml @@ -0,0 +1,25 @@ + + + + + + + + + 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 new file mode 100644 index 00000000..d34e2081 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/drawable/abs__tab_indicator_ab_holo.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..8811dad8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout-large/abs__action_mode_close_item.xml @@ -0,0 +1,40 @@ + + + + + + + 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 new file mode 100644 index 00000000..6c183c05 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_dropdown_item.xml @@ -0,0 +1,26 @@ + + + diff --git a/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_item.xml b/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_item.xml new file mode 100644 index 00000000..61dc0252 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout-v14/sherlock_spinner_item.xml @@ -0,0 +1,26 @@ + + + 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 new file mode 100644 index 00000000..040df44a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + 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 new file mode 100644 index 00000000..c64ef141 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout-xlarge/abs__screen_action_bar_overlay.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_home.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_home.xml new file mode 100644 index 00000000..5c1e9ec4 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_home.xml @@ -0,0 +1,38 @@ + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab.xml new file mode 100644 index 00000000..f46f7a04 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab.xml @@ -0,0 +1,7 @@ + + + \ 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 new file mode 100644 index 00000000..0d51220c --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_tab_bar_view.xml @@ -0,0 +1,6 @@ + + + \ 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 new file mode 100644 index 00000000..dd69acad --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_bar_title_item.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + 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 new file mode 100644 index 00000000..13149fd6 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_item_layout.xml @@ -0,0 +1,56 @@ + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_layout.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_layout.xml new file mode 100644 index 00000000..a6f8e53f --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_menu_layout.xml @@ -0,0 +1,23 @@ + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_bar.xml b/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_bar.xml new file mode 100644 index 00000000..7168dc77 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_bar.xml @@ -0,0 +1,24 @@ + + + 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 new file mode 100644 index 00000000..875ec3e1 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__action_mode_close_item.xml @@ -0,0 +1,31 @@ + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view.xml b/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view.xml new file mode 100644 index 00000000..019d14ef --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..b430032a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__activity_chooser_view_list_item.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__dialog_title_holo.xml b/android-libraries/ActionBarSherlock/res/layout/abs__dialog_title_holo.xml new file mode 100644 index 00000000..6402f28b --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__dialog_title_holo.xml @@ -0,0 +1,46 @@ + + + + + + + + + + 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 new file mode 100644 index 00000000..39aca3a8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_checkbox.xml @@ -0,0 +1,26 @@ + + + + + + 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 new file mode 100644 index 00000000..55ab28a2 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_icon.xml @@ -0,0 +1,28 @@ + + + + + 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 new file mode 100644 index 00000000..147f36fe --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_layout.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..ff54bbec --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__list_menu_item_radio.xml @@ -0,0 +1,24 @@ + + + + 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 new file mode 100644 index 00000000..d42425ad --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__popup_menu_item_layout.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar.xml b/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar.xml new file mode 100644 index 00000000..1fb82fe9 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + 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 new file mode 100644 index 00000000..0961ef56 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__screen_action_bar_overlay.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple.xml b/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple.xml new file mode 100644 index 00000000..33e2dea0 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple.xml @@ -0,0 +1,38 @@ + + + + + + + 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 new file mode 100644 index 00000000..f8b9fb18 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/abs__screen_simple_overlay_action_mode.xml @@ -0,0 +1,38 @@ + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/main.xml b/android-libraries/ActionBarSherlock/res/layout/main.xml new file mode 100644 index 00000000..ac9c0aba --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/main.xml @@ -0,0 +1,12 @@ + + + + + + \ 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 new file mode 100644 index 00000000..a6c6252d --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_dropdown_item.xml @@ -0,0 +1,26 @@ + + + diff --git a/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_item.xml b/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_item.xml new file mode 100644 index 00000000..bea74017 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/layout/sherlock_spinner_item.xml @@ -0,0 +1,26 @@ + + + diff --git a/android-libraries/ActionBarSherlock/res/values-land/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-land/abs__dimens.xml new file mode 100644 index 00000000..502cc16a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-land/abs__dimens.xml @@ -0,0 +1,33 @@ + + + + + 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 new file mode 100644 index 00000000..3312cfa7 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-large-hdpi-1024x600/abs__dimens.xml @@ -0,0 +1,33 @@ + + + + + 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 new file mode 100644 index 00000000..502cc16a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-large-land-hdpi-1024x600/abs__dimens.xml @@ -0,0 +1,33 @@ + + + + + 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 new file mode 100644 index 00000000..3312cfa7 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-large-land-mdpi-1024x600/abs__dimens.xml @@ -0,0 +1,33 @@ + + + + + 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 new file mode 100644 index 00000000..35910333 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-large-mdpi-1024x600/abs__dimens.xml @@ -0,0 +1,36 @@ + + + + + 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 new file mode 100644 index 00000000..63b12f7f --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-large/abs__dimens.xml @@ -0,0 +1,29 @@ + + + + + 55% + + 80% + diff --git a/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__bools.xml b/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__bools.xml new file mode 100644 index 00000000..7a48e154 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__bools.xml @@ -0,0 +1,19 @@ + + + + + false + diff --git a/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__dimens.xml new file mode 100644 index 00000000..f6785381 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-sw600dp/abs__dimens.xml @@ -0,0 +1,38 @@ + + + + + 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 new file mode 100644 index 00000000..03473572 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-v11/abs__themes.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values-v14/abs__styles.xml b/android-libraries/ActionBarSherlock/res/values-v14/abs__styles.xml new file mode 100644 index 00000000..f2aa64d2 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-v14/abs__styles.xml @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values-v14/abs__themes.xml b/android-libraries/ActionBarSherlock/res/values-v14/abs__themes.xml new file mode 100644 index 00000000..ceb96073 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-v14/abs__themes.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values-w360dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-w360dp/abs__dimens.xml new file mode 100644 index 00000000..6f49d7e4 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-w360dp/abs__dimens.xml @@ -0,0 +1,22 @@ + + + + 3 + diff --git a/android-libraries/ActionBarSherlock/res/values-w480dp/abs__bools.xml b/android-libraries/ActionBarSherlock/res/values-w480dp/abs__bools.xml new file mode 100644 index 00000000..3eaf4aee --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-w480dp/abs__bools.xml @@ -0,0 +1,22 @@ + + + + true + false + diff --git a/android-libraries/ActionBarSherlock/res/values-w480dp/abs__config.xml b/android-libraries/ActionBarSherlock/res/values-w480dp/abs__config.xml new file mode 100644 index 00000000..88357b0a --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-w480dp/abs__config.xml @@ -0,0 +1,29 @@ + + + + + + + + true + + diff --git a/android-libraries/ActionBarSherlock/res/values-w500dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-w500dp/abs__dimens.xml new file mode 100644 index 00000000..2fd4deea --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-w500dp/abs__dimens.xml @@ -0,0 +1,22 @@ + + + + 4 + diff --git a/android-libraries/ActionBarSherlock/res/values-w600dp/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-w600dp/abs__dimens.xml new file mode 100644 index 00000000..b085952d --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-w600dp/abs__dimens.xml @@ -0,0 +1,22 @@ + + + + 5 + diff --git a/android-libraries/ActionBarSherlock/res/values-xlarge/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values-xlarge/abs__dimens.xml new file mode 100644 index 00000000..bfc535de --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values-xlarge/abs__dimens.xml @@ -0,0 +1,45 @@ + + + + + 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 new file mode 100644 index 00000000..81c34710 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__attrs.xml @@ -0,0 +1,380 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values/abs__bools.xml b/android-libraries/ActionBarSherlock/res/values/abs__bools.xml new file mode 100644 index 00000000..0b432448 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__bools.xml @@ -0,0 +1,22 @@ + + + + + false + true + true + + diff --git a/android-libraries/ActionBarSherlock/res/values/abs__colors.xml b/android-libraries/ActionBarSherlock/res/values/abs__colors.xml new file mode 100644 index 00000000..625c632f --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__colors.xml @@ -0,0 +1,27 @@ + + + + + #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 new file mode 100644 index 00000000..4c7b5d45 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__config.xml @@ -0,0 +1,43 @@ + + + + + + + + 320dp + + + false + + + true + + + false + + diff --git a/android-libraries/ActionBarSherlock/res/values/abs__dimens.xml b/android-libraries/ActionBarSherlock/res/values/abs__dimens.xml new file mode 100644 index 00000000..0a409756 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__dimens.xml @@ -0,0 +1,50 @@ + + + + + 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 new file mode 100644 index 00000000..f9f56045 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__ids.xml @@ -0,0 +1,26 @@ + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values/abs__strings.xml b/android-libraries/ActionBarSherlock/res/values/abs__strings.xml new file mode 100644 index 00000000..1e1c7022 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__strings.xml @@ -0,0 +1,42 @@ + + + + + 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 new file mode 100644 index 00000000..8cbd3648 --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__styles.xml @@ -0,0 +1,384 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values/abs__themes.xml b/android-libraries/ActionBarSherlock/res/values/abs__themes.xml new file mode 100644 index 00000000..5300dedd --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/abs__themes.xml @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android-libraries/ActionBarSherlock/res/values/strings.xml b/android-libraries/ActionBarSherlock/res/values/strings.xml new file mode 100644 index 00000000..43d1652c --- /dev/null +++ b/android-libraries/ActionBarSherlock/res/values/strings.xml @@ -0,0 +1,7 @@ + + + + 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 new file mode 100644 index 00000000..3e3db62b --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/android/support/v4/app/_ActionBarSherlockTrojanHorse.java @@ -0,0 +1,144 @@ +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 new file mode 100644 index 00000000..8340fb59 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/ActionBarSherlock.java @@ -0,0 +1,791 @@ +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 new file mode 100644 index 00000000..2497d24f --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/ActionBar.java @@ -0,0 +1,947 @@ +/* + * 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 new file mode 100644 index 00000000..9cb57e95 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockActivity.java @@ -0,0 +1,259 @@ +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 new file mode 100644 index 00000000..a7c856bf --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockDialogFragment.java @@ -0,0 +1,68 @@ +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 new file mode 100644 index 00000000..078f9b0c --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockExpandableListActivity.java @@ -0,0 +1,259 @@ +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 new file mode 100644 index 00000000..0f24e9c8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragment.java @@ -0,0 +1,68 @@ +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 new file mode 100644 index 00000000..5cd13ba7 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockFragmentActivity.java @@ -0,0 +1,292 @@ +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 new file mode 100644 index 00000000..00c00fee --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListActivity.java @@ -0,0 +1,259 @@ +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 new file mode 100644 index 00000000..13ca3c49 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockListFragment.java @@ -0,0 +1,68 @@ +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 new file mode 100644 index 00000000..4f80be51 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/app/SherlockPreferenceActivity.java @@ -0,0 +1,259 @@ +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 new file mode 100644 index 00000000..05353d28 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockCompat.java @@ -0,0 +1,1207 @@ +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 new file mode 100644 index 00000000..9afca185 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ActionBarSherlockNative.java @@ -0,0 +1,328 @@ +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 new file mode 100644 index 00000000..8e1efe8c --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/ResourcesCompat.java @@ -0,0 +1,95 @@ +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 new file mode 100644 index 00000000..6ae0402c --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarImpl.java @@ -0,0 +1,1026 @@ +/* + * 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 new file mode 100644 index 00000000..e390ea42 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/app/ActionBarWrapper.java @@ -0,0 +1,468 @@ +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 new file mode 100644 index 00000000..2caf5b4a --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Animator.java @@ -0,0 +1,278 @@ +/* + * 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 new file mode 100644 index 00000000..02ddff48 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorListenerAdapter.java @@ -0,0 +1,54 @@ +/* + * 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 new file mode 100644 index 00000000..3231080c --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/AnimatorSet.java @@ -0,0 +1,1111 @@ +/* + * 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 new file mode 100644 index 00000000..e4101936 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java @@ -0,0 +1,42 @@ +/* + * 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 new file mode 100644 index 00000000..6d9dafa7 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatKeyframeSet.java @@ -0,0 +1,136 @@ +/* + * 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 new file mode 100644 index 00000000..ed5e79ec --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntEvaluator.java @@ -0,0 +1,42 @@ +/* + * 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 new file mode 100644 index 00000000..e9215e7f --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/IntKeyframeSet.java @@ -0,0 +1,135 @@ +/* + * 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 new file mode 100644 index 00000000..ab76fa7f --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/Keyframe.java @@ -0,0 +1,361 @@ +/* + * 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 new file mode 100644 index 00000000..a71e1ad3 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/KeyframeSet.java @@ -0,0 +1,227 @@ +/* + * 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 new file mode 100644 index 00000000..21d15c02 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ObjectAnimator.java @@ -0,0 +1,491 @@ +/* + * 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 new file mode 100644 index 00000000..84f7504a --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java @@ -0,0 +1,1012 @@ +/* + * 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 new file mode 100644 index 00000000..0ea31924 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/TypeEvaluator.java @@ -0,0 +1,44 @@ +/* + * 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 new file mode 100644 index 00000000..d8a12c68 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/ValueAnimator.java @@ -0,0 +1,1265 @@ +/* + * 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 new file mode 100644 index 00000000..7b830b9c --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/NineViewGroup.java @@ -0,0 +1,79 @@ +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 new file mode 100644 index 00000000..067d0494 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/view/animation/AnimatorProxy.java @@ -0,0 +1,212 @@ +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 new file mode 100644 index 00000000..2c428e90 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineFrameLayout.java @@ -0,0 +1,65 @@ +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 new file mode 100644 index 00000000..129b5aaa --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineHorizontalScrollView.java @@ -0,0 +1,41 @@ +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 new file mode 100644 index 00000000..a670b1f6 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/widget/NineLinearLayout.java @@ -0,0 +1,65 @@ +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 new file mode 100644 index 00000000..b136d50f --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/ActionProviderWrapper.java @@ -0,0 +1,40 @@ +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 new file mode 100644 index 00000000..0a87bd3f --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/StandaloneActionMode.java @@ -0,0 +1,148 @@ +/* + * 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 new file mode 100644 index 00000000..7d45e81b --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_HasStateListenerSupport.java @@ -0,0 +1,6 @@ +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 new file mode 100644 index 00000000..3869d329 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/View_OnAttachStateChangeListener.java @@ -0,0 +1,8 @@ +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 new file mode 100644 index 00000000..0354ad1a --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenu.java @@ -0,0 +1,264 @@ +/* + * 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 new file mode 100644 index 00000000..510b9748 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItem.java @@ -0,0 +1,278 @@ +/* + * 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 new file mode 100644 index 00000000..dcb50f36 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuItemView.java @@ -0,0 +1,295 @@ +/* + * 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 new file mode 100644 index 00000000..6f568c69 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.java @@ -0,0 +1,721 @@ +/* + * 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 new file mode 100644 index 00000000..e090677a --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuView.java @@ -0,0 +1,572 @@ +/* + * 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 new file mode 100644 index 00000000..6da26f2a --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/BaseMenuPresenter.java @@ -0,0 +1,231 @@ +/* + * 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 new file mode 100644 index 00000000..ac25c373 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ListMenuItemView.java @@ -0,0 +1,278 @@ +/* + * 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 new file mode 100644 index 00000000..179b8f03 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuBuilder.java @@ -0,0 +1,1335 @@ +/* + * 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 new file mode 100644 index 00000000..f5359fb4 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemImpl.java @@ -0,0 +1,647 @@ +/* + * 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 new file mode 100644 index 00000000..907a7aa0 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuItemWrapper.java @@ -0,0 +1,292 @@ +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 new file mode 100644 index 00000000..f030de31 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPopupHelper.java @@ -0,0 +1,376 @@ +/* + * 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 new file mode 100644 index 00000000..c3f35472 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuPresenter.java @@ -0,0 +1,148 @@ +/* + * 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 new file mode 100644 index 00000000..323ba2d8 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuView.java @@ -0,0 +1,120 @@ +/* + * 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 new file mode 100644 index 00000000..64fc4aea --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/MenuWrapper.java @@ -0,0 +1,180 @@ +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 new file mode 100644 index 00000000..6679cf38 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuBuilder.java @@ -0,0 +1,134 @@ +/* + * 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 new file mode 100644 index 00000000..7d307acb --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/SubMenuWrapper.java @@ -0,0 +1,72 @@ +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 new file mode 100644 index 00000000..3a4a4467 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/AbsActionBarView.java @@ -0,0 +1,291 @@ +/* + * 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 new file mode 100644 index 00000000..5e5aa286 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContainer.java @@ -0,0 +1,245 @@ +/* + * 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 new file mode 100644 index 00000000..9ec250f3 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarContextView.java @@ -0,0 +1,518 @@ +/* + * 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 new file mode 100644 index 00000000..4636de17 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ActionBarView.java @@ -0,0 +1,1548 @@ +/* + * 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 new file mode 100644 index 00000000..fa3698f3 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingButton.java @@ -0,0 +1,40 @@ +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 new file mode 100644 index 00000000..673ec554 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/CapitalizingTextView.java @@ -0,0 +1,44 @@ +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 new file mode 100644 index 00000000..ad1b4f0a --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/FakeDialogPhoneWindow.java @@ -0,0 +1,64 @@ +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 new file mode 100644 index 00000000..ce0cb3bc --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAbsSpinner.java @@ -0,0 +1,479 @@ +/* + * 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 new file mode 100644 index 00000000..c786dc5c --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsAdapterView.java @@ -0,0 +1,1160 @@ +/* + * 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 new file mode 100644 index 00000000..1b4463a5 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsLinearLayout.java @@ -0,0 +1,272 @@ +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 new file mode 100644 index 00000000..d13c6cea --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsListPopupWindow.java @@ -0,0 +1,644 @@ +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 new file mode 100644 index 00000000..1c02d4ac --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsProgressBar.java @@ -0,0 +1,1193 @@ +/* + * 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 new file mode 100644 index 00000000..038d1e03 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsSpinner.java @@ -0,0 +1,703 @@ +/* + * 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 new file mode 100644 index 00000000..a7185d08 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java @@ -0,0 +1,21 @@ +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 new file mode 100644 index 00000000..1a532e06 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java @@ -0,0 +1,545 @@ +/* + * 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 new file mode 100644 index 00000000..81b4cd4d --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionMode.java @@ -0,0 +1,224 @@ +/* + * 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 new file mode 100644 index 00000000..ae7cb1fe --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/ActionProvider.java @@ -0,0 +1,170 @@ +/* + * 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 new file mode 100644 index 00000000..43281b01 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/CollapsibleActionView.java @@ -0,0 +1,39 @@ +/* + * 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 new file mode 100644 index 00000000..951f4cce --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Menu.java @@ -0,0 +1,447 @@ +/* + * 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 new file mode 100644 index 00000000..96945974 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java @@ -0,0 +1,472 @@ +/* + * 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 new file mode 100644 index 00000000..7fc3aa43 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java @@ -0,0 +1,598 @@ +/* + * 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 new file mode 100644 index 00000000..397fd1c2 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/SubMenu.java @@ -0,0 +1,110 @@ +/* + * 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 new file mode 100644 index 00000000..a340a429 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/view/Window.java @@ -0,0 +1,65 @@ +/* + * 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 new file mode 100644 index 00000000..37920747 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java @@ -0,0 +1,1131 @@ +/* + * 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 new file mode 100644 index 00000000..da13bc99 --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java @@ -0,0 +1,818 @@ +/* + * 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 new file mode 100644 index 00000000..83e9f0ca --- /dev/null +++ b/android-libraries/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java @@ -0,0 +1,316 @@ +/* + * 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 new file mode 100644 index 00000000..a4f1e405 --- /dev/null +++ b/android-libraries/TreeViewList/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/android-libraries/TreeViewList/.project b/android-libraries/TreeViewList/.project new file mode 100644 index 00000000..c9d4fdac --- /dev/null +++ b/android-libraries/TreeViewList/.project @@ -0,0 +1,33 @@ + + + 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 new file mode 100644 index 00000000..28a7fe08 --- /dev/null +++ b/android-libraries/TreeViewList/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + \ 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 new file mode 100644 index 00000000..2b846618 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter$1.class 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 new file mode 100644 index 00000000..40535baa Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/AbstractTreeViewAdapter.class 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 new file mode 100644 index 00000000..77562f42 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/BuildConfig.class 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 new file mode 100644 index 00000000..c2a6124d Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeNode.class 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 new file mode 100644 index 00000000..791ae79a Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/InMemoryTreeStateManager.class 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 new file mode 100644 index 00000000..35af40c6 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeAlreadyInTreeException.class 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 new file mode 100644 index 00000000..a9813987 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/NodeNotInTreeException.class 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 new file mode 100644 index 00000000..1a7b40c1 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$attr.class 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 new file mode 100644 index 00000000..f266770c Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$drawable.class 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 new file mode 100644 index 00000000..7f119578 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$id.class 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 new file mode 100644 index 00000000..a13978fa Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$layout.class 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 new file mode 100644 index 00000000..4a475b27 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$style.class 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 new file mode 100644 index 00000000..a992b85f Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R$styleable.class 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 new file mode 100644 index 00000000..ef23d5e4 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/R.class 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 new file mode 100644 index 00000000..4ddc77cc Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeBuilder.class 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 new file mode 100644 index 00000000..d2e71937 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeConfigurationException.class 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 new file mode 100644 index 00000000..683896ce Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeNodeInfo.class 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 new file mode 100644 index 00000000..f3beab57 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeStateManager.class 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 new file mode 100644 index 00000000..2b9baacc Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList$1.class 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 new file mode 100644 index 00000000..53039993 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/TreeViewList.class 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 new file mode 100644 index 00000000..bdd09ce9 --- /dev/null +++ b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/overview.html @@ -0,0 +1,24 @@ + + +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 new file mode 100644 index 00000000..d0a12754 Binary files /dev/null and b/android-libraries/TreeViewList/bin/classes/pl/polidea/treeview/package-info.class differ diff --git a/android-libraries/TreeViewList/bin/jarlist.cache b/android-libraries/TreeViewList/bin/jarlist.cache new file mode 100644 index 00000000..1b5ec3f9 --- /dev/null +++ b/android-libraries/TreeViewList/bin/jarlist.cache @@ -0,0 +1,3 @@ +# 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 new file mode 100644 index 00000000..84ca818c Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-hdpi/collapsed.png differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-hdpi/expanded.png b/android-libraries/TreeViewList/bin/res/drawable-hdpi/expanded.png new file mode 100644 index 00000000..27612315 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-hdpi/expanded.png 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 new file mode 100644 index 00000000..882eb148 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-hdpi/ic_launcher.png differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-ldpi/collapsed.png b/android-libraries/TreeViewList/bin/res/drawable-ldpi/collapsed.png new file mode 100644 index 00000000..f9c06f4f Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-ldpi/collapsed.png differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-ldpi/expanded.png b/android-libraries/TreeViewList/bin/res/drawable-ldpi/expanded.png new file mode 100644 index 00000000..7ce50746 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-ldpi/expanded.png 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 new file mode 100644 index 00000000..18689f65 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-ldpi/ic_launcher.png differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-mdpi/collapsed.png b/android-libraries/TreeViewList/bin/res/drawable-mdpi/collapsed.png new file mode 100644 index 00000000..d2e87746 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-mdpi/collapsed.png differ diff --git a/android-libraries/TreeViewList/bin/res/drawable-mdpi/expanded.png b/android-libraries/TreeViewList/bin/res/drawable-mdpi/expanded.png new file mode 100644 index 00000000..4c5ad0f9 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-mdpi/expanded.png 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 new file mode 100644 index 00000000..02e96b96 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable-mdpi/ic_launcher.png 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 new file mode 100644 index 00000000..6bc40f6d Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_disabled.9.png 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 new file mode 100644 index 00000000..38c67542 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_focus.9.png 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 new file mode 100644 index 00000000..8d2894e1 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_longpress.9.png 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 new file mode 100644 index 00000000..900623e1 Binary files /dev/null and b/android-libraries/TreeViewList/bin/res/drawable/list_selector_background_pressed.9.png differ diff --git a/android-libraries/TreeViewList/bin/treeviewlist.jar b/android-libraries/TreeViewList/bin/treeviewlist.jar new file mode 100644 index 00000000..3445f56d Binary files /dev/null and b/android-libraries/TreeViewList/bin/treeviewlist.jar differ diff --git a/android-libraries/TreeViewList/gen/pl/polidea/treeview/BuildConfig.java b/android-libraries/TreeViewList/gen/pl/polidea/treeview/BuildConfig.java new file mode 100644 index 00000000..18bc91b3 --- /dev/null +++ b/android-libraries/TreeViewList/gen/pl/polidea/treeview/BuildConfig.java @@ -0,0 +1,6 @@ +/** 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 new file mode 100644 index 00000000..3ef9b354 --- /dev/null +++ b/android-libraries/TreeViewList/gen/pl/polidea/treeview/R.java @@ -0,0 +1,276 @@ +/* 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 new file mode 100644 index 00000000..b1cdf17b --- /dev/null +++ b/android-libraries/TreeViewList/proguard.cfg @@ -0,0 +1,40 @@ +-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 new file mode 100644 index 00000000..5fa344c9 --- /dev/null +++ b/android-libraries/TreeViewList/project.properties @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 00000000..c1e1f3d5 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-hdpi/collapsed.png differ diff --git a/android-libraries/TreeViewList/res/drawable-hdpi/expanded.png b/android-libraries/TreeViewList/res/drawable-hdpi/expanded.png new file mode 100644 index 00000000..cec254aa Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-hdpi/expanded.png differ diff --git a/android-libraries/TreeViewList/res/drawable-hdpi/ic_launcher.png b/android-libraries/TreeViewList/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 00000000..8074c4c5 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-hdpi/ic_launcher.png differ diff --git a/android-libraries/TreeViewList/res/drawable-ldpi/collapsed.png b/android-libraries/TreeViewList/res/drawable-ldpi/collapsed.png new file mode 100644 index 00000000..a52e846a Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-ldpi/collapsed.png differ diff --git a/android-libraries/TreeViewList/res/drawable-ldpi/expanded.png b/android-libraries/TreeViewList/res/drawable-ldpi/expanded.png new file mode 100644 index 00000000..d8b7ab89 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-ldpi/expanded.png differ diff --git a/android-libraries/TreeViewList/res/drawable-ldpi/ic_launcher.png b/android-libraries/TreeViewList/res/drawable-ldpi/ic_launcher.png new file mode 100644 index 00000000..1095584e Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-ldpi/ic_launcher.png differ diff --git a/android-libraries/TreeViewList/res/drawable-mdpi/collapsed.png b/android-libraries/TreeViewList/res/drawable-mdpi/collapsed.png new file mode 100644 index 00000000..b2355514 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-mdpi/collapsed.png differ diff --git a/android-libraries/TreeViewList/res/drawable-mdpi/expanded.png b/android-libraries/TreeViewList/res/drawable-mdpi/expanded.png new file mode 100644 index 00000000..f7377cb3 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-mdpi/expanded.png differ diff --git a/android-libraries/TreeViewList/res/drawable-mdpi/ic_launcher.png b/android-libraries/TreeViewList/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 00000000..a07c69fa Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable-mdpi/ic_launcher.png differ diff --git a/android-libraries/TreeViewList/res/drawable/divider.xml b/android-libraries/TreeViewList/res/drawable/divider.xml new file mode 100644 index 00000000..5f379499 --- /dev/null +++ b/android-libraries/TreeViewList/res/drawable/divider.xml @@ -0,0 +1,6 @@ + + diff --git a/android-libraries/TreeViewList/res/drawable/list_selector_background.xml b/android-libraries/TreeViewList/res/drawable/list_selector_background.xml new file mode 100644 index 00000000..2b21b0c1 --- /dev/null +++ b/android-libraries/TreeViewList/res/drawable/list_selector_background.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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 new file mode 100644 index 00000000..bf970b05 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable/list_selector_background_disabled.9.png 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 new file mode 100644 index 00000000..c3e24158 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable/list_selector_background_focus.9.png 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 new file mode 100644 index 00000000..5cbb251a Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable/list_selector_background_longpress.9.png 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 new file mode 100644 index 00000000..02b4e9a5 Binary files /dev/null and b/android-libraries/TreeViewList/res/drawable/list_selector_background_pressed.9.png 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 new file mode 100644 index 00000000..0dec1335 --- /dev/null +++ b/android-libraries/TreeViewList/res/drawable/list_selector_background_transition.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/android-libraries/TreeViewList/res/layout/tree_list_item_wrapper.xml b/android-libraries/TreeViewList/res/layout/tree_list_item_wrapper.xml new file mode 100644 index 00000000..9512a0c8 --- /dev/null +++ b/android-libraries/TreeViewList/res/layout/tree_list_item_wrapper.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/android-libraries/TreeViewList/res/values/attrs.xml b/android-libraries/TreeViewList/res/values/attrs.xml new file mode 100644 index 00000000..30060a4c --- /dev/null +++ b/android-libraries/TreeViewList/res/values/attrs.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android-libraries/TreeViewList/res/values/styles.xml b/android-libraries/TreeViewList/res/values/styles.xml new file mode 100644 index 00000000..005c6007 --- /dev/null +++ b/android-libraries/TreeViewList/res/values/styles.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android-libraries/TreeViewList/src/pl/polidea/treeview/AbstractTreeViewAdapter.java b/android-libraries/TreeViewList/src/pl/polidea/treeview/AbstractTreeViewAdapter.java new file mode 100644 index 00000000..7f2b366a --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/AbstractTreeViewAdapter.java @@ -0,0 +1,315 @@ +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 new file mode 100644 index 00000000..6035369f --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeNode.java @@ -0,0 +1,116 @@ +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 new file mode 100644 index 00000000..bae675bf --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/InMemoryTreeStateManager.java @@ -0,0 +1,374 @@ +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 new file mode 100644 index 00000000..680d0266 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeAlreadyInTreeException.java @@ -0,0 +1,14 @@ +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 new file mode 100644 index 00000000..f20450e1 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/NodeNotInTreeException.java @@ -0,0 +1,15 @@ +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 new file mode 100644 index 00000000..13b499c4 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeBuilder.java @@ -0,0 +1,126 @@ +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 new file mode 100644 index 00000000..1fa72e04 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeConfigurationException.java @@ -0,0 +1,15 @@ +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 new file mode 100644 index 00000000..32d18dd4 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeNodeInfo.java @@ -0,0 +1,69 @@ +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 new file mode 100644 index 00000000..781b70e5 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeStateManager.java @@ -0,0 +1,193 @@ +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 new file mode 100644 index 00000000..fb48ab5c --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/TreeViewList.java @@ -0,0 +1,198 @@ +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 new file mode 100644 index 00000000..bdd09ce9 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/overview.html @@ -0,0 +1,24 @@ + + +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 new file mode 100644 index 00000000..a622e091 --- /dev/null +++ b/android-libraries/TreeViewList/src/pl/polidea/treeview/package-info.java @@ -0,0 +1,4 @@ +/** + * 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 new file mode 100644 index 00000000..a4f1e405 --- /dev/null +++ b/android-libraries/achartengine/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/android-libraries/achartengine/.project b/android-libraries/achartengine/.project new file mode 100644 index 00000000..fb1c7567 --- /dev/null +++ b/android-libraries/achartengine/.project @@ -0,0 +1,33 @@ + + + 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 new file mode 100644 index 00000000..083e05fc --- /dev/null +++ b/android-libraries/achartengine/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + \ 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 new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/android-libraries/achartengine/extra/LICENSE-2.0.txt @@ -0,0 +1,202 @@ + + 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 new file mode 100644 index 00000000..337e8f37 --- /dev/null +++ b/android-libraries/achartengine/project.properties @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 00000000..301f1a8f --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/ChartFactory.java @@ -0,0 +1,708 @@ +/** + * 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 new file mode 100644 index 00000000..56c190ae --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/GraphicalActivity.java @@ -0,0 +1,48 @@ +/** + * 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 new file mode 100644 index 00000000..e9aebff5 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/GraphicalView.java @@ -0,0 +1,337 @@ +/** + * 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 new file mode 100644 index 00000000..4debe964 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/ITouchHandler.java @@ -0,0 +1,63 @@ +/** + * 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 new file mode 100644 index 00000000..a06d05d6 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/TouchHandler.java @@ -0,0 +1,204 @@ +/** + * 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 new file mode 100644 index 00000000..38b4f227 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/TouchHandlerOld.java @@ -0,0 +1,137 @@ +/** + * 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 new file mode 100644 index 00000000..f99a5c2a --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/AbstractChart.java @@ -0,0 +1,475 @@ +/** + * 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 new file mode 100644 index 00000000..d5d0fb23 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/BarChart.java @@ -0,0 +1,329 @@ +/** + * 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 new file mode 100644 index 00000000..f3125713 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/BubbleChart.java @@ -0,0 +1,146 @@ +/** + * 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 new file mode 100644 index 00000000..d2d306ca --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/ClickableArea.java @@ -0,0 +1,44 @@ +/** + * 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 new file mode 100644 index 00000000..d684c3a2 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/CombinedXYChart.java @@ -0,0 +1,177 @@ +/** + * 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 new file mode 100644 index 00000000..2011318f --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/CubicLineChart.java @@ -0,0 +1,120 @@ +/** + * 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 new file mode 100644 index 00000000..ebfcbbb1 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/DialChart.java @@ -0,0 +1,236 @@ +/** + * 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 new file mode 100644 index 00000000..ad67b076 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/DoughnutChart.java @@ -0,0 +1,162 @@ +/** + * 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 new file mode 100644 index 00000000..2c458986 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/LineChart.java @@ -0,0 +1,175 @@ +/** + * 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 new file mode 100644 index 00000000..d656a95e --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/PieChart.java @@ -0,0 +1,136 @@ +/** + * 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 new file mode 100644 index 00000000..6e4b7150 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/PieMapper.java @@ -0,0 +1,139 @@ +/** + * 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 new file mode 100644 index 00000000..0fb0a2e4 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/PieSegment.java @@ -0,0 +1,70 @@ +/** + * 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 new file mode 100644 index 00000000..29a2311a --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/PointStyle.java @@ -0,0 +1,90 @@ +/** + * 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 new file mode 100644 index 00000000..105f509a --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/RangeBarChart.java @@ -0,0 +1,145 @@ +/** + * 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 new file mode 100644 index 00000000..4da4f006 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/RangeStackedBarChart.java @@ -0,0 +1,29 @@ +/** + * 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 new file mode 100644 index 00000000..1a2121d4 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/RoundChart.java @@ -0,0 +1,143 @@ +/** + * 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 new file mode 100644 index 00000000..1d3b2a18 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/ScatterChart.java @@ -0,0 +1,266 @@ +/** + * 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 new file mode 100644 index 00000000..ba201de7 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/TimeChart.java @@ -0,0 +1,226 @@ +/** + * 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 new file mode 100644 index 00000000..6b531d60 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/XYChart.java @@ -0,0 +1,905 @@ +/** + * 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 new file mode 100644 index 00000000..2c5fbec1 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/chart/package.html @@ -0,0 +1,6 @@ + +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 new file mode 100644 index 00000000..8265f278 Binary files /dev/null and b/android-libraries/achartengine/src/org/achartengine/image/zoom-1.png 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 new file mode 100644 index 00000000..1ac4864d Binary files /dev/null and b/android-libraries/achartengine/src/org/achartengine/image/zoom_in.png 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 new file mode 100644 index 00000000..d67a87de Binary files /dev/null and b/android-libraries/achartengine/src/org/achartengine/image/zoom_out.png differ diff --git a/android-libraries/achartengine/src/org/achartengine/model/CategorySeries.java b/android-libraries/achartengine/src/org/achartengine/model/CategorySeries.java new file mode 100644 index 00000000..ae31c7dd --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/CategorySeries.java @@ -0,0 +1,143 @@ +/** + * 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 new file mode 100644 index 00000000..992db4c1 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/MultipleCategorySeries.java @@ -0,0 +1,145 @@ +/** + * 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 new file mode 100644 index 00000000..4d2767cf --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/Point.java @@ -0,0 +1,52 @@ +/** + * 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 new file mode 100644 index 00000000..c004fa10 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/RangeCategorySeries.java @@ -0,0 +1,111 @@ +/** + * 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 new file mode 100644 index 00000000..4319c742 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/SeriesSelection.java @@ -0,0 +1,49 @@ +/** + * 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 new file mode 100644 index 00000000..6b9a18e5 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/TimeSeries.java @@ -0,0 +1,43 @@ +/** + * 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 new file mode 100644 index 00000000..6ac6a6de --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/XYMultipleSeriesDataset.java @@ -0,0 +1,94 @@ +/** + * 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 new file mode 100644 index 00000000..56063b77 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/XYSeries.java @@ -0,0 +1,255 @@ +/** + * 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 new file mode 100644 index 00000000..81aff28b --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/XYValueSeries.java @@ -0,0 +1,139 @@ +/** + * 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 new file mode 100644 index 00000000..6135d29c --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/model/package.html @@ -0,0 +1,6 @@ + +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 new file mode 100644 index 00000000..b26cf259 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/package.html @@ -0,0 +1,6 @@ + +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 new file mode 100644 index 00000000..3ac93d54 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/BasicStroke.java @@ -0,0 +1,107 @@ +/** + * 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 new file mode 100644 index 00000000..4dbb2549 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/DefaultRenderer.java @@ -0,0 +1,750 @@ +/** + * 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 new file mode 100644 index 00000000..1ed84619 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/DialRenderer.java @@ -0,0 +1,196 @@ +/** + * 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 new file mode 100644 index 00000000..0763fc58 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/SimpleSeriesRenderer.java @@ -0,0 +1,235 @@ +/** + * 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 new file mode 100644 index 00000000..64b34211 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/XYMultipleSeriesRenderer.java @@ -0,0 +1,1101 @@ +/** + * 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 new file mode 100644 index 00000000..42e4808e --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/XYSeriesRenderer.java @@ -0,0 +1,128 @@ +/** + * 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 new file mode 100644 index 00000000..c9db0a45 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/renderer/package.html @@ -0,0 +1,6 @@ + +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 new file mode 100644 index 00000000..99841ed7 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/AbstractTool.java @@ -0,0 +1,111 @@ +/** + * 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 new file mode 100644 index 00000000..92f67b84 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/FitZoom.java @@ -0,0 +1,78 @@ +/** + * 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 new file mode 100644 index 00000000..2d4ea28e --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/Pan.java @@ -0,0 +1,163 @@ +/** + * 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 new file mode 100644 index 00000000..d3d136c0 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/PanListener.java @@ -0,0 +1,28 @@ +/** + * 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 new file mode 100644 index 00000000..0abee92c --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/Zoom.java @@ -0,0 +1,189 @@ +/** + * 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 new file mode 100644 index 00000000..bd8fb686 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/ZoomEvent.java @@ -0,0 +1,56 @@ +/** + * 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 new file mode 100644 index 00000000..4827483e --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/tools/ZoomListener.java @@ -0,0 +1,33 @@ +/** + * 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 new file mode 100644 index 00000000..f9572622 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/util/IndexXYMap.java @@ -0,0 +1,108 @@ +/** + * 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 new file mode 100644 index 00000000..f5b893bf --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/util/MathHelper.java @@ -0,0 +1,174 @@ +/** + * 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 new file mode 100644 index 00000000..53761a4d --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/util/XYEntry.java @@ -0,0 +1,45 @@ +/** + * 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 new file mode 100644 index 00000000..da92e913 --- /dev/null +++ b/android-libraries/achartengine/src/org/achartengine/util/package.html @@ -0,0 +1,6 @@ + +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 index b1868ee8..07677d89 100644 --- a/android/.classpath +++ b/android/.classpath @@ -2,11 +2,10 @@ - + - diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml index 07a6582f..473dfeb2 100644 --- a/android/AndroidManifest.xml +++ b/android/AndroidManifest.xml @@ -5,7 +5,7 @@ android:versionName="1.0" > @@ -13,30 +13,24 @@ + android:theme="@style/AppTheme.NoActionBar" > - - - @@ -62,7 +56,9 @@ android:scheme="file" /> - + @@ -73,12 +69,18 @@ - + android:theme="@style/AppTheme.NoActionBar" /> + - + android:theme="@style/AppTheme.NoActionBar" /> + + + \ No newline at end of file diff --git a/android/project.properties b/android/project.properties index 8da376af..8202ea55 100644 --- a/android/project.properties +++ b/android/project.properties @@ -9,3 +9,6 @@ # 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/actionbar_shadow.9.png b/android/res/drawable-hdpi/actionbar_shadow.9.png deleted file mode 100644 index 3c80a3fc..00000000 Binary files a/android/res/drawable-hdpi/actionbar_shadow.9.png and /dev/null differ diff --git a/android/res/drawable-hdpi/collapsed.png b/android/res/drawable-hdpi/collapsed.png deleted file mode 100644 index c1e1f3d5..00000000 Binary files a/android/res/drawable-hdpi/collapsed.png and /dev/null differ diff --git a/android/res/drawable-hdpi/expanded.png b/android/res/drawable-hdpi/expanded.png deleted file mode 100644 index cec254aa..00000000 Binary files a/android/res/drawable-hdpi/expanded.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 new file mode 100644 index 00000000..444e8a5e Binary files /dev/null and b/android/res/drawable-hdpi/ic_menu_add.png differ diff --git a/android/res/drawable-hdpi/ic_menu_archive.png b/android/res/drawable-hdpi/ic_menu_archive.png new file mode 100644 index 00000000..e2d9bc1a Binary files /dev/null and b/android/res/drawable-hdpi/ic_menu_archive.png differ diff --git a/android/res/drawable-hdpi/ic_menu_info_details.png b/android/res/drawable-hdpi/ic_menu_info_details.png new file mode 100644 index 00000000..6a7a1e94 Binary files /dev/null and b/android/res/drawable-hdpi/ic_menu_info_details.png differ diff --git a/android/res/drawable-hdpi/ic_menu_preferences.png b/android/res/drawable-hdpi/ic_menu_preferences.png new file mode 100644 index 00000000..5321f828 Binary files /dev/null and b/android/res/drawable-hdpi/ic_menu_preferences.png differ diff --git a/android/res/drawable-hdpi/ic_menu_save.png b/android/res/drawable-hdpi/ic_menu_save.png new file mode 100644 index 00000000..36fc7f4d Binary files /dev/null and b/android/res/drawable-hdpi/ic_menu_save.png differ diff --git a/android/res/drawable-hdpi/ic_menu_search.png b/android/res/drawable-hdpi/ic_menu_search.png new file mode 100644 index 00000000..a7f9bbee Binary files /dev/null and b/android/res/drawable-hdpi/ic_menu_search.png differ diff --git a/android/res/drawable-hdpi/or_launcher.png b/android/res/drawable-hdpi/or_launcher.png new file mode 100644 index 00000000..22c526f3 Binary files /dev/null and b/android/res/drawable-hdpi/or_launcher.png differ diff --git a/android/res/drawable-ldpi/collapsed.png b/android/res/drawable-ldpi/collapsed.png deleted file mode 100644 index a52e846a..00000000 Binary files a/android/res/drawable-ldpi/collapsed.png and /dev/null differ diff --git a/android/res/drawable-ldpi/expanded.png b/android/res/drawable-ldpi/expanded.png deleted file mode 100644 index d8b7ab89..00000000 Binary files a/android/res/drawable-ldpi/expanded.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 new file mode 100644 index 00000000..89620af8 Binary files /dev/null and b/android/res/drawable-ldpi/ic_menu_add.png differ diff --git a/android/res/drawable-ldpi/ic_menu_archive.png b/android/res/drawable-ldpi/ic_menu_archive.png new file mode 100644 index 00000000..719ecd85 Binary files /dev/null and b/android/res/drawable-ldpi/ic_menu_archive.png differ diff --git a/android/res/drawable-ldpi/ic_menu_info_details.png b/android/res/drawable-ldpi/ic_menu_info_details.png new file mode 100644 index 00000000..55c57d5c Binary files /dev/null and b/android/res/drawable-ldpi/ic_menu_info_details.png differ diff --git a/android/res/drawable-ldpi/ic_menu_preferences.png b/android/res/drawable-ldpi/ic_menu_preferences.png new file mode 100644 index 00000000..efc2f3e4 Binary files /dev/null and b/android/res/drawable-ldpi/ic_menu_preferences.png differ diff --git a/android/res/drawable-ldpi/ic_menu_save.png b/android/res/drawable-ldpi/ic_menu_save.png new file mode 100644 index 00000000..ac053b41 Binary files /dev/null and b/android/res/drawable-ldpi/ic_menu_save.png differ diff --git a/android/res/drawable-ldpi/ic_menu_search.png b/android/res/drawable-ldpi/ic_menu_search.png new file mode 100644 index 00000000..1d95408c Binary files /dev/null and b/android/res/drawable-ldpi/ic_menu_search.png differ diff --git a/android/res/drawable-ldpi/or_launcher.png b/android/res/drawable-ldpi/or_launcher.png new file mode 100644 index 00000000..5f7a0b2a Binary files /dev/null and b/android/res/drawable-ldpi/or_launcher.png differ diff --git a/android/res/drawable-mdpi/actionbar_shadow.9.png b/android/res/drawable-mdpi/actionbar_shadow.9.png deleted file mode 100644 index cae1778f..00000000 Binary files a/android/res/drawable-mdpi/actionbar_shadow.9.png and /dev/null differ diff --git a/android/res/drawable-mdpi/collapsed.png b/android/res/drawable-mdpi/collapsed.png deleted file mode 100644 index b2355514..00000000 Binary files a/android/res/drawable-mdpi/collapsed.png and /dev/null differ diff --git a/android/res/drawable-mdpi/expanded.png b/android/res/drawable-mdpi/expanded.png deleted file mode 100644 index f7377cb3..00000000 Binary files a/android/res/drawable-mdpi/expanded.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_home_carat.png b/android/res/drawable-mdpi/ic_home_carat.png deleted file mode 100644 index 22dad56d..00000000 Binary files a/android/res/drawable-mdpi/ic_home_carat.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 new file mode 100644 index 00000000..361c7c46 Binary files /dev/null and b/android/res/drawable-mdpi/ic_menu_add.png differ diff --git a/android/res/drawable-mdpi/ic_menu_archive.png b/android/res/drawable-mdpi/ic_menu_archive.png new file mode 100644 index 00000000..49ac569d Binary files /dev/null and b/android/res/drawable-mdpi/ic_menu_archive.png differ diff --git a/android/res/drawable-mdpi/ic_menu_info_details.png b/android/res/drawable-mdpi/ic_menu_info_details.png new file mode 100644 index 00000000..18b15b5a Binary files /dev/null and b/android/res/drawable-mdpi/ic_menu_info_details.png differ diff --git a/android/res/drawable-mdpi/ic_menu_preferences.png b/android/res/drawable-mdpi/ic_menu_preferences.png new file mode 100644 index 00000000..ccc50e66 Binary files /dev/null and b/android/res/drawable-mdpi/ic_menu_preferences.png differ diff --git a/android/res/drawable-mdpi/ic_menu_save.png b/android/res/drawable-mdpi/ic_menu_save.png new file mode 100644 index 00000000..5f668644 Binary files /dev/null and b/android/res/drawable-mdpi/ic_menu_save.png differ diff --git a/android/res/drawable-mdpi/ic_menu_search.png b/android/res/drawable-mdpi/ic_menu_search.png new file mode 100644 index 00000000..5d3155e0 Binary files /dev/null and b/android/res/drawable-mdpi/ic_menu_search.png differ diff --git a/android/res/drawable-mdpi/or_launcher.png b/android/res/drawable-mdpi/or_launcher.png index 849b6f1f..36a91549 100644 Binary files a/android/res/drawable-mdpi/or_launcher.png and b/android/res/drawable-mdpi/or_launcher.png differ diff --git a/android/res/drawable-xhdpi/actionbar_shadow.9.png b/android/res/drawable-xhdpi/actionbar_shadow.9.png deleted file mode 100644 index 30778e3f..00000000 Binary files a/android/res/drawable-xhdpi/actionbar_shadow.9.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 new file mode 100644 index 00000000..7d498a96 Binary files /dev/null and b/android/res/drawable-xhdpi/ic_menu_add.png differ diff --git a/android/res/drawable-xhdpi/ic_menu_archive.png b/android/res/drawable-xhdpi/ic_menu_archive.png new file mode 100644 index 00000000..b1be9d5b Binary files /dev/null and b/android/res/drawable-xhdpi/ic_menu_archive.png differ diff --git a/android/res/drawable-xhdpi/ic_menu_info_details.png b/android/res/drawable-xhdpi/ic_menu_info_details.png new file mode 100644 index 00000000..24ea5437 Binary files /dev/null and b/android/res/drawable-xhdpi/ic_menu_info_details.png differ diff --git a/android/res/drawable-xhdpi/ic_menu_preferences.png b/android/res/drawable-xhdpi/ic_menu_preferences.png new file mode 100644 index 00000000..02cfbad0 Binary files /dev/null and b/android/res/drawable-xhdpi/ic_menu_preferences.png differ diff --git a/android/res/drawable-xhdpi/ic_menu_save.png b/android/res/drawable-xhdpi/ic_menu_save.png new file mode 100644 index 00000000..62a66d87 Binary files /dev/null and b/android/res/drawable-xhdpi/ic_menu_save.png differ diff --git a/android/res/drawable-xhdpi/ic_menu_search.png b/android/res/drawable-xhdpi/ic_menu_search.png new file mode 100644 index 00000000..5c18f9e8 Binary files /dev/null and b/android/res/drawable-xhdpi/ic_menu_search.png differ diff --git a/android/res/drawable-xhdpi/or_launcher.png b/android/res/drawable-xhdpi/or_launcher.png index 77464db0..f13148d2 100644 Binary files a/android/res/drawable-xhdpi/or_launcher.png and b/android/res/drawable-xhdpi/or_launcher.png differ diff --git a/android/res/drawable/actionbar_compat_item.xml b/android/res/drawable/actionbar_compat_item.xml deleted file mode 100644 index 4b3960cf..00000000 --- a/android/res/drawable/actionbar_compat_item.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - diff --git a/android/res/drawable/actionbar_compat_item_focused.xml b/android/res/drawable/actionbar_compat_item_focused.xml deleted file mode 100644 index 04811d33..00000000 --- a/android/res/drawable/actionbar_compat_item_focused.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - diff --git a/android/res/drawable/actionbar_compat_item_pressed.xml b/android/res/drawable/actionbar_compat_item_pressed.xml deleted file mode 100644 index 72ff4b4f..00000000 --- a/android/res/drawable/actionbar_compat_item_pressed.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - diff --git a/android/res/drawable/divider.xml b/android/res/drawable/divider.xml deleted file mode 100644 index 5f379499..00000000 --- a/android/res/drawable/divider.xml +++ /dev/null @@ -1,6 +0,0 @@ - - diff --git a/android/res/drawable/home_item.xml b/android/res/drawable/home_item.xml deleted file mode 100644 index 9afcd5a0..00000000 --- a/android/res/drawable/home_item.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/android/res/drawable/ic_menu_preferences.png b/android/res/drawable/ic_menu_preferences.png deleted file mode 100644 index b8e71412..00000000 Binary files a/android/res/drawable/ic_menu_preferences.png and /dev/null differ diff --git a/android/res/drawable/list_selector_background.xml b/android/res/drawable/list_selector_background.xml deleted file mode 100644 index 2b21b0c1..00000000 --- a/android/res/drawable/list_selector_background.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/android/res/drawable/list_selector_background_disabled.9.png b/android/res/drawable/list_selector_background_disabled.9.png deleted file mode 100644 index bf970b05..00000000 Binary files a/android/res/drawable/list_selector_background_disabled.9.png and /dev/null differ diff --git a/android/res/drawable/list_selector_background_focus.9.png b/android/res/drawable/list_selector_background_focus.9.png deleted file mode 100644 index c3e24158..00000000 Binary files a/android/res/drawable/list_selector_background_focus.9.png and /dev/null differ diff --git a/android/res/drawable/list_selector_background_longpress.9.png b/android/res/drawable/list_selector_background_longpress.9.png deleted file mode 100644 index 5cbb251a..00000000 Binary files a/android/res/drawable/list_selector_background_longpress.9.png and /dev/null differ diff --git a/android/res/drawable/list_selector_background_pressed.9.png b/android/res/drawable/list_selector_background_pressed.9.png deleted file mode 100644 index 02b4e9a5..00000000 Binary files a/android/res/drawable/list_selector_background_pressed.9.png and /dev/null differ diff --git a/android/res/drawable/list_selector_background_transition.xml b/android/res/drawable/list_selector_background_transition.xml deleted file mode 100644 index 0dec1335..00000000 --- a/android/res/drawable/list_selector_background_transition.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - diff --git a/android/res/drawable/simulation_state.xml b/android/res/drawable/simulation_state.xml new file mode 100644 index 00000000..28e59234 --- /dev/null +++ b/android/res/drawable/simulation_state.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/android/res/drawable/simulation_state_green.xml b/android/res/drawable/simulation_state_green.xml new file mode 100644 index 00000000..4ccef189 --- /dev/null +++ b/android/res/drawable/simulation_state_green.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/android/res/drawable/simulation_state_red.xml b/android/res/drawable/simulation_state_red.xml new file mode 100644 index 00000000..37c5b523 --- /dev/null +++ b/android/res/drawable/simulation_state_red.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/android/res/drawable/simulation_state_yellow.xml b/android/res/drawable/simulation_state_yellow.xml new file mode 100644 index 00000000..1d258478 --- /dev/null +++ b/android/res/drawable/simulation_state_yellow.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/android/res/layout-land/simulation_event_item.xml b/android/res/layout-land/simulation_event_item.xml new file mode 100644 index 00000000..726be698 --- /dev/null +++ b/android/res/layout-land/simulation_event_item.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/android/res/layout-large-land/motorbrowser.xml b/android/res/layout-large-land/motorbrowser.xml new file mode 100644 index 00000000..25a2a836 --- /dev/null +++ b/android/res/layout-large-land/motorbrowser.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/android/res/layout-large-land/openrocketviewer.xml b/android/res/layout-large-land/openrocketviewer.xml new file mode 100644 index 00000000..64816245 --- /dev/null +++ b/android/res/layout-large-land/openrocketviewer.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/android/res/layout-v11/actionbar_indeterminate_progress.xml b/android/res/layout-v11/actionbar_indeterminate_progress.xml deleted file mode 100644 index c05750e0..00000000 --- a/android/res/layout-v11/actionbar_indeterminate_progress.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - diff --git a/android/res/layout-xlarge-land/motorbrowser.xml b/android/res/layout-xlarge-land/motorbrowser.xml deleted file mode 100644 index 33c1237d..00000000 --- a/android/res/layout-xlarge-land/motorbrowser.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/android/res/layout-xlarge-land/openrocketviewer.xml b/android/res/layout-xlarge-land/openrocketviewer.xml deleted file mode 100644 index 64816245..00000000 --- a/android/res/layout-xlarge-land/openrocketviewer.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/android/res/layout/actionbar_compat.xml b/android/res/layout/actionbar_compat.xml deleted file mode 100644 index 7e504d91..00000000 --- a/android/res/layout/actionbar_compat.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - diff --git a/android/res/layout/component_list_item.xml b/android/res/layout/component_list_item.xml index 6956b2d0..7b12fc2d 100644 --- a/android/res/layout/component_list_item.xml +++ b/android/res/layout/component_list_item.xml @@ -3,11 +3,11 @@ android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" - padding="2dip" > + android:padding="2dip" >
+ * + * @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 new file mode 100644 index 00000000..f49f9481 --- /dev/null +++ b/core/src/de/congrace/exp4j/CustomFunction.java @@ -0,0 +1,90 @@ +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 new file mode 100644 index 00000000..0d70b0b0 --- /dev/null +++ b/core/src/de/congrace/exp4j/Example.java @@ -0,0 +1,77 @@ +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 new file mode 100644 index 00000000..8ecf1b5c --- /dev/null +++ b/core/src/de/congrace/exp4j/ExpressionBuilder.java @@ -0,0 +1,135 @@ +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 new file mode 100644 index 00000000..24b1109d --- /dev/null +++ b/core/src/de/congrace/exp4j/FunctionSeparatorToken.java @@ -0,0 +1,17 @@ +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 new file mode 100644 index 00000000..6bc620ce --- /dev/null +++ b/core/src/de/congrace/exp4j/FunctionToken.java @@ -0,0 +1,161 @@ +/* +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 new file mode 100644 index 00000000..9712bce3 --- /dev/null +++ b/core/src/de/congrace/exp4j/InfixTranslator.java @@ -0,0 +1,109 @@ +/* + 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 new file mode 100644 index 00000000..e3810db0 --- /dev/null +++ b/core/src/de/congrace/exp4j/InvalidCustomFunctionException.java @@ -0,0 +1,9 @@ +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 new file mode 100644 index 00000000..b765d451 --- /dev/null +++ b/core/src/de/congrace/exp4j/NumberToken.java @@ -0,0 +1,66 @@ +/* + 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 new file mode 100644 index 00000000..765f4508 --- /dev/null +++ b/core/src/de/congrace/exp4j/OperatorToken.java @@ -0,0 +1,243 @@ +/* + 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 new file mode 100644 index 00000000..ad8ab0f6 --- /dev/null +++ b/core/src/de/congrace/exp4j/ParenthesisToken.java @@ -0,0 +1,69 @@ +/* + 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 new file mode 100644 index 00000000..0bbcc142 --- /dev/null +++ b/core/src/de/congrace/exp4j/PostfixExpression.java @@ -0,0 +1,116 @@ +/* + 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 new file mode 100644 index 00000000..2ce4030a --- /dev/null +++ b/core/src/de/congrace/exp4j/Token.java @@ -0,0 +1,50 @@ +/* + 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 new file mode 100644 index 00000000..c2c99d97 --- /dev/null +++ b/core/src/de/congrace/exp4j/Tokenizer.java @@ -0,0 +1,223 @@ +/* + 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 new file mode 100644 index 00000000..ae350932 --- /dev/null +++ b/core/src/de/congrace/exp4j/UnknownFunctionException.java @@ -0,0 +1,37 @@ +/* + 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 new file mode 100644 index 00000000..fcbf7da2 --- /dev/null +++ b/core/src/de/congrace/exp4j/UnparsableExpressionException.java @@ -0,0 +1,47 @@ +/* + 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 new file mode 100644 index 00000000..0030e70b --- /dev/null +++ b/core/src/de/congrace/exp4j/Variable.java @@ -0,0 +1,107 @@ +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 new file mode 100644 index 00000000..f567006f --- /dev/null +++ b/core/src/de/congrace/exp4j/VariableSet.java @@ -0,0 +1,42 @@ +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 new file mode 100644 index 00000000..716ef2ee --- /dev/null +++ b/core/src/de/congrace/exp4j/VariableToken.java @@ -0,0 +1,47 @@ +/* + 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/Warning.java b/core/src/net/sf/openrocket/aerodynamics/Warning.java index 56c65a3a..363606d7 100644 --- a/core/src/net/sf/openrocket/aerodynamics/Warning.java +++ b/core/src/net/sf/openrocket/aerodynamics/Warning.java @@ -102,6 +102,7 @@ public abstract class Warning { private double length = Double.NaN; private double delay = Double.NaN; + @Override public String toString() { String str = "No motor with designation '" + designation + "'"; if (manufacturer != null) @@ -315,4 +316,13 @@ public abstract class Warning { //// 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/barrowman/FinSetCalc.java b/core/src/net/sf/openrocket/aerodynamics/barrowman/FinSetCalc.java index bd8ee75e..96abf7a6 100644 --- a/core/src/net/sf/openrocket/aerodynamics/barrowman/FinSetCalc.java +++ b/core/src/net/sf/openrocket/aerodynamics/barrowman/FinSetCalc.java @@ -163,7 +163,7 @@ public class FinSetCalc extends RocketComponentCalc { default: // Assume 75% efficiency cna *= 0.75; - warnings.add("Too many parallel fins"); + warnings.add(Warning.PARALLEL_FINS); break; } diff --git a/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java b/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java index 23178a33..458cbe19 100644 --- a/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java +++ b/core/src/net/sf/openrocket/aerodynamics/barrowman/SymmetricComponentCalc.java @@ -5,6 +5,7 @@ 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; @@ -140,7 +141,7 @@ public class SymmetricComponentCalc extends RocketComponentCalc { // Add warning on supersonic flight if (conditions.getMach() > 1.1) { - warnings.add("Body calculations may not be entirely accurate at supersonic speeds."); + warnings.add(Warning.SUPERSONIC); } } diff --git a/core/src/net/sf/openrocket/arch/SystemInfo.java b/core/src/net/sf/openrocket/arch/SystemInfo.java index 7b526f2c..316f313c 100644 --- a/core/src/net/sf/openrocket/arch/SystemInfo.java +++ b/core/src/net/sf/openrocket/arch/SystemInfo.java @@ -1,12 +1,13 @@ 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. * @@ -26,7 +27,7 @@ public class SystemInfo { * @return the operating system of the current system. */ public static Platform getPlatform() { - String os = System.getProperty("os.name").toLowerCase(); + String os = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); if (os.indexOf("win") >= 0) { return Platform.WINDOWS; @@ -41,8 +42,8 @@ public class SystemInfo { } - - + + /** * Return the application data directory of this user. The location depends * on the current platform. diff --git a/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java b/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java index 3122f085..799c2a3d 100644 --- a/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java +++ b/core/src/net/sf/openrocket/communication/UpdateInfoRetriever.java @@ -28,6 +28,7 @@ public class UpdateInfoRetriever { */ public void start() { fetcher = new UpdateInfoFetcher(); + fetcher.setName("UpdateInfoFetcher"); fetcher.setDaemon(true); fetcher.start(); } @@ -67,7 +68,7 @@ public class UpdateInfoRetriever { } - + /** * Parse the data received from the server. * @@ -84,7 +85,7 @@ public class UpdateInfoRetriever { reader = new BufferedReader(r); } - + String version = null; ArrayList> updates = new ArrayList>(); @@ -113,7 +114,7 @@ public class UpdateInfoRetriever { } - + /** * An asynchronous task that fetches and parses the update info. * @@ -183,7 +184,7 @@ public class UpdateInfoRetriever { String contentType = connection.getContentType(); if (contentType == null || - contentType.toLowerCase().indexOf(Communicator.UPDATE_INFO_CONTENT_TYPE) < 0) { + contentType.toLowerCase(Locale.ENGLISH).indexOf(Communicator.UPDATE_INFO_CONTENT_TYPE) < 0) { // Unknown response type log.warn("Unknown Content-type received:" + contentType); return; @@ -223,7 +224,7 @@ public class UpdateInfoRetriever { return; } - + info = new UpdateInfo(version, updates); log.info("Found update: " + info); } finally { diff --git a/core/src/net/sf/openrocket/database/ComponentPresetDao.java b/core/src/net/sf/openrocket/database/ComponentPresetDao.java new file mode 100644 index 00000000..a27a7f5d --- /dev/null +++ b/core/src/net/sf/openrocket/database/ComponentPresetDao.java @@ -0,0 +1,33 @@ +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 new file mode 100644 index 00000000..bb2fae2b --- /dev/null +++ b/core/src/net/sf/openrocket/database/ComponentPresetDatabase.java @@ -0,0 +1,208 @@ +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 index 37636304..d0909cd6 100644 --- a/core/src/net/sf/openrocket/database/Database.java +++ b/core/src/net/sf/openrocket/database/Database.java @@ -1,6 +1,7 @@ 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; @@ -15,9 +16,12 @@ 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; @@ -31,7 +35,7 @@ import net.sf.openrocket.util.JarUtil; public class Database> extends AbstractSet { private static final LogHelper log = Application.getLogger(); - private final List list = new ArrayList(); + protected final List list = new ArrayList(); private final ArrayList> listeners = new ArrayList>(); private final Loader loader; @@ -126,7 +130,30 @@ public class Database> extends AbstractSet { //////// 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 diff --git a/core/src/net/sf/openrocket/database/Databases.java b/core/src/net/sf/openrocket/database/Databases.java index 30797e31..853790bf 100644 --- a/core/src/net/sf/openrocket/database/Databases.java +++ b/core/src/net/sf/openrocket/database/Databases.java @@ -3,6 +3,7 @@ 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; @@ -17,6 +18,7 @@ public class Databases { private static final LogHelper log = Application.getLogger(); private static final Translator trans = Application.getTranslator(); + /* Static implementations of specific databases: */ /** @@ -37,65 +39,53 @@ public class Databases { static { // Add default materials - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Acrylic"), 1190, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Aluminum"), 2700, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Balsa"), 170, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Basswood"), 500, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Birch"), 670, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Brass"), 8600, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Cardboard"), 680, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Carbonfiber"), 1780, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Cork"), 240, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.DepronXPS"), 40, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Fiberglass"), 1850, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Kraftphenolic"), 950, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Maple"), 755, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Paperoffice"), 820, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Pine"), 530, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Plywoodbirch"), 630, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.PolycarbonateLexan"), 1200, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Polystyrene"), 1050, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.PVC"), 1390, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Spruce"), 450, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Steel"), 7850, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.StyrofoamgenericEPS"), 20, false)); - // BULK_MATERIAL.add(new Material.Bulk("Styrofoam (Blue foam, XPS)", 32, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.StyrofoamBluefoamXPS"), 32, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Titanium"), 4500, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.Quantumtubing"), 1050, false)); - BULK_MATERIAL.add(new Material.Bulk(trans.get("Databases.materials.BlueTube"), 1300, false)); + 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(new Material.Surface(trans.get("Databases.materials.Ripstopnylon"), 0.067, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Mylar"), 0.021, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Polyethylenethin"), 0.015, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Polyethyleneheavy"), 0.040, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Silk"), 0.060, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Paperoffice"), 0.080, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Cellophane"), 0.018, false)); - SURFACE_MATERIAL.add(new Material.Surface(trans.get("Databases.materials.Crepepaper"), 0.025, false)); + 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)); - //// Thread (heavy-duty) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Threadheavy-duty"), 0.0003, false)); - //// Elastic cord (round 2mm, 1/16 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Elasticcordround2mm"), 0.0018, false)); - //// Elastic cord (flat 6mm, 1/4 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Elasticcordflat6mm"), 0.0043, false)); - //// Elastic cord (flat 12mm, 1/2 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Elasticcordflat12mm"), 0.008, false)); - //// Elastic cord (flat 19mm, 3/4 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Elasticcordflat19mm"), 0.0012, false)); - //// Elastic cord (flat 25mm, 1 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Elasticcordflat25mm"), 0.0016, false)); - //// Braided nylon (2 mm, 1/16 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Braidednylon2mm"), 0.001, false)); - //// Braided nylon (3 mm, 1/8 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Braidednylon3mm"), 0.0035, false)); - //// Tubular nylon (11 mm, 7/16 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Tubularnylon11mm"), 0.013, false)); - //// Tubular nylon (14 mm, 9/16 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Tubularnylon14mm"), 0.016, false)); - //// Tubular nylon (25 mm, 1 in) - LINE_MATERIAL.add(new Material.Line(trans.get("Databases.materials.Tubularnylon25mm"), 0.029, false)); + 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 @@ -126,6 +116,14 @@ public class Databases { } + 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. */ @@ -133,16 +131,18 @@ public class Databases { } - /** * 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 name the material name in the database. - * @return the material, or null if not found. + * @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 name) { + public static Material findMaterial(Material.Type type, String baseName) { Database db; switch (type) { case BULK: @@ -158,6 +158,8 @@ public class Databases { throw new IllegalArgumentException("Illegal material type: " + type); } + String name = trans.get("material", baseName); + for (Material m : db) { if (m.getName().equalsIgnoreCase(name)) { return m; @@ -168,17 +170,18 @@ public class Databases { /** - * Find a material from the database or return a new material if the specified + * 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 name the material name. + * @param baseName the base name of the material. * @param density the density of the material. - * @param userDefined whether a newly created material should be user-defined. * @return the material object from the database or a new material. */ - public static Material findMaterial(Material.Type type, String name, double density, - boolean userDefined) { + public static Material findMaterial(Material.Type type, String baseName, double density) { Database db; switch (type) { case BULK: @@ -194,13 +197,14 @@ public class Databases { 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, userDefined); + return Material.newMaterial(type, name, density, true); } - } diff --git a/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java b/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java index 1aeb6cd4..9b4c8b18 100644 --- a/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java +++ b/core/src/net/sf/openrocket/database/ThrustCurveMotorSetDatabase.java @@ -204,6 +204,10 @@ public abstract class ThrustCurveMotorSetDatabase implements MotorDatabase { * 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 index cafc98f3..12535220 100644 --- a/core/src/net/sf/openrocket/document/OpenRocketDocument.java +++ b/core/src/net/sf/openrocket/document/OpenRocketDocument.java @@ -1,8 +1,12 @@ 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; @@ -13,6 +17,10 @@ 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; @@ -50,7 +58,8 @@ public class OpenRocketDocument implements ComponentChangeListener { 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.* @@ -103,7 +112,59 @@ public class OpenRocketDocument implements ComponentChangeListener { } - + 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; diff --git a/core/src/net/sf/openrocket/document/Simulation.java b/core/src/net/sf/openrocket/document/Simulation.java index 74d3ab28..edb093c3 100644 --- a/core/src/net/sf/openrocket/document/Simulation.java +++ b/core/src/net/sf/openrocket/document/Simulation.java @@ -75,8 +75,6 @@ public class Simulation implements ChangeSource, Cloneable { private Class simulationStepperClass = RK4SimulationStepper.class; private Class aerodynamicCalculatorClass = BarrowmanCalculator.class; private Class massCalculatorClass = BasicMassCalculator.class; - - /** Listeners for this object */ private List listeners = new ArrayList(); @@ -90,8 +88,8 @@ public class Simulation implements ChangeSource, Cloneable { /** - * Create a new simulation for the rocket. The initial motor configuration is - * taken from the default rocket configuration. + * 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. */ @@ -148,7 +146,6 @@ public class Simulation implements ChangeSource, Cloneable { } - /** * Return the rocket associated with this simulation. * @@ -280,6 +277,7 @@ public class Simulation implements ChangeSource, Cloneable { } SimulationConditions simulationConditions = options.toSimulationConditions(); + simulationConditions.setSimulation(this); for (SimulationListener l : additionalListeners) { simulationConditions.getSimulationListenerList().add(l); } diff --git a/core/src/net/sf/openrocket/file/GeneralRocketLoader.java b/core/src/net/sf/openrocket/file/GeneralRocketLoader.java index 775d9edd..da6858d8 100644 --- a/core/src/net/sf/openrocket/file/GeneralRocketLoader.java +++ b/core/src/net/sf/openrocket/file/GeneralRocketLoader.java @@ -12,6 +12,8 @@ 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; /** @@ -26,9 +28,9 @@ 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 = "PK".getBytes(Charset.forName("US-ASCII")); - private static final byte[] OPENROCKET_SIGNATURE = " 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); @@ -63,11 +63,24 @@ public final class MotorLoaderHelper { } } } - + + } + } + + 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. @@ -78,22 +91,16 @@ public final class MotorLoaderHelper { * @return a list of all motors loaded. */ public static List load(FileIterator iterator) { - GeneralMotorLoader loader = new GeneralMotorLoader(); List list = new ArrayList(); - + while (iterator.hasNext()) { final Pair input = iterator.next(); log.debug("Loading motors from file " + input.getU()); try { - List motors = loader.load(input.getV(), input.getU()); - if (motors.size() == 0) { - log.warn("No motors found in file " + input.getU()); - } + List motors = load(input.getV(), input.getU()); for (Motor m : motors) { list.add((ThrustCurveMotor) m); } - } catch (IOException e) { - log.warn("IOException when loading motor file " + input.getU(), e); } finally { try { input.getV().close(); @@ -103,8 +110,8 @@ public final class MotorLoaderHelper { } } iterator.close(); - + return list; } - + } diff --git a/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java b/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java index 5b863158..0a5e0479 100644 --- a/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/OpenRocketSaver.java @@ -8,6 +8,7 @@ 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; @@ -18,6 +19,8 @@ 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; @@ -26,6 +29,7 @@ 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; @@ -97,6 +101,9 @@ public class OpenRocketSaver extends RocketSaver { writeln(""); + // Save custom expressions; + saveCustomDatatypes(document); + // Save all simulations writeln(""); indent++; @@ -120,7 +127,41 @@ public class OpenRocketSaver extends RocketSaver { } } + /* + * 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) { @@ -183,6 +224,11 @@ public class OpenRocketSaver extends RocketSaver { */ 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 @@ -194,15 +240,34 @@ public class OpenRocketSaver extends RocketSaver { * 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) - Iterator iterator = document.getRocket().iterator(); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); + for (RocketComponent c : document.getRocket()) { if (!(c instanceof MotorMount)) continue; @@ -215,10 +280,7 @@ public class OpenRocketSaver extends RocketSaver { } // Check for fin tabs (version 1.1) - iterator = document.getRocket().iterator(); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - + for (RocketComponent c : document.getRocket()) { // Check for fin tabs if (c instanceof FinSet) { FinSet fin = (FinSet) c; @@ -304,8 +366,10 @@ public class OpenRocketSaver extends RocketSaver { writeln("" + escapeXML(simulation.getName()) + ""); // TODO: MEDIUM: Other simulators/calculators + writeln("RK4Simulator"); writeln("BarrowmanCalculator"); + writeln(""); indent++; @@ -318,7 +382,7 @@ public class OpenRocketSaver extends RocketSaver { writeElement("launchaltitude", cond.getLaunchAltitude()); writeElement("launchlatitude", cond.getLaunchLatitude()); writeElement("launchlongitude", cond.getLaunchLongitude()); - writeElement("geodeticmethod", cond.getGeodeticComputation().name().toLowerCase()); + writeElement("geodeticmethod", cond.getGeodeticComputation().name().toLowerCase(Locale.ENGLISH)); if (cond.isISAAtmosphere()) { writeln(""); @@ -341,7 +405,6 @@ public class OpenRocketSaver extends RocketSaver { writeElement("listener", escapeXML(s)); } - // Write basic simulation data FlightData data = simulation.getSimulatedData(); @@ -419,6 +482,17 @@ public class OpenRocketSaver extends RocketSaver { 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) @@ -553,7 +627,7 @@ public class OpenRocketSaver extends RocketSaver { * @return the corresponding XML name. */ public static String enumToXMLName(Enum e) { - return e.name().toLowerCase().replace("_", ""); + return e.name().toLowerCase(Locale.ENGLISH).replace("_", ""); } } diff --git a/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java b/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java index 313fa981..4efdf9db 100644 --- a/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java +++ b/core/src/net/sf/openrocket/file/openrocket/importt/OpenRocketLoader.java @@ -7,6 +7,7 @@ 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; @@ -27,6 +28,7 @@ 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; @@ -71,6 +73,7 @@ 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; @@ -163,7 +166,7 @@ public class OpenRocketLoader extends AbstractRocketLoader { class DocumentConfig { /* Remember to update OpenRocketSaver as well! */ - public static final String[] SUPPORTED_VERSIONS = { "1.0", "1.1", "1.2", "1.3", "1.4" }; + 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. @@ -235,6 +238,8 @@ class DocumentConfig { 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( @@ -508,7 +513,7 @@ class DocumentConfig { return null; name = name.trim(); for (Enum e : enumClass.getEnumConstants()) { - if (e.name().toLowerCase().replace("_", "").equals(name)) { + if (e.name().toLowerCase(Locale.ENGLISH).replace("_", "").equals(name)) { return e; } } @@ -644,6 +649,7 @@ class OpenRocketContentHandler extends AbstractElementHandler { private boolean rocketDefined = false; private boolean simulationsDefined = false; + private boolean datatypesDefined = false; public OpenRocketContentHandler(DocumentLoadingContext context) { this.context = context; @@ -651,7 +657,6 @@ class OpenRocketContentHandler extends AbstractElementHandler { this.doc = new OpenRocketDocument(rocket); } - public OpenRocketDocument getDocument() { if (!rocketDefined) return null; @@ -673,6 +678,15 @@ class OpenRocketContentHandler extends AbstractElementHandler { 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 @@ -690,8 +704,90 @@ class OpenRocketContentHandler extends AbstractElementHandler { } } +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 @@ -926,7 +1022,7 @@ class MotorMountHandler extends AbstractElementHandler { if (element.equals("ignitionevent")) { MotorMount.IgnitionEvent event = null; for (MotorMount.IgnitionEvent e : MotorMount.IgnitionEvent.values()) { - if (e.name().toLowerCase().replaceAll("_", "").equals(content)) { + if (e.name().toLowerCase(Locale.ENGLISH).replaceAll("_", "").equals(content)) { event = e; break; } @@ -1084,7 +1180,7 @@ class MotorHandler extends AbstractElementHandler { // Motor type type = null; for (Motor.Type t : Motor.Type.values()) { - if (t.name().toLowerCase().equals(content.trim())) { + if (t.name().toLowerCase(Locale.ENGLISH).equals(content.trim())) { type = t; break; } @@ -1190,13 +1286,18 @@ class SimulationsHandler extends AbstractElementHandler { 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; @@ -1213,7 +1314,9 @@ class SingleSimulationHandler extends AbstractElementHandler { this.context = context; } - + public OpenRocketDocument getDocument() { + return doc; + } @Override public ElementHandler openElement(String element, HashMap attributes, @@ -1226,7 +1329,7 @@ class SingleSimulationHandler extends AbstractElementHandler { conditionHandler = new SimulationConditionsHandler(doc.getRocket(), context); return conditionHandler; } else if (element.equals("flightdata")) { - dataHandler = new FlightDataHandler(context); + dataHandler = new FlightDataHandler(this, context); return dataHandler; } else { warnings.add("Unknown element '" + element + "', ignoring."); @@ -1289,8 +1392,6 @@ class SingleSimulationHandler extends AbstractElementHandler { } } - - class SimulationConditionsHandler extends AbstractElementHandler { private final DocumentLoadingContext context; private SimulationOptions conditions; @@ -1475,11 +1576,13 @@ class FlightDataHandler extends AbstractElementHandler { private WarningSet warningSet = new WarningSet(); private List branches = new ArrayList(); + private SingleSimulationHandler simHandler; private FlightData data; - public FlightDataHandler(DocumentLoadingContext context) { + public FlightDataHandler(SingleSimulationHandler simHandler, DocumentLoadingContext context) { this.context = context; + this.simHandler = simHandler; } public FlightData getFlightData() { @@ -1499,7 +1602,8 @@ class FlightDataHandler extends AbstractElementHandler { return null; } dataHandler = new FlightDataBranchHandler(attributes.get("name"), - attributes.get("types"), context); + attributes.get("types"), + simHandler, context); return dataHandler; } @@ -1596,18 +1700,59 @@ class FlightDataBranchHandler extends AbstractElementHandler { private final FlightDataType[] types; private final FlightDataBranch branch; - public FlightDataBranchHandler(String name, String typeList, DocumentLoadingContext context) { + 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++) { - types[i] = FlightDataType.getType(split[i], UnitGroup.UNITS_NONE); + 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; @@ -1933,8 +2078,71 @@ class ColorSetter implements Setter { } } +////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; @@ -1985,12 +2193,12 @@ class MaterialSetter implements Setter { // Check type if specified str = attributes.remove("type"); - if (str != null && !type.name().toLowerCase().equals(str)) { + 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, false); + mat = Databases.findMaterial(type, name, density); setMethod.invoke(c, mat); } @@ -1999,6 +2207,7 @@ class MaterialSetter implements Setter { + class PositionSetter implements Setter { @Override diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java index 2f1b2a4e..5415832a 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/ExternalComponentSaver.java @@ -1,23 +1,24 @@ 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; + ExternalComponent ext = (ExternalComponent) c; // Finish enum names are currently the same except for case - elements.add("" + ext.getFinish().name().toLowerCase() + ""); + 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 index 8756d89f..7eaffc69 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/FinSetSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/FinSetSaver.java @@ -1,34 +1,35 @@ 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() + 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) && + if (!MathUtil.equals(fins.getTabHeight(), 0) && !MathUtil.equals(fins.getTabLength(), 0)) { elements.add("" + fins.getTabHeight() + ""); elements.add("" + fins.getTabLength() + ""); elements.add("" + + fins.getTabRelativePosition().name().toLowerCase(Locale.ENGLISH) + "\">" + fins.getTabShift() + ""); - + } } - + } diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java index 22dcaa9c..a73d8fd6 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/RecoveryDeviceSaver.java @@ -1,27 +1,28 @@ 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() + ""); + + 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/RocketComponentSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RocketComponentSaver.java index 3cd29acb..a4892902 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RocketComponentSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/RocketComponentSaver.java @@ -3,21 +3,26 @@ 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 @@ -26,7 +31,14 @@ public class RocketComponentSaver { 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(); @@ -38,19 +50,19 @@ public class RocketComponentSaver { LineStyle style = c.getLineStyle(); if (style != null) { // Type names currently equivalent to the enum names except for case. - elements.add("" + style.name().toLowerCase() + ""); + 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(); + String type = c.getRelativePosition().name().toLowerCase(Locale.ENGLISH); elements.add("" + c.getPositionValue() + ""); } - + // Overrides boolean overridden = false; if (c.isMassOverridden()) { @@ -66,7 +78,7 @@ public class RocketComponentSaver { + ""); } - + // Comment if (c.getComment().length() > 0) { elements.add("" + RocketSaver.escapeXML(c.getComment()) + ""); @@ -75,8 +87,8 @@ public class RocketComponentSaver { } - - + + protected final String materialParam(Material mat) { return materialParam("material", mat); } @@ -99,7 +111,9 @@ public class RocketComponentSaver { throw new BugException("Unknown material type: " + mat.getType()); } - return str + " density=\"" + mat.getDensity() + "\">" + RocketSaver.escapeXML(mat.getName()) + ""; + String baseName = trans.getBaseText("material", mat.getName()); + + return str + " density=\"" + mat.getDensity() + "\">" + RocketSaver.escapeXML(baseName) + ""; } @@ -121,7 +135,7 @@ public class RocketComponentSaver { elements.add(" "); if (motor.getMotorType() != Motor.Type.UNKNOWN) { - elements.add(" " + motor.getMotorType().name().toLowerCase() + ""); + elements.add(" " + motor.getMotorType().name().toLowerCase(Locale.ENGLISH) + ""); } if (motor instanceof ThrustCurveMotor) { ThrustCurveMotor m = (ThrustCurveMotor) motor; @@ -144,7 +158,7 @@ public class RocketComponentSaver { } elements.add(" " - + mount.getIgnitionEvent().name().toLowerCase().replace("_", "") + + mount.getIgnitionEvent().name().toLowerCase(Locale.ENGLISH).replace("_", "") + ""); elements.add(" " + mount.getIgnitionDelay() + ""); diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java index e8b7a345..be7c52af 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/RocketSaver.java @@ -2,51 +2,49 @@ 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("" + 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()) + 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() + 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/StageSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/StageSaver.java index e0b1b58d..23f591f3 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/StageSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/StageSaver.java @@ -2,6 +2,7 @@ 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; @@ -27,7 +28,7 @@ public class StageSaver extends ComponentAssemblySaver { if (stage.getStageNumber() > 0) { elements.add("" - + stage.getSeparationEvent().name().toLowerCase().replace("_", "") + + stage.getSeparationEvent().name().toLowerCase(Locale.ENGLISH).replace("_", "") + ""); elements.add("" + stage.getSeparationDelay() + ""); } diff --git a/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java b/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java index d7bb1ed7..0a4169f9 100644 --- a/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java +++ b/core/src/net/sf/openrocket/file/openrocket/savers/TransitionSaver.java @@ -2,26 +2,27 @@ 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. */ @@ -30,31 +31,31 @@ public class TransitionSaver extends SymmetricComponentSaver { 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() + ""); + 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() + ""); @@ -65,7 +66,7 @@ public class TransitionSaver extends SymmetricComponentSaver { elements.add("" + trans.isForeShoulderCapped() + ""); } - + elements.add("" + trans.getAftShoulderRadius() + ""); elements.add("" + trans.getAftShoulderLength() @@ -75,5 +76,5 @@ public class TransitionSaver extends SymmetricComponentSaver { elements.add("" + trans.isAftShoulderCapped() + ""); } - + } diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java b/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java index 9686b979..431db265 100644 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java +++ b/core/src/net/sf/openrocket/file/rocksim/RocksimCommonConstants.java @@ -79,6 +79,10 @@ public class RocksimCommonConstants { 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. */ @@ -103,7 +107,4 @@ public class RocksimCommonConstants { * Radius conversion. Rocksim is always in diameters, OpenRocket mostly in radius. */ public static final int ROCKSIM_TO_OPENROCKET_RADIUS = 2 * ROCKSIM_TO_OPENROCKET_LENGTH; - public static final String TUBE_FIN_SET = "TubeFinSet"; - public static final String RING_TAIL = "RingTail"; - public static final String EXTERNAL_POD = "ExternalPod"; } diff --git a/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java b/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java index cd580ea1..8d24e244 100644 --- a/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java +++ b/core/src/net/sf/openrocket/file/rocksim/RocksimNoseConeCode.java @@ -5,38 +5,57 @@ 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), - 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), + 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); + HAACK(6, Transition.Shape.HAACK); - /** The Rocksim enumeration value. Sent in XML. */ + /** + * The Rocksim enumeration value. Sent in XML. + */ private final int ordinal; - - /** The corresponding OpenRocket shape. */ + + /** + * 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 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) { + 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() { @@ -45,8 +64,8 @@ public enum RocksimNoseConeCode { /** * Lookup an instance of this enum based upon the Rocksim code. - * - * @param rocksimShapeCode the Rocksim code (from XML) + * + * @param rocksimShapeCode the Rocksim code (from XML) * @return an instance of this enum */ public static RocksimNoseConeCode fromCode(int rocksimShapeCode) { @@ -61,9 +80,8 @@ public enum RocksimNoseConeCode { /** * Lookup an ordinal value for the Rocksim code. - * - * @param type the OR Shape - * + * + * @param type the OR Shape * @return the Rocksim code */ public static int toCode(Transition.Shape type) { @@ -78,4 +96,36 @@ public enum RocksimNoseConeCode { } 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/RocksimSaver.java b/core/src/net/sf/openrocket/file/rocksim/export/RocksimSaver.java index 47e28bd5..9d601efb 100644 --- a/core/src/net/sf/openrocket/file/rocksim/export/RocksimSaver.java +++ b/core/src/net/sf/openrocket/file/rocksim/export/RocksimSaver.java @@ -48,7 +48,7 @@ public class RocksimSaver extends RocketSaver { marshaller.marshal(toRocksimDocumentDTO(doc), sw); return sw.toString(); } catch (Exception e) { - e.printStackTrace(); + log.error("Could not marshall a design to Rocksim format. " + e.getMessage()); } 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 index 6302c62a..35296d41 100644 --- a/core/src/net/sf/openrocket/file/rocksim/importt/BaseHandler.java +++ b/core/src/net/sf/openrocket/file/rocksim/importt/BaseHandler.java @@ -3,260 +3,286 @@ */ 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; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; +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 + * @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; - } - - /** - * 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) { - if (!parent.isCompatible(child)) { - 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. The name of the material is prepended with 'RS: ' to - * indicate it came from a RockSim material. - * - * @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 Material.newMaterial(type, ROCKSIM_MATERIAL_PREFIX + name, density, true); - } - - /** - * 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 seta - * @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; - } - + + /** + * 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/FinSetHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/FinSetHandler.java index 048a2fd4..01b49030 100644 --- a/core/src/net/sf/openrocket/file/rocksim/importt/FinSetHandler.java +++ b/core/src/net/sf/openrocket/file/rocksim/importt/FinSetHandler.java @@ -330,7 +330,7 @@ class FinSetHandler extends AbstractElementHandler { */ private Coordinate[] toCoordinates (String pointList, WarningSet warnings) { List result = new ArrayList(); - if (pointList != null && !pointList.isEmpty()) { + if (pointList != null && pointList.length() > 0) { String[] points = pointList.split("\\Q|\\E"); for (String point : points) { String[] aPoint = point.split(","); diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java index ee8cd22d..2d918af9 100644 --- a/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java +++ b/core/src/net/sf/openrocket/file/rocksim/importt/MassObjectHandler.java @@ -5,9 +5,11 @@ 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; @@ -21,12 +23,12 @@ import java.util.HashMap; */ 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. + * 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; @@ -51,12 +53,12 @@ class MassObjectHandler extends PositionDependentHandler { private int typeCode = 0; /** - * Constructor. - *l - * @param c the parent component - * @param warnings the warning set - * - * @throws IllegalArgumentException thrown if c is null + * 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) { @@ -89,7 +91,7 @@ class MassObjectHandler extends PositionDependentHandler { //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); + super.setCG(0); } if (RocksimCommonConstants.TYPE_CODE.equals(element)) { typeCode = Integer.parseInt(content); @@ -104,32 +106,68 @@ class MassObjectHandler extends PositionDependentHandler { } @Override - public void endHandler(String element, HashMap attributes, String content, WarningSet warnings) throws SAXException { - if (typeCode == 0) { //General Mass Object + 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); } - else if (typeCode == 1) { //Shock Cord - 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 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); + } - //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 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()); } } @@ -154,7 +192,8 @@ class MassObjectHandler extends PositionDependentHandler { } /** - * Get the required type of material for this component. Does not apply to MassComponents, but does apply to Shock Cords. + * Get the required type of material for this component. Does not apply to MassComponents, but does apply to Shock + * Cords. * * @return LINE */ diff --git a/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java b/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java index 0cd180e9..f4b1720a 100644 --- a/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java +++ b/core/src/net/sf/openrocket/file/rocksim/importt/TransitionHandler.java @@ -48,6 +48,9 @@ class TransitionHandler extends BaseHandler { @Override public ElementHandler openElement(String element, HashMap attributes, WarningSet warnings) { + if (RocksimCommonConstants.ATTACHED_PARTS.equals(element)) { + return new AttachedPartsHandler(transition); + } return PlainTextHandler.INSTANCE; } diff --git a/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java b/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java index d5c1f373..169a4d70 100644 --- a/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java +++ b/core/src/net/sf/openrocket/file/simplesax/DelegatorHandler.java @@ -1,11 +1,10 @@ package net.sf.openrocket.file.simplesax; -import java.util.ArrayDeque; -import java.util.Deque; 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; @@ -18,9 +17,9 @@ import org.xml.sax.helpers.DefaultHandler; class DelegatorHandler extends DefaultHandler { private final WarningSet warnings; - private final Deque handlerStack = new ArrayDeque(); - private final Deque elementData = new ArrayDeque(); - private final Deque> elementAttributes = new ArrayDeque>(); + 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 diff --git a/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java b/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java index ec17b775..6f9bc2eb 100644 --- a/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java +++ b/core/src/net/sf/openrocket/file/simplesax/SimpleSAX.java @@ -1,6 +1,8 @@ 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; @@ -23,7 +25,9 @@ import org.xml.sax.helpers.XMLReaderFactory; * @author Sampo Niskanen */ public class SimpleSAX { - + + static final XMLReaderCache cache = new XMLReaderCache(10); + /** * Read a simple XML file. * @@ -35,13 +39,35 @@ public class SimpleSAX { */ public static void readXML(InputSource source, ElementHandler initialHandler, WarningSet warnings) throws IOException, SAXException { - + DelegatorHandler xmlhandler = new DelegatorHandler(initialHandler, warnings); - - XMLReader reader = XMLReaderFactory.createXMLReader(); + + 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/SpinnerEditor.java b/core/src/net/sf/openrocket/gui/SpinnerEditor.java index 843eed6a..be4b7952 100644 --- a/core/src/net/sf/openrocket/gui/SpinnerEditor.java +++ b/core/src/net/sf/openrocket/gui/SpinnerEditor.java @@ -1,6 +1,8 @@ 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 @@ -9,13 +11,27 @@ import javax.swing.JSpinner; * @author Sampo Niskanen */ -public class SpinnerEditor extends JSpinner.NumberEditor { -//public class SpinnerEditor extends JSpinner.DefaultEditor { +//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); + 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/adaptors/Column.java b/core/src/net/sf/openrocket/gui/adaptors/Column.java index 87997c48..9c4801a6 100644 --- a/core/src/net/sf/openrocket/gui/adaptors/Column.java +++ b/core/src/net/sf/openrocket/gui/adaptors/Column.java @@ -63,5 +63,16 @@ public abstract class Column { * @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 index e50a8ea5..b8b8d3ec 100644 --- a/core/src/net/sf/openrocket/gui/adaptors/ColumnTableModel.java +++ b/core/src/net/sf/openrocket/gui/adaptors/ColumnTableModel.java @@ -52,5 +52,10 @@ public abstract class ColumnTableModel extends AbstractTableModel { } 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 index 820a54a6..3216f0a7 100644 --- a/core/src/net/sf/openrocket/gui/adaptors/DoubleModel.java +++ b/core/src/net/sf/openrocket/gui/adaptors/DoubleModel.java @@ -10,10 +10,10 @@ 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.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; @@ -23,6 +23,8 @@ 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; @@ -48,20 +50,25 @@ import net.sf.openrocket.util.StateChangeListener; 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 using JSpinner.NumberEditor. It extends SpinnerNumberModel + * 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. */ - private class ValueSpinnerModel extends SpinnerNumberModel implements Invalidatable { + public class ValueSpinnerModel extends AbstractSpinnerModel implements Invalidatable { + + private ExpressionParser parser = new ExpressionParser(); @Override public Object getValue() { - return currentUnit.toUnit(DoubleModel.this.getValue()); + return currentUnit.toString(DoubleModel.this.getValue()); } @Override @@ -72,14 +79,41 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat " value=" + value + ", currently firing events"); return; } - Number num = (Number) value; - 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); + 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 @@ -106,18 +140,6 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat return d; } - - @Override - public Comparable getMinimum() { - return currentUnit.toUnit(minValue); - } - - @Override - public Comparable getMaximum() { - return currentUnit.toUnit(maxValue); - } - - @Override public void addChangeListener(ChangeListener l) { DoubleModel.this.addChangeListener(l); @@ -144,10 +166,6 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat return new ValueSpinnerModel(); } - - - - //////////// JSlider model //////////// private class ValueSliderModel implements BoundedRangeModel, StateChangeListener, Invalidatable { @@ -157,7 +175,8 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat * 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; @@ -169,11 +188,10 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat //private final double linear0; // Non-linear multiplier, exponent and constant - private final double quad2, quad1, quad0; + private double quad2, quad1, quad0; - - public ValueSliderModel(DoubleModel min, DoubleModel max) { + this.islinear = true; linearPosition = 1.0; this.min = min; @@ -187,11 +205,12 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat } - + /** * 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); @@ -205,6 +224,10 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat 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 * @@ -213,32 +236,46 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat * 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 = new DoubleModel(max); + this.max = max; + + this.islinear = false; + + max.addChangeListener(this); - linearPosition = pos; //linear0 = min; //linear1 = (mid-min)/pos; - if (!(min < mid && mid <= max && 0 < pos && pos < 1)) { + 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 = (mid - min) / pos; - quad2 = (max - mid - delta + delta * pos) / pow2(pos - 1); - quad1 = (delta + 2 * (mid - max) * pos - delta * pos * pos) / pow2(pos - 1); - quad0 = (mid - (2 * mid + delta) * pos + (max + delta) * pos * pos) / pow2(pos - 1); - + 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) { @@ -366,6 +403,11 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat @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(); @@ -385,14 +427,18 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat 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 { @@ -491,15 +537,15 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat } - - - + + + //////////// 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; @@ -516,14 +562,14 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat private Unit currentUnit; private final double minValue; - private final double maxValue; + 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; @@ -677,7 +723,7 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat } - + /** * Returns the value of the variable (in SI units). */ @@ -725,7 +771,6 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat } } - /** * Returns whether setting the value automatically is available. */ @@ -811,7 +856,7 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat } - + /** * Add a listener to the model. Adds the model as a listener to the value source if this * is the first listener. @@ -897,10 +942,10 @@ public class DoubleModel implements StateChangeListener, ChangeSource, Invalidat // 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); + if (l instanceof StateChangeListener) { + ((StateChangeListener) l).stateChanged(event); + } else if (l instanceof ChangeListener) { + ((ChangeListener) l).stateChanged(cevent); } } firing--; diff --git a/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java b/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java index a914df00..c3ebf835 100644 --- a/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java +++ b/core/src/net/sf/openrocket/gui/adaptors/MaterialModel.java @@ -22,7 +22,7 @@ import net.sf.openrocket.util.Reflection; public class MaterialModel extends AbstractListModel implements ComboBoxModel, ComponentChangeListener, DatabaseListener { - private static final String CUSTOM = "Custom"; + private final String custom; private final Component parentComponent; @@ -47,6 +47,7 @@ public class MaterialModel extends AbstractListModel implements this.parentComponent = parent; this.component = component; this.type = type; + this.custom = trans.get ("Material.CUSTOM"); switch (type) { case LINE: @@ -90,7 +91,7 @@ public class MaterialModel extends AbstractListModel implements return; } - if (item == CUSTOM) { + if (item == custom) { // Open custom material dialog in the future, after combo box has closed SwingUtilities.invokeLater(new Runnable() { @@ -129,7 +130,7 @@ public class MaterialModel extends AbstractListModel implements @Override public Object getElementAt(int index) { if (index == database.size()) { - return CUSTOM; + return custom; } else if (index >= database.size()+1) { return null; } diff --git a/core/src/net/sf/openrocket/gui/adaptors/PresetModel.java b/core/src/net/sf/openrocket/gui/adaptors/PresetModel.java new file mode 100644 index 00000000..474610de --- /dev/null +++ b/core/src/net/sf/openrocket/gui/adaptors/PresetModel.java @@ -0,0 +1,120 @@ +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/StarCheckBox.java b/core/src/net/sf/openrocket/gui/components/StarCheckBox.java new file mode 100644 index 00000000..a7bdb6d5 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/components/StarCheckBox.java @@ -0,0 +1,20 @@ +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 index cad8a25a..70328411 100644 --- a/core/src/net/sf/openrocket/gui/components/StyledLabel.java +++ b/core/src/net/sf/openrocket/gui/components/StyledLabel.java @@ -90,8 +90,8 @@ public class StyledLabel extends JLabel { if (str.startsWith("") && str.indexOf("(component, "CrossSection")); panel.add(combo, "growx, wrap unrel"); - + //// Thickness: panel.add(new JLabel(trans.get("EllipticalFinSetCfg.Thickness"))); @@ -167,15 +167,15 @@ public class EllipticalFinSetConfig extends FinSetConfig { 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(); diff --git a/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java b/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java index af4c7bf4..aa82e994 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/FreeformFinSetConfig.java @@ -104,7 +104,7 @@ public class FreeformFinSetConfig extends FinSetConfig { //// Base rotation panel.add(new JLabel(trans.get("FreeformFinSetCfg.lbl.Finrotation"))); - m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE, -Math.PI, Math.PI); + m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); diff --git a/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java b/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java index 947b205a..07248d11 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/LaunchLugConfig.java @@ -29,7 +29,7 @@ public class LaunchLugConfig extends RocketComponentConfig { JPanel primary = new JPanel(new MigLayout("fill")); - + JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); //// Body tube length @@ -45,7 +45,7 @@ public class LaunchLugConfig extends RocketComponentConfig { 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"))); @@ -60,14 +60,14 @@ public class LaunchLugConfig extends RocketComponentConfig { 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"); @@ -75,7 +75,7 @@ public class LaunchLugConfig extends RocketComponentConfig { 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"))); @@ -89,12 +89,11 @@ public class LaunchLugConfig extends RocketComponentConfig { 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, - -Math.PI, Math.PI); + m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); @@ -103,14 +102,14 @@ public class LaunchLugConfig extends RocketComponentConfig { 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"))); @@ -121,7 +120,7 @@ public class LaunchLugConfig extends RocketComponentConfig { RocketComponent.Position.MIDDLE, RocketComponent.Position.BOTTOM, RocketComponent.Position.ABSOLUTE - })); + })); panel.add(combo, "spanx, growx, wrap"); //// plus @@ -138,12 +137,12 @@ public class LaunchLugConfig extends RocketComponentConfig { new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap para"); - - + + //// Material materialPanel(panel, Material.Type.BULK); - + primary.add(panel, "grow"); //// General and General properties diff --git a/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java b/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java index b199d209..cf70d463 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/MassComponentConfig.java @@ -29,11 +29,11 @@ public class MassComponentConfig extends RocketComponentConfig { 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"))); @@ -46,8 +46,20 @@ public class MassComponentConfig extends RocketComponentConfig { 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"))); @@ -61,7 +73,7 @@ public class MassComponentConfig extends RocketComponentConfig { 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"))); @@ -76,7 +88,7 @@ public class MassComponentConfig extends RocketComponentConfig { 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"))); @@ -88,7 +100,7 @@ public class MassComponentConfig extends RocketComponentConfig { 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"); @@ -130,11 +142,11 @@ public class MassComponentConfig extends RocketComponentConfig { 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, 0); + m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); @@ -143,7 +155,7 @@ public class MassComponentConfig extends RocketComponentConfig { 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() { diff --git a/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java b/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java index 227a475c..45eca30f 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/MotorConfig.java @@ -131,7 +131,7 @@ public class MotorConfig extends JPanel { dm = new DoubleModel(mount, "IgnitionDelay", 0); spin = new JSpinner(dm.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); + spin.setEditor(new SpinnerEditor(spin,3)); panel.add(spin, "gap rel rel"); //// seconds diff --git a/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java b/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java index 682f6d35..b1b8d55a 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/NoseConeConfig.java @@ -12,10 +12,12 @@ 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; @@ -47,9 +49,6 @@ public class NoseConeConfig extends RocketComponentConfig { DoubleModel m; JPanel panel = new JPanel(new MigLayout("", "[][65lp::][30lp::]")); - - - //// Shape selection //// Nose cone shape: panel.add(new JLabel(trans.get("NoseConeCfg.lbl.Noseconeshape"))); diff --git a/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java b/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java index 5e299922..1e767a78 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/ParachuteConfig.java @@ -201,7 +201,7 @@ public class ParachuteConfig extends RecoveryDeviceConfig { m = new DoubleModel(component, "DeployDelay", 0); spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); + spin.setEditor(new SpinnerEditor(spin,3)); panel.add(spin, "spanx, split"); //// seconds @@ -262,7 +262,7 @@ public class ParachuteConfig extends RecoveryDeviceConfig { //// Radial direction: panel.add(new JLabel(trans.get("ParachuteCfg.lbl.Radialdirection"))); - m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE, 0); + m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); diff --git a/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java b/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java index 23906d6f..80363300 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/RingComponentConfig.java @@ -41,7 +41,7 @@ public class RingComponentConfig extends RocketComponentConfig { JSpinner spin; DoubleModel od = null; - + //// Outer diameter if (outer != null) { panel.add(new JLabel(outer)); @@ -65,7 +65,7 @@ public class RingComponentConfig extends RocketComponentConfig { } } - + //// Inner diameter if (inner != null) { panel.add(new JLabel(inner)); @@ -92,7 +92,7 @@ public class RingComponentConfig extends RocketComponentConfig { } } - + //// Wall thickness if (thickness != null) { panel.add(new JLabel(thickness)); @@ -108,7 +108,7 @@ public class RingComponentConfig extends RocketComponentConfig { panel.add(new BasicSlider(m.getSliderModel(0, 0.01)), "w 100lp, wrap"); } - + //// Inner tube length if (length != null) { panel.add(new JLabel(length)); @@ -124,7 +124,7 @@ public class RingComponentConfig extends RocketComponentConfig { panel.add(new BasicSlider(m.getSliderModel(0, 0.1, 1.0)), "w 100lp, wrap"); } - + //// Position //// Position relative to: @@ -137,7 +137,7 @@ public class RingComponentConfig extends RocketComponentConfig { RocketComponent.Position.MIDDLE, RocketComponent.Position.BOTTOM, RocketComponent.Position.ABSOLUTE - })); + })); panel.add(combo, "spanx 3, growx, wrap"); //// plus @@ -155,7 +155,7 @@ public class RingComponentConfig extends RocketComponentConfig { new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap"); - + //// Material JPanel sub = materialPanel(new JPanel(new MigLayout()), Material.Type.BULK); @@ -195,14 +195,14 @@ public class RingComponentConfig extends RocketComponentConfig { 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, 0); + m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); @@ -216,7 +216,7 @@ public class RingComponentConfig extends RocketComponentConfig { 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 @@ -230,13 +230,13 @@ public class RingComponentConfig extends RocketComponentConfig { }); 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 index 95853b02..c2fbd63e 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/RocketComponentConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/RocketComponentConfig.java @@ -9,6 +9,7 @@ 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; @@ -24,12 +25,14 @@ 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; @@ -40,6 +43,7 @@ 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; @@ -60,7 +64,9 @@ public class RocketComponentConfig extends JPanel { private final List invalidatables = new ArrayList(); - + private JComboBox presetComboBox; + private PresetModel presetModel; + protected final JTextField componentNameField; protected JTextArea commentTextArea; private final TextFieldListener textFieldListener; @@ -68,11 +74,11 @@ public class RocketComponentConfig extends JPanel { private JCheckBox colorDefault; private JPanel buttonPanel; - private JLabel massLabel; + private JLabel infoLabel; public RocketComponentConfig(OpenRocketDocument document, RocketComponent component) { - setLayout(new MigLayout("fill", "[grow, fill]")); + setLayout(new MigLayout("fill", "[min,align right]:10[fill, grow]")); this.document = document; this.component = component; @@ -80,7 +86,7 @@ public class RocketComponentConfig extends JPanel { JLabel label = new JLabel(trans.get("RocketCompCfg.lbl.Componentname")); //// The component name. label.setToolTipText(trans.get("RocketCompCfg.ttip.Thecomponentname")); - this.add(label, "split, gapright 10"); + this.add(label, "spanx, split"); componentNameField = new JTextField(15); textFieldListener = new TextFieldListener(); @@ -88,11 +94,20 @@ public class RocketComponentConfig extends JPanel { componentNameField.addFocusListener(textFieldListener); //// The component name. componentNameField.setToolTipText(trans.get("RocketCompCfg.ttip.Thecomponentname")); - this.add(componentNameField, "growx, growy 0, wrap"); + 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, "growx, growy 1, wrap"); + 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(), @@ -119,8 +134,8 @@ public class RocketComponentConfig extends JPanel { buttonPanel = new JPanel(new MigLayout("fill, ins 0")); //// Mass: - massLabel = new StyledLabel(trans.get("RocketCompCfg.lbl.Mass") + " ", -1); - buttonPanel.add(massLabel, "growx"); + infoLabel = new StyledLabel(" ", -1); + buttonPanel.add(infoLabel, "growx"); for (JButton b : buttons) { buttonPanel.add(b, "right, gap para"); @@ -158,33 +173,38 @@ public class RocketComponentConfig extends JPanel { colorDefault.setSelected(component.getColor() == null); } - // Mass label + // Info label + StringBuilder sb = new StringBuilder(); + + if (component.getPresetComponent() != null) { + ComponentPreset preset = component.getPresetComponent(); + sb.append(preset.getManufacturer() + " " + preset.getPartNo() + " "); + } + if (component.isMassive()) { - //// Component mass: - String text = trans.get("RocketCompCfg.lbl.Componentmass") + " "; - text += UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit( - component.getComponentMass()); + sb.append(trans.get("RocketCompCfg.lbl.Componentmass") + " "); + sb.append(UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit( + component.getComponentMass())); String overridetext = null; if (component.isMassOverridden()) { - //// (overridden to 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()) { - ///// (overridden by overridetext = trans.get("RocketCompCfg.lbl.overriddenby") + " " + c.getName() + ")"; } } - if (overridetext != null) - text = text + " " + overridetext; + if (overridetext != null) { + sb.append(" " + overridetext); + } - massLabel.setText(text); + infoLabel.setText(sb.toString()); } else { - massLabel.setText(""); + infoLabel.setText(""); } } @@ -197,6 +217,7 @@ public class RocketComponentConfig extends JPanel { 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")); @@ -207,7 +228,7 @@ public class RocketComponentConfig extends JPanel { 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.
@@ -286,7 +307,7 @@ public class RocketComponentConfig extends JPanel { bm.addEnableComponent(bs); panel.add(bs, "growx 5, w 100lp, wrap"); - + //// CG override bm = new BooleanModel(component, "CGOverridden"); check = new JCheckBox(bm); @@ -324,7 +345,7 @@ public class RocketComponentConfig extends JPanel { bm.addEnableComponent(bs); panel.add(bs, "growx 5, w 100lp, wrap 35lp"); - + // Override subcomponents checkbox bm = new BooleanModel(component, "OverrideSubcomponents"); check = new JCheckBox(bm); @@ -336,7 +357,7 @@ public class RocketComponentConfig extends JPanel { 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() + ".", -1), + component.getComponentName().toLowerCase(Locale.getDefault()) + ".", -1), "spanx, wrap, gap para, height 0::30lp"); return panel; @@ -364,7 +385,7 @@ public class RocketComponentConfig extends JPanel { } - + private JPanel figureTab() { JPanel panel = new JPanel(new MigLayout("align 20% 20%")); @@ -384,7 +405,7 @@ public class RocketComponentConfig extends JPanel { } //// Choose color - Color awtColor = ColorConversion.toAwtColor(c); + Color awtColor = ColorConversion.toAwtColor(c); awtColor = JColorChooser.showDialog(tabbedPane, trans.get("RocketCompCfg.lbl.Choosecolor"), awtColor); c = ColorConversion.fromAwtColor(awtColor); if (c != null) { @@ -450,7 +471,7 @@ public class RocketComponentConfig extends JPanel { } - + protected JPanel shoulderTab() { JPanel panel = new JPanel(new MigLayout("fill")); JPanel sub; @@ -460,7 +481,7 @@ public class RocketComponentConfig extends JPanel { JCheckBox check; JSpinner spin; - + //// Fore shoulder, not for NoseCone if (!(component instanceof NoseCone)) { @@ -469,7 +490,7 @@ public class RocketComponentConfig extends JPanel { //// Fore shoulder sub.setBorder(BorderFactory.createTitledBorder(trans.get("RocketCompCfg.border.Foreshoulder"))); - + //// Radius //// Diameter: sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Diameter"))); @@ -484,7 +505,7 @@ public class RocketComponentConfig extends JPanel { 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"))); @@ -497,7 +518,7 @@ public class RocketComponentConfig extends JPanel { 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"))); @@ -511,7 +532,7 @@ public class RocketComponentConfig extends JPanel { 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); @@ -521,11 +542,11 @@ public class RocketComponentConfig extends JPanel { 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::]", "")); @@ -536,7 +557,7 @@ public class RocketComponentConfig extends JPanel { //// Aft shoulder sub.setBorder(BorderFactory.createTitledBorder(trans.get("RocketCompCfg.title.Aftshoulder"))); - + //// Radius //// Diameter: sub.add(new JLabel(trans.get("RocketCompCfg.lbl.Diameter"))); @@ -551,7 +572,7 @@ public class RocketComponentConfig extends JPanel { 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"))); @@ -564,7 +585,7 @@ public class RocketComponentConfig extends JPanel { 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"))); @@ -578,7 +599,7 @@ public class RocketComponentConfig extends JPanel { 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); @@ -588,16 +609,16 @@ public class RocketComponentConfig extends JPanel { check.setToolTipText(trans.get("RocketCompCfg.ttip.Endcapped")); sub.add(check, "spanx"); - + panel.add(sub); - + return panel; } - - + + /* * Private inner class to handle events in componentNameField. */ @@ -635,6 +656,8 @@ public class RocketComponentConfig extends JPanel { 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/StreamerConfig.java b/core/src/net/sf/openrocket/gui/configdialog/StreamerConfig.java index 8d7be304..49137045 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/StreamerConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/StreamerConfig.java @@ -39,7 +39,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::][]", "")); - + //// Strip length: panel.add(new JLabel(trans.get("StreamerCfg.lbl.Striplength"))); @@ -62,8 +62,8 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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"))); @@ -86,7 +86,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { // 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"))); @@ -96,8 +96,8 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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")); @@ -124,14 +124,14 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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"))); @@ -143,7 +143,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { RocketComponent.Position.MIDDLE, RocketComponent.Position.BOTTOM, RocketComponent.Position.ABSOLUTE - })); + })); panel.add(combo, "spanx, growx, wrap"); //// plus @@ -160,7 +160,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap"); - + //// Spatial length: panel.add(new JLabel(trans.get("StreamerCfg.lbl.Packedlength"))); @@ -173,7 +173,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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"))); @@ -188,7 +188,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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")), ""); @@ -202,7 +202,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { m = new DoubleModel(component, "DeployDelay", 0); spin = new JSpinner(m.getSpinnerModel()); - spin.setEditor(new SpinnerEditor(spin)); + spin.setEditor(new SpinnerEditor(spin,3)); panel.add(spin, "spanx, split"); //// seconds @@ -226,7 +226,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { altitudeComponents.add(slider); panel.add(slider, "w 100lp, wrap"); - + primary.add(panel, "grow"); updateFields(); @@ -241,9 +241,9 @@ public class StreamerConfig extends RecoveryDeviceConfig { } - - - + + + protected JPanel positionTab() { JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); @@ -260,12 +260,12 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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, 0); + m = new DoubleModel(component, "RadialDirection", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); @@ -274,7 +274,7 @@ public class StreamerConfig extends RecoveryDeviceConfig { 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() { diff --git a/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java b/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java index 47650ffd..7c343fbf 100644 --- a/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java +++ b/core/src/net/sf/openrocket/gui/configdialog/TrapezoidFinSetConfig.java @@ -37,7 +37,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { JPanel mainPanel = new JPanel(new MigLayout()); - + JPanel panel = new JPanel(new MigLayout("gap rel unrel", "[][65lp::][30lp::]", "")); //// Number of fins: @@ -54,7 +54,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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")); @@ -62,7 +62,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { label.setToolTipText(trans.get("TrapezoidFinSetCfg.lbl.ttip.Finrotation")); panel.add(label); - m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE, -Math.PI, Math.PI); + m = new DoubleModel(component, "BaseRotation", UnitGroup.UNITS_ANGLE); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); @@ -71,7 +71,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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 @@ -89,7 +89,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -102,8 +102,8 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -116,7 +116,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -129,8 +129,8 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -147,7 +147,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -162,27 +162,27 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -195,7 +195,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"))); @@ -207,7 +207,7 @@ public class TrapezoidFinSetConfig extends FinSetConfig { 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"); @@ -223,14 +223,14 @@ public class TrapezoidFinSetConfig extends FinSetConfig { new DoubleModel(component.getParent(), "Length"))), "w 100lp, wrap para"); - - + + //// Material materialPanel(panel, Material.Type.BULK); - - - + + + mainPanel.add(panel, "aligny 20%"); //// General and General properties diff --git a/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionDialog.java b/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionDialog.java new file mode 100644 index 00000000..b8dee9fb --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionDialog.java @@ -0,0 +1,35 @@ +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 new file mode 100644 index 00000000..ba928482 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/CustomExpressionPanel.java @@ -0,0 +1,261 @@ +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 new file mode 100644 index 00000000..615fdc14 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/ExpressionBuilderDialog.java @@ -0,0 +1,272 @@ +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 new file mode 100644 index 00000000..d51af30c --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/OperatorSelector.java @@ -0,0 +1,157 @@ +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 new file mode 100644 index 00000000..3b084da5 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/OperatorTableModel.java @@ -0,0 +1,52 @@ +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 new file mode 100644 index 00000000..90130e63 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/VariableSelector.java @@ -0,0 +1,149 @@ +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 new file mode 100644 index 00000000..f9d64978 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/customexpression/VariableTableModel.java @@ -0,0 +1,84 @@ +/** + * + */ +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 index 1bad92f0..5b7d6cc9 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/AboutDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/AboutDialog.java @@ -31,6 +31,7 @@ public class AboutDialog extends JDialog { "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)

" + @@ -40,10 +41,14 @@ public class AboutDialog extends JDialog { "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/)"; + "iText (http://www.itextpdf.com/)
" + + "exp4j (http://projects.congrace.de/exp4j/index.html)
" + + "JOGL (http://jogamp.org/jogl/www/)"; public AboutDialog(JFrame parent) { diff --git a/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java b/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java index 635e6468..9f5064ed 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/ComponentAnalysisDialog.java @@ -119,7 +119,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { roll = new DoubleModel(rocketPanel, "CPRoll", UnitGroup.UNITS_ROLL); //// Wind direction: - panel.add(new JLabel(trans.get("componentanalysisdlg.lbl.winddir")), "width 100lp!"); + 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"); @@ -149,17 +149,17 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { 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 100lp!"); + 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 100lp!"); + 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 100lp!"); + 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"); @@ -193,7 +193,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { public Object getValueAt(int row) { RocketComponent c = cpData.get(row).getComponent(); if (c instanceof Rocket) { - return "Total"; + return trans.get("componentanalysisdlg.TOTAL"); } return c.toString(); } @@ -203,7 +203,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { return 200; } }, - new Column("CG / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().getUnit()) { + new Column(trans.get("componentanalysisdlg.TabStability.Col.CG") + " / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().getUnit()) { private Unit unit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); @Override @@ -211,7 +211,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { return unit.toString(cgData.get(row).x); } }, - new Column("Mass / " + UnitGroup.UNITS_MASS.getDefaultUnit().getUnit()) { + new Column(trans.get("componentanalysisdlg.TabStability.Col.Mass") + " / " + UnitGroup.UNITS_MASS.getDefaultUnit().getUnit()) { private Unit unit = UnitGroup.UNITS_MASS.getDefaultUnit(); @Override @@ -219,7 +219,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { return unit.toString(cgData.get(row).weight); } }, - new Column("CP / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().getUnit()) { + new Column(trans.get("componentanalysisdlg.TabStability.Col.CP") + " / " + UnitGroup.UNITS_LENGTH.getDefaultUnit().getUnit()) { private Unit unit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); @Override @@ -268,7 +268,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { public Object getValueAt(int row) { RocketComponent c = dragData.get(row).getComponent(); if (c instanceof Rocket) { - return "Total"; + return trans.get("componentanalysisdlg.TOTAL"); } return c.toString(); } @@ -342,7 +342,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { public Object getValueAt(int row) { RocketComponent c = rollData.get(row).getComponent(); if (c instanceof Rocket) { - return "Total"; + return trans.get("componentanalysisdlg.TOTAL"); } return c.toString(); } @@ -407,13 +407,13 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { this.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { - System.out.println("Closing method called: " + this); + //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"); + //System.out.println("SETTING NAN VALUES"); rocketPanel.setCPAOA(Double.NaN); rocketPanel.setCPTheta(Double.NaN); rocketPanel.setCPMach(Double.NaN); @@ -541,7 +541,7 @@ public class ComponentAnalysisDialog extends JDialog implements ChangeListener { // Set warnings if (set.isEmpty()) { warningList.setListData(new String[] { - "No warnings." + trans.get("componentanalysisdlg.noWarnings") }); } else { warningList.setListData(new Vector(set)); diff --git a/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java b/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java index 5e5aece8..9ef95a9b 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/CustomMaterialDialog.java @@ -15,6 +15,7 @@ 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; @@ -24,7 +25,8 @@ 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; @@ -34,14 +36,13 @@ public class CustomMaterialDialog extends JDialog { private JSpinner densitySpinner; private UnitSelector densityUnit; private JCheckBox addBox; - private static final Translator trans = Application.getTranslator(); - + 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 @@ -54,14 +55,14 @@ public class CustomMaterialDialog extends JDialog { // Add title and note if (title != null) { - panel.add(new JLabel("" + title + ":"), - "gapleft para, span, wrap" + (note == null ? " para":"")); + 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); @@ -93,7 +94,7 @@ public class CustomMaterialDialog extends JDialog { panel.add(new JLabel(trans.get("custmatdlg.lbl.Materialdensity"))); densitySpinner = new JSpinner(); panel.add(densitySpinner, "w 70lp"); - densityUnit = new UnitSelector((DoubleModel)null); + densityUnit = new UnitSelector((DoubleModel) null); panel.add(densityUnit, "w 30lp"); panel.add(new JPanel(), "growx, wrap"); updateDensityModel(); @@ -103,9 +104,9 @@ public class CustomMaterialDialog extends JDialog { if (saveOption) { //// Add material to database addBox = new JCheckBox(trans.get("custmatdlg.checkbox.Addmaterial")); - panel.add(addBox,"span, wrap"); + panel.add(addBox, "span, wrap"); } - + //// OK button JButton okButton = new JButton(trans.get("dlg.but.ok")); @@ -116,7 +117,7 @@ public class CustomMaterialDialog extends JDialog { CustomMaterialDialog.this.setVisible(false); } }); - panel.add(okButton,"span, split, tag ok"); + panel.add(okButton, "span, split, tag ok"); //// Cancel JButton closeButton = new JButton(trans.get("dlg.but.cancel")); @@ -127,7 +128,7 @@ public class CustomMaterialDialog extends JDialog { CustomMaterialDialog.this.setVisible(false); } }); - panel.add(closeButton,"tag cancel"); + panel.add(closeButton, "tag cancel"); this.setContentPane(panel); this.pack(); @@ -149,7 +150,7 @@ public class CustomMaterialDialog extends JDialog { public Material getMaterial() { Material.Type type; String name; - double density; + double materialDensity; if (typeBox != null) { type = (Material.Type) typeBox.getSelectedItem(); @@ -159,9 +160,9 @@ public class CustomMaterialDialog extends JDialog { name = nameField.getText().trim(); - density = this.density.getValue(); + materialDensity = this.density.getValue(); - return Material.newMaterial(type, name, density, true); + return Databases.findMaterial(type, name, materialDensity); } diff --git a/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java b/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java index 0a41ce66..6735e0d3 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/EditMotorConfigurationDialog.java @@ -70,15 +70,7 @@ public class EditMotorConfigurationDialog extends JDialog { this.rocket = rocket; - ArrayList mountList = new ArrayList(); - Iterator iterator = rocket.iterator(); - while (iterator.hasNext()) { - RocketComponent c = iterator.next(); - if (c instanceof MotorMount) { - mountList.add((MotorMount) c); - } - } - mounts = mountList.toArray(new MotorMount[0]); + mounts = rocket.getMotorMounts().toArray( new MotorMount[0]) ; diff --git a/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java b/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java index 729586d3..bf2249ce 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/PrintDialog.java @@ -61,22 +61,25 @@ public class PrintDialog extends JDialog implements TreeSelectionListener { 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) { + 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 @@ -257,7 +260,7 @@ public class PrintDialog extends JDialog implements TreeSelectionListener { /** * Generate a report using a temporary file. The file will be deleted upon JVM exit. * - * @param paper the name of the paper size + * @param settings the container of different print settings * * @return a file, populated with the "printed" output (the rocket info) * @@ -273,7 +276,7 @@ public class PrintDialog extends JDialog implements TreeSelectionListener { * Generate a report to a specified file. * * @param f the file to which rocket data will be written - * @param paper the name of the paper size + * @param settings the container of different print settings * * @return a file, populated with the "printed" output (the rocket info) * @@ -281,7 +284,7 @@ public class PrintDialog extends JDialog implements TreeSelectionListener { */ private File generateReport(File f, PrintSettings settings) throws IOException { Iterator toBePrinted = currentTree.getToBePrinted(); - new PrintController().print(document, toBePrinted, new FileOutputStream(f), settings); + new PrintController().print(document, toBePrinted, new FileOutputStream(f), settings, rotation); return f; } diff --git a/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java b/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java index eeb939c7..ca4205d2 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/motor/MotorChooserDialog.java @@ -29,7 +29,7 @@ public class MotorChooserDialog extends JDialog implements CloseableDialog { public MotorChooserDialog(Motor current, double delay, double diameter, Window owner) { - super(owner, "Select a rocket motor", Dialog.ModalityType.APPLICATION_MODAL); + super(owner, trans.get ("MotorChooserDialog.title"), Dialog.ModalityType.APPLICATION_MODAL); // Check that the motor database has been loaded properly MotorDatabaseLoadingDialog.check(null); 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 index d4cefca2..7520a01b 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorColumns.java +++ b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorColumns.java @@ -116,28 +116,28 @@ enum ThrustCurveMotorColumns { tip += "" + desc.replace("\n", "
") + "


"; } - tip += ("Diameter: " + + tip += (trans.get("TCurveMotor.ttip.diameter") + " " + UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit().toStringUnit(m.getDiameter()) + "
"); - tip += ("Length: " + + tip += (trans.get("TCurveMotor.ttip.length") + " " + UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit().toStringUnit(m.getLength()) + "
"); - tip += ("Maximum thrust: " + + tip += (trans.get("TCurveMotor.ttip.maxThrust") + " " + UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(m.getMaxThrustEstimate()) + "
"); - tip += ("Average thrust: " + + tip += (trans.get("TCurveMotor.ttip.avgThrust") + " " + UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(m.getAverageThrustEstimate()) + "
"); - tip += ("Burn time: " + + tip += (trans.get("TCurveMotor.ttip.burnTime") + " " + UnitGroup.UNITS_SHORT_TIME.getDefaultUnit() .toStringUnit(m.getBurnTimeEstimate()) + "
"); - tip += ("Total impulse: " + + tip += (trans.get("TCurveMotor.ttip.totalImpulse") + " " + UnitGroup.UNITS_IMPULSE.getDefaultUnit() .toStringUnit(m.getTotalImpulseEstimate()) + "
"); - tip += ("Launch mass: " + + tip += (trans.get("TCurveMotor.ttip.launchMass") + " " + UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(m.getLaunchCG().weight) + "
"); - tip += ("Empty mass: " + + tip += (trans.get("TCurveMotor.ttip.emptyMass") + " " + UnitGroup.UNITS_MASS.getDefaultUnit() .toStringUnit(m.getEmptyCG().weight)); return tip; 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 index 8e6fe5d6..7deaaa8f 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorSelectionPanel.java +++ b/core/src/net/sf/openrocket/gui/dialogs/motor/thrustcurve/ThrustCurveMotorSelectionPanel.java @@ -14,6 +14,7 @@ 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; @@ -333,7 +334,7 @@ public class ThrustCurveMotorSelectionPanel extends JPanel implements MotorSelec String[] split = text.split("\\s+"); ArrayList list = new ArrayList(); for (String s : split) { - s = s.trim().toLowerCase(); + s = s.trim().toLowerCase(Locale.getDefault()); if (s.length() > 0) { list.add(s); } @@ -762,7 +763,7 @@ public class ThrustCurveMotorSelectionPanel extends JPanel implements MotorSelec s = s.trim(); if (s.length() == 0) { //// No description available. - comment.setText("No description available."); + comment.setText(trans.get("TCMotorSelPan.noDescription")); comment.setFont(noCommentFont); comment.setForeground(NO_COMMENT_COLOR); } else { @@ -776,7 +777,7 @@ public class ThrustCurveMotorSelectionPanel extends JPanel implements MotorSelec private void scrollSelectionVisible() { if (selectedMotorSet != null) { int index = table.convertRowIndexToView(model.getIndex(selectedMotorSet)); - System.out.println("index=" + index); + //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); @@ -943,7 +944,7 @@ public class ThrustCurveMotorSelectionPanel extends JPanel implements MotorSelec public boolean filterByString(ThrustCurveMotorSet m) { main: for (String s : searchTerms) { for (ThrustCurveMotorColumns col : ThrustCurveMotorColumns.values()) { - String str = col.getValue(m).toString().toLowerCase(); + String str = col.getValue(m).toString().toLowerCase(Locale.getDefault()); if (str.indexOf(s) >= 0) continue main; } diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java index 033da286..7a0ecc5f 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/optimization/GeneralOptimizationDialog.java @@ -108,7 +108,7 @@ public class GeneralOptimizationDialog extends JDialog { 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"); @@ -116,17 +116,17 @@ public class GeneralOptimizationDialog extends JDialog { 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; @@ -177,7 +177,7 @@ public class GeneralOptimizationDialog extends JDialog { /** The optimization worker that is running */ private OptimizationWorker worker = null; - + private double bestValue = Double.NaN; private Unit bestValueUnit = Unit.NOUNIT2; private int stepCount = 0; @@ -187,7 +187,7 @@ public class GeneralOptimizationDialog extends JDialog { private final Map evaluationHistory = new LinkedHashMap(); private final List optimizationPath = new LinkedList(); - + private boolean updating = false; @@ -213,7 +213,7 @@ public class GeneralOptimizationDialog extends JDialog { JPanel panel = new JPanel(new MigLayout("fill")); - + ChangeListener clearHistoryChangeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { @@ -227,8 +227,8 @@ public class GeneralOptimizationDialog extends JDialog { } }; - - + + //// Selected modifiers table selectedModifierTableModel = new ParameterSelectionTableModel(); @@ -275,8 +275,8 @@ public class GeneralOptimizationDialog extends JDialog { disableComponents.add(selectedModifierDescription); panel.add(selectedModifierDescription, "growx"); - - + + //// Add/remove buttons sub = new JPanel(new MigLayout("fill")); @@ -331,8 +331,8 @@ public class GeneralOptimizationDialog extends JDialog { panel.add(sub); - - + + //// Available modifier tree availableModifierTree = new SimulationModifierTree(documentCopy.getRocket(), simulationModifiers, selectedModifiers); availableModifierTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @@ -365,9 +365,9 @@ public class GeneralOptimizationDialog extends JDialog { 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")); @@ -376,7 +376,7 @@ public class GeneralOptimizationDialog extends JDialog { sub.setBorder(border); disableComponents.add(sub); - + //// Simulation to optimize label = new JLabel(trans.get("lbl.optimizeSim")); @@ -392,8 +392,8 @@ public class GeneralOptimizationDialog extends JDialog { 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"); @@ -408,8 +408,8 @@ public class GeneralOptimizationDialog extends JDialog { disableComponents.add(optimizationParameterCombo); sub.add(optimizationParameterCombo, "growx, wrap unrel"); - - + + //// Optimization goal label = new JLabel(trans.get("lbl.optimizeGoal")); tip = trans.get("lbl.optimizeGoal"); @@ -424,7 +424,7 @@ public class GeneralOptimizationDialog extends JDialog { disableComponents.add(optimizationGoalCombo); sub.add(optimizationGoalCombo, "growx"); - + //// Optimization custom value optimizationSeekValue = new DoubleModel(0, UnitGroup.UNITS_NONE); optimizationSeekValue.addChangeListener(clearHistoryChangeListener); @@ -441,11 +441,11 @@ public class GeneralOptimizationDialog extends JDialog { disableComponents.add(optimizationGoalUnitSelector); sub.add(optimizationGoalUnitSelector, "width 20lp, wrap unrel"); - + panel.add(sub, "grow"); - - + + //// Required stability sub-panel sub = new JPanel(new MigLayout("fill")); @@ -454,15 +454,15 @@ public class GeneralOptimizationDialog extends JDialog { 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")); @@ -488,7 +488,7 @@ public class GeneralOptimizationDialog extends JDialog { disableComponents.add(minimumStabilityUnitSelector); sub.add(minimumStabilityUnitSelector, "growx, wrap unrel"); - + //// Maximum stability tip = trans.get("lbl.requireMaxStability.ttip"); maximumStabilitySelected = new JCheckBox(trans.get("lbl.requireMaxStability")); @@ -513,20 +513,20 @@ public class GeneralOptimizationDialog extends JDialog { 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); @@ -534,10 +534,10 @@ public class GeneralOptimizationDialog extends JDialog { 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); @@ -547,7 +547,7 @@ public class GeneralOptimizationDialog extends JDialog { 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); @@ -557,7 +557,7 @@ public class GeneralOptimizationDialog extends JDialog { stepCountLabel.setToolTipText(tip); sub.add(stepCountLabel, "wrap rel"); - + label = new JLabel(trans.get("status.evalCount")); tip = trans.get("status.evalCount.ttip"); label.setToolTipText(tip); @@ -567,7 +567,7 @@ public class GeneralOptimizationDialog extends JDialog { evaluationCountLabel.setToolTipText(tip); sub.add(evaluationCountLabel, "wrap rel"); - + label = new JLabel(trans.get("status.stepSize")); tip = trans.get("status.stepSize.ttip"); label.setToolTipText(tip); @@ -577,7 +577,7 @@ public class GeneralOptimizationDialog extends JDialog { stepSizeLabel.setToolTipText(tip); sub.add(stepSizeLabel, "wrap para"); - + //// Start/Stop button startButton = new JToggleButton(START_TEXT); @@ -599,7 +599,7 @@ public class GeneralOptimizationDialog extends JDialog { }); 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() { @@ -619,7 +619,7 @@ public class GeneralOptimizationDialog extends JDialog { 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() { @@ -632,13 +632,13 @@ public class GeneralOptimizationDialog extends JDialog { disableComponents.add(saveButton); sub.add(saveButton, "span, growx"); - - + + panel.add(sub, "wrap para*2"); - - - + + + //// Bottom buttons applyButton = new JButton(trans.get("btn.apply")); @@ -677,7 +677,7 @@ public class GeneralOptimizationDialog extends JDialog { }); panel.add(closeButton, "right"); - + this.add(panel); clearHistory(); updateComponents(); @@ -691,7 +691,7 @@ public class GeneralOptimizationDialog extends JDialog { return; } - + if (selectedModifiers.isEmpty()) { JOptionPane.showMessageDialog(this, trans.get("error.selectParams.text"), trans.get("error.selectParams.title"), JOptionPane.ERROR_MESSAGE); @@ -702,7 +702,7 @@ public class GeneralOptimizationDialog extends JDialog { return; } - + running = true; // Update the button status @@ -711,7 +711,7 @@ public class GeneralOptimizationDialog extends JDialog { 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(); @@ -740,7 +740,7 @@ public class GeneralOptimizationDialog extends JDialog { * 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) { @@ -761,7 +761,7 @@ public class GeneralOptimizationDialog extends JDialog { maxAbsolute = true; } - + if (!minimumStabilitySelected.isSelected()) { min = Double.NaN; minAbsolute = maxAbsolute; @@ -789,7 +789,7 @@ public class GeneralOptimizationDialog extends JDialog { new Object[] { trans.get("error.optimizationFailure.text"), exception.getLocalizedMessage() - }, trans.get("error.optimizationFailure.title"), JOptionPane.ERROR_MESSAGE); + }, trans.get("error.optimizationFailure.title"), JOptionPane.ERROR_MESSAGE); } worker = null; @@ -862,7 +862,7 @@ public class GeneralOptimizationDialog extends JDialog { }; worker.start(); - + clearHistory(); updateComponents(); @@ -889,13 +889,13 @@ public class GeneralOptimizationDialog extends JDialog { startButton.setText(START_TEXT); updating = false; - + updateComponents(); } - - + + /** * Reset the current optimization history and values. This does not reset the design. */ @@ -969,7 +969,7 @@ public class GeneralOptimizationDialog extends JDialog { availableModifierTree.populateTree(documentCopy.getRocket(), simulationModifiers); availableModifierTree.expandComponents(); - + // Update selectable simulations populateSimulations(); @@ -986,7 +986,7 @@ public class GeneralOptimizationDialog extends JDialog { current = selection.toString(); } - + List> simulations = new ArrayList>(); Rocket rocket = documentCopy.getRocket(); @@ -1006,15 +1006,15 @@ public class GeneralOptimizationDialog extends JDialog { 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.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)) { @@ -1102,7 +1102,7 @@ public class GeneralOptimizationDialog extends JDialog { } - + private void addModifier(SimulationModifier mod) { if (!selectedModifiers.contains(mod)) { log.user(1, "Adding simulation modifier " + mod); @@ -1124,7 +1124,7 @@ public class GeneralOptimizationDialog extends JDialog { } - + /** * Update the enabled status of all components in the dialog. */ @@ -1140,7 +1140,7 @@ public class GeneralOptimizationDialog extends JDialog { updating = true; - + // First enable all components if optimization not running if (!running) { log.debug("Initially enabling all components"); @@ -1149,7 +1149,7 @@ public class GeneralOptimizationDialog extends JDialog { } } - + // "Add" button SimulationModifier mod = getSelectedAvailableModifier(); state = (mod != null && !selectedModifiers.contains(mod)); @@ -1166,7 +1166,7 @@ public class GeneralOptimizationDialog extends JDialog { log.debug("removeAllButton enabled: " + state); removeAllButton.setEnabled(state); - + // Optimization goal String selected = (String) optimizationGoalCombo.getSelectedItem(); state = GOAL_SEEK.equals(selected); @@ -1174,7 +1174,7 @@ public class GeneralOptimizationDialog extends JDialog { optimizationGoalSpinner.setVisible(state); optimizationGoalUnitSelector.setVisible(state); - + // Minimum/maximum stability options state = minimumStabilitySelected.isSelected(); log.debug("minimumStabilitySpinner & UnitSelector enabled: " + state); @@ -1186,7 +1186,7 @@ public class GeneralOptimizationDialog extends JDialog { 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() + @@ -1198,7 +1198,7 @@ public class GeneralOptimizationDialog extends JDialog { 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"); @@ -1207,7 +1207,7 @@ public class GeneralOptimizationDialog extends JDialog { } } - + // Update description text mod = getSelectedModifier(); if (mod != null) { @@ -1216,7 +1216,7 @@ public class GeneralOptimizationDialog extends JDialog { selectedModifierDescription.setText(""); } - + // Update the figure figure.setConfiguration(getSelectedSimulation().getConfiguration()); @@ -1233,7 +1233,7 @@ public class GeneralOptimizationDialog extends JDialog { 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()); @@ -1282,7 +1282,7 @@ public class GeneralOptimizationDialog extends JDialog { writer.write("\n"); } - + for (FunctionEvaluationData data : evaluationHistory.values()) { Value[] state = data.getState(); @@ -1334,7 +1334,17 @@ public class GeneralOptimizationDialog extends JDialog { */ @SuppressWarnings("unchecked") private Simulation getSelectedSimulation() { - return ((Named) simulationSelectionCombo.getSelectedItem()).get(); + /* 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(); } @@ -1580,6 +1590,6 @@ public class GeneralOptimizationDialog extends JDialog { } } - - + + } diff --git a/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java b/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java index 1e7e47f0..663c79b8 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java +++ b/core/src/net/sf/openrocket/gui/dialogs/optimization/SimulationModifierTree.java @@ -16,9 +16,11 @@ 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; /** @@ -32,6 +34,7 @@ import net.sf.openrocket.util.TextUtil; public class SimulationModifierTree extends BasicTree { private final List selectedModifiers; + private static final Translator trans = Application.getTranslator(); /** * Sole constructor. @@ -76,7 +79,7 @@ public class SimulationModifierTree extends BasicTree { DefaultMutableTreeNode modifierNode; if (component.getChildCount() > 0) { - modifierNode = new DefaultMutableTreeNode("Optimization parameters"); + modifierNode = new DefaultMutableTreeNode(trans.get("SimulationModifierTree.OptimizationParameters")); node.add(modifierNode); } else { modifierNode = node; diff --git a/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java b/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java index 986c4a40..a3d963ee 100644 --- a/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java +++ b/core/src/net/sf/openrocket/gui/dialogs/preferences/PreferencesDialog.java @@ -388,7 +388,6 @@ public class PreferencesDialog extends JDialog { 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)); @@ -403,10 +402,16 @@ public class PreferencesDialog extends JDialog { //// 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() { diff --git a/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetChooserDialog.java b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetChooserDialog.java new file mode 100644 index 00000000..9efa3675 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetChooserDialog.java @@ -0,0 +1,298 @@ +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 new file mode 100644 index 00000000..7c66aa13 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetRowFilter.java @@ -0,0 +1,38 @@ +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 new file mode 100644 index 00000000..cad447f1 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTable.java @@ -0,0 +1,283 @@ +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 new file mode 100644 index 00000000..5d5d12d6 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/dialogs/preset/ComponentPresetTableColumn.java @@ -0,0 +1,84 @@ +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 new file mode 100644 index 00000000..ac05c789 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/dialogs/preset/XTableColumnModel.java @@ -0,0 +1,242 @@ +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 new file mode 100644 index 00000000..80cdbfc0 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/figure3d/ComponentRenderer.java @@ -0,0 +1,340 @@ +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 new file mode 100644 index 00000000..4c1d9344 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/figure3d/MassObjectRenderer.java @@ -0,0 +1,263 @@ +/* + ** 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 new file mode 100644 index 00000000..d7c2e842 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/figure3d/Quick3dMain.java @@ -0,0 +1,76 @@ +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 new file mode 100644 index 00000000..8df1e850 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/figure3d/RocketFigure3d.java @@ -0,0 +1,628 @@ +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 new file mode 100644 index 00000000..49341020 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/figure3d/RocketRenderer.java @@ -0,0 +1,303 @@ +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 new file mode 100644 index 00000000..3789a780 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/figure3d/TransitionRenderer.java @@ -0,0 +1,247 @@ +/* + ** 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/main/BasicFrame.java b/core/src/net/sf/openrocket/gui/main/BasicFrame.java index c05c1ba3..bdfcbd4a 100644 --- a/core/src/net/sf/openrocket/gui/main/BasicFrame.java +++ b/core/src/net/sf/openrocket/gui/main/BasicFrame.java @@ -1,62 +1,5 @@ package net.sf.openrocket.gui.main; -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; - -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 net.miginfocom.swing.MigLayout; import net.sf.openrocket.aerodynamics.WarningSet; import net.sf.openrocket.document.OpenRocketDocument; @@ -68,6 +11,7 @@ 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; @@ -105,149 +49,194 @@ 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(); - - - // Set replaceable flag to false at first modification - rocket.addComponentChangeListener(new ComponentChangeListener() { - @Override - public void componentChanged(ComponentChangeEvent e) { - replaceable = false; - BasicFrame.this.rocket.removeComponentChangeListener(this); - } - }); - - + // 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 + + // 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); @@ -257,12 +246,12 @@ public class BasicFrame extends JFrame { 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 @@ -271,15 +260,15 @@ public class BasicFrame extends JFrame { 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); @@ -289,9 +278,9 @@ public class BasicFrame extends JFrame { 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 @@ -309,7 +298,7 @@ public class BasicFrame extends JFrame { } }; tree.addMouseListener(ml); - + // Update dialog when selection is changed componentSelectionModel.addTreeSelectionListener(new TreeSelectionListener() { @Override @@ -319,7 +308,7 @@ public class BasicFrame extends JFrame { if (path == null) return; tree.scrollPathToVisible(path); - + if (!ComponentConfigDialog.isDialogVisible()) return; RocketComponent c = (RocketComponent) path.getLastPathComponent(); @@ -327,57 +316,57 @@ public class BasicFrame extends JFrame { 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. */ @@ -386,11 +375,11 @@ public class BasicFrame extends JFrame { if (path == null) return null; tree.scrollPathToVisible(path); - + return (RocketComponent) path.getLastPathComponent(); } - - + + /** * Creates the menu for the window. */ @@ -398,15 +387,15 @@ public class BasicFrame extends JFrame { 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 + + //// 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); @@ -418,14 +407,11 @@ public class BasicFrame extends JFrame { public void actionPerformed(ActionEvent e) { log.user("New... selected"); newAction(); - if (replaceable) { - log.info("Closing previous window"); - closeAction(); - } + 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)); @@ -440,7 +426,14 @@ public class BasicFrame extends JFrame { } }); 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 @@ -462,9 +455,9 @@ public class BasicFrame extends JFrame { } }); 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)); @@ -479,7 +472,7 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + //// Save as... item = new JMenuItem(trans.get("main.menu.file.saveAs"), KeyEvent.VK_A); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, @@ -495,7 +488,7 @@ public class BasicFrame extends JFrame { } }); 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)); @@ -510,10 +503,10 @@ public class BasicFrame extends JFrame { } }); 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)); @@ -528,9 +521,9 @@ public class BasicFrame extends JFrame { } }); 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)); @@ -545,26 +538,26 @@ public class BasicFrame extends JFrame { } }); 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)); @@ -572,26 +565,26 @@ public class BasicFrame extends JFrame { //// 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")); @@ -605,9 +598,9 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - - - + + + //// Preferences item = new JMenuItem(trans.get("main.menu.edit.preferences")); item.setIcon(Icons.PREFERENCES); @@ -621,17 +614,17 @@ public class BasicFrame extends JFrame { } }); 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 @@ -644,39 +637,49 @@ public class BasicFrame extends JFrame { } }); 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); + 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")); @@ -688,9 +691,9 @@ public class BasicFrame extends JFrame { } }); 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); @@ -703,7 +706,7 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + //// Debug log item = new JMenuItem(trans.get("main.menu.help.debugLog")); item.setIcon(Icons.HELP_DEBUG_LOG); @@ -716,10 +719,10 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + menu.addSeparator(); - - + + //// License item = new JMenuItem(trans.get("main.menu.help.license"), KeyEvent.VK_L); item.setIcon(Icons.HELP_LICENSE); @@ -732,8 +735,8 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - - + + //// About item = new JMenuItem(trans.get("main.menu.help.about"), KeyEvent.VK_A); item.setIcon(Icons.HELP_ABOUT); @@ -746,24 +749,24 @@ public class BasicFrame extends JFrame { } }); 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() { @@ -781,9 +784,9 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + menu.addSeparator(); - + //// Create test rocket item = new JMenuItem("Create test rocket"); item.addActionListener(new ActionListener() { @@ -798,7 +801,7 @@ public class BasicFrame extends JFrame { JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Random", "OK" }, "OK"); - + Rocket r; if (sel == 0) { r = new TestRockets(null).makeTestRocket(); @@ -807,7 +810,7 @@ public class BasicFrame extends JFrame { } else { return; } - + OpenRocketDocument doc = new OpenRocketDocument(r); doc.setSaved(true); BasicFrame frame = new BasicFrame(doc); @@ -815,9 +818,9 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - - - + + + item = new JMenuItem("Create 'Iso-Haisu'"); item.addActionListener(new ActionListener() { @Override @@ -831,8 +834,8 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - - + + item = new JMenuItem("Create 'Big Blue'"); item.addActionListener(new ActionListener() { @Override @@ -846,16 +849,16 @@ public class BasicFrame extends JFrame { } }); 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(); @@ -872,7 +875,7 @@ public class BasicFrame extends JFrame { o = null; } sb.append("Total: " + count); - + // Get basic memory stats System.gc(); long max = Runtime.getRuntime().maxMemory(); @@ -883,14 +886,14 @@ public class BasicFrame extends JFrame { 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() { @@ -920,10 +923,10 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - - + + menu.addSeparator(); - + //// Exception here item = new JMenuItem("Exception here"); item.addActionListener(new ActionListener() { @@ -934,7 +937,7 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + item = new JMenuItem("Exception from EDT"); item.addActionListener(new ActionListener() { @Override @@ -950,7 +953,7 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + item = new JMenuItem("Exception from other thread"); item.addActionListener(new ActionListener() { @Override @@ -965,7 +968,7 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - + item = new JMenuItem("OutOfMemoryError here"); item.addActionListener(new ActionListener() { @Override @@ -975,11 +978,11 @@ public class BasicFrame extends JFrame { } }); menu.add(item); - - + + menu.addSeparator(); - - + + item = new JMenuItem("Test popup"); item.addActionListener(new ActionListener() { @Override @@ -995,33 +998,33 @@ public class BasicFrame extends JFrame { } }); 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()); @@ -1030,31 +1033,33 @@ public class BasicFrame extends JFrame { 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)) { - - // 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(); - replaceable = false; - } + 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. @@ -1063,16 +1068,16 @@ public class BasicFrame extends JFrame { */ 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 { @@ -1080,44 +1085,38 @@ public class BasicFrame extends JFrame { } 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(); - if (open(is, filename, parent)) { - // Close previous window if replacing - if (parent.replaceable && parent.document.isSaved()) { - parent.closeAction(); - parent.replaceable = false; - } - } + 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. @@ -1127,12 +1126,12 @@ public class BasicFrame extends JFrame { 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. @@ -1141,11 +1140,11 @@ public class BasicFrame extends JFrame { 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). @@ -1153,9 +1152,9 @@ public class BasicFrame extends JFrame { * @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)) { @@ -1163,50 +1162,50 @@ public class BasicFrame extends JFrame { 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()) { @@ -1221,21 +1220,24 @@ public class BasicFrame extends JFrame { //// 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 @@ -1251,13 +1253,13 @@ public class BasicFrame extends JFrame { return saveAsAction(); } log.info("Saving document to " + file); - + if (FileHelper.ROCKSIM_DESIGN_FILTER.accept(file)) { return saveAsRocksim(file); } return saveAs(file); } - + /** * "Save As" action. * @@ -1272,13 +1274,13 @@ public class BasicFrame extends JFrame { */ 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); @@ -1291,22 +1293,22 @@ public class BasicFrame extends JFrame { 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); } @@ -1315,7 +1317,7 @@ public class BasicFrame extends JFrame { return FileHelper.confirmWrite(file, this) && saveAs(file); } } - + /** * Perform the writing of the design to the given file in Rocksim format. * @@ -1328,7 +1330,7 @@ public class BasicFrame extends JFrame { if (!FileHelper.confirmWrite(file, this)) { return false; } - + try { new RocksimSaver().save(file, document); return true; @@ -1336,7 +1338,7 @@ public class BasicFrame extends JFrame { return false; } } - + /** * Perform the writing of the design to the given file in OpenRocket format. * @@ -1347,25 +1349,25 @@ public class BasicFrame extends JFrame { 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); @@ -1373,9 +1375,9 @@ public class BasicFrame extends JFrame { 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[] { @@ -1385,15 +1387,15 @@ public class BasicFrame extends JFrame { } 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"); @@ -1420,14 +1422,14 @@ public class BasicFrame extends JFrame { 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"); @@ -1435,22 +1437,26 @@ public class BasicFrame extends JFrame { } return true; } - - - + + + /** - * + * */ public void printAction() { - new PrintDialog(this, document).setVisible(true); + 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 @@ -1458,13 +1464,14 @@ public class BasicFrame extends JFrame { rocket.addChild(stage); OpenRocketDocument doc = new OpenRocketDocument(rocket); doc.setSaved(true); - + BasicFrame frame = new BasicFrame(doc); frame.replaceable = true; frame.setVisible(true); - ComponentConfigDialog.showDialog(frame, doc, rocket); + // 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. */ @@ -1482,33 +1489,33 @@ public class BasicFrame extends JFrame { 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 + * 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. */ @@ -1522,11 +1529,11 @@ public class BasicFrame extends JFrame { 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. */ diff --git a/core/src/net/sf/openrocket/gui/main/MRUDesignFile.java b/core/src/net/sf/openrocket/gui/main/MRUDesignFile.java new file mode 100644 index 00000000..f32d23e8 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/main/MRUDesignFile.java @@ -0,0 +1,179 @@ +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 new file mode 100644 index 00000000..8757eaa2 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/main/MRUDesignFileAction.java @@ -0,0 +1,86 @@ +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/SimulationEditDialog.java b/core/src/net/sf/openrocket/gui/main/SimulationEditDialog.java index 2b5ca7e7..35c72db6 100644 --- a/core/src/net/sf/openrocket/gui/main/SimulationEditDialog.java +++ b/core/src/net/sf/openrocket/gui/main/SimulationEditDialog.java @@ -30,6 +30,7 @@ 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; @@ -82,19 +83,20 @@ public class SimulationEditDialog extends JDialog { 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, Simulation s) { - this(parent, s, 0); + public SimulationEditDialog(Window parent, OpenRocketDocument document, Simulation s) { + this(parent, document, s, 0); } - public SimulationEditDialog(Window parent, Simulation s, int tab) { + 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(); @@ -125,7 +127,7 @@ public class SimulationEditDialog extends JDialog { String name = field.getText(); if (name == null || name.equals("")) return; - System.out.println("Setting name:" + name); + //System.out.println("Setting name:" + name); simulation.setName(name); } @@ -169,7 +171,7 @@ public class SimulationEditDialog extends JDialog { @Override public void actionPerformed(ActionEvent e) { SimulationEditDialog.this.dispose(); - SimulationRunDialog.runSimulations(parentWindow, simulation); + SimulationRunDialog.runSimulations(parentWindow, SimulationEditDialog.this.document, simulation); } }); mainPanel.add(button, "gapright para"); @@ -241,7 +243,7 @@ public class SimulationEditDialog extends JDialog { label.setToolTipText(tip); sub.add(label); - m = new DoubleModel(conditions, "WindSpeedAverage", UnitGroup.UNITS_VELOCITY, 0); + m = new DoubleModel(conditions, "WindSpeedAverage", UnitGroup.UNITS_WINDSPEED, 0); spin = new JSpinner(m.getSpinnerModel()); spin.setEditor(new SpinnerEditor(spin)); @@ -266,7 +268,7 @@ public class SimulationEditDialog extends JDialog { label.setToolTipText(tip); sub.add(label); - m = new DoubleModel(conditions, "WindSpeedDeviation", UnitGroup.UNITS_VELOCITY, 0); + m = new DoubleModel(conditions, "WindSpeedDeviation", UnitGroup.UNITS_WINDSPEED, 0); DoubleModel m2 = new DoubleModel(conditions, "WindSpeedAverage", 0.25, UnitGroup.UNITS_COEFFICIENT, 0); @@ -834,9 +836,6 @@ public class SimulationEditDialog extends JDialog { return new SimulationExportPanel(simulation); } - - - /** * Return a panel stating that there is no data available, and that the user diff --git a/core/src/net/sf/openrocket/gui/main/SimulationPanel.java b/core/src/net/sf/openrocket/gui/main/SimulationPanel.java index 719e1cf6..b12b8561 100644 --- a/core/src/net/sf/openrocket/gui/main/SimulationPanel.java +++ b/core/src/net/sf/openrocket/gui/main/SimulationPanel.java @@ -135,7 +135,7 @@ public class SimulationPanel extends JPanel { long t = System.currentTimeMillis(); new SimulationRunDialog(SwingUtilities.getWindowAncestor( - SimulationPanel.this), sims).setVisible(true); + SimulationPanel.this), document, sims).setVisible(true); log.info("Running simulations took " + (System.currentTimeMillis() - t) + " ms"); fireMaintainSelection(); } @@ -514,7 +514,7 @@ public class SimulationPanel extends JPanel { } private void openDialog(final Simulation sim, int position) { - new SimulationEditDialog(SwingUtilities.getWindowAncestor(this), sim, position) + new SimulationEditDialog(SwingUtilities.getWindowAncestor(this), document, sim, position) .setVisible(true); fireMaintainSelection(); } @@ -571,42 +571,38 @@ public class SimulationPanel extends JPanel { tip = "" + sim.getName() + "
"; switch (sim.getStatus()) { case UPTODATE: - //// Up to date
- tip += "Up to date
"; + tip += trans.get ("simpanel.ttip.uptodate") + "
"; break; case LOADED: - //// Data loaded from a file
- tip += "Data loaded from a file
"; + tip += trans.get ("simpanel.ttip.loaded") + "
"; break; case OUTDATED: - tip += "Data is out of date
"; - tip += "Click Run simulations to simulate.
"; + tip += trans.get ("simpanel.ttip.outdated") + "
"; break; case EXTERNAL: - tip += "Imported data
"; + tip += trans.get ("simpanel.ttip.external") + "
"; return tip; case NOT_SIMULATED: - tip += "Not simulated yet
"; - tip += "Click Run simulations to simulate."; + tip += trans.get ("simpanel.ttip.notSimulated"); return tip; } if (data == null) { - tip += "No simulation data available."; + tip += trans.get ("simpanel.ttip.noData"); return tip; } WarningSet warnings = data.getWarningSet(); if (warnings.isEmpty()) { - tip += "No warnings."; + tip += trans.get ("simpanel.ttip.noWarnings"); return tip; } - tip += "Warnings:"; + tip += trans.get ("simpanel.ttip.warnings"); for (Warning w : warnings) { tip += "
" + w.toString(); } diff --git a/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java b/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java index f85b248f..65fabb8f 100644 --- a/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java +++ b/core/src/net/sf/openrocket/gui/main/SimulationRunDialog.java @@ -10,8 +10,11 @@ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Iterator; import java.util.List; -import java.util.concurrent.ExecutorService; 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; @@ -21,6 +24,7 @@ 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; @@ -32,6 +36,8 @@ 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; @@ -58,8 +64,28 @@ public class SimulationRunDialog extends JDialog { private static final double APOGEE_PROGRESS = 0.7; - private final static ExecutorService executor = Executors.newFixedThreadPool( - SwingPreferences.getMaxThreadCount()); + /** + * 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; @@ -72,6 +98,7 @@ public class SimulationRunDialog extends JDialog { * 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; @@ -79,9 +106,10 @@ public class SimulationRunDialog extends JDialog { private final double[] simulationMaxVelocity; private final boolean[] simulationDone; - public SimulationRunDialog(Window window, Simulation... simulations) { + 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"); @@ -106,7 +134,7 @@ public class SimulationRunDialog extends JDialog { for (int i = 0; i < n; i++) { simulationNames[i] = simulations[i].getName(); - simulationWorkers[i] = new InteractiveSimulationWorker(simulations[i], i); + simulationWorkers[i] = new InteractiveSimulationWorker(document, simulations[i], i); executor.execute(simulationWorkers[i]); } @@ -172,10 +200,10 @@ public class SimulationRunDialog extends JDialog { * the Cancel button on the dialog. */ public void cancelSimulations() { - executor.shutdownNow(); for (SimulationWorker w : simulationWorkers) { w.cancel(true); } + executor.purge(); } @@ -185,8 +213,8 @@ public class SimulationRunDialog extends JDialog { * @param parent the parent Window of the dialog to use. * @param simulations the simulations to run. */ - public static void runSimulations(Window parent, Simulation... simulations) { - new SimulationRunDialog(parent, simulations).setVisible(true); + public static void runSimulations(Window parent, OpenRocketDocument document, Simulation... simulations) { + new SimulationRunDialog(parent, document, simulations).setVisible(true); } @@ -254,6 +282,8 @@ public class SimulationRunDialog extends JDialog { private volatile double burnoutVelocity; private volatile double apogeeAltitude; + private final CustomExpressionSimulationListener exprListener; + /* * -2 = time from 0 ... burnoutTimeEstimate * -1 = velocity from v(burnoutTimeEstimate) ... 0 @@ -264,8 +294,10 @@ public class SimulationRunDialog extends JDialog { private int progress = 0; - public InteractiveSimulationWorker(Simulation sim, int index) { + 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 @@ -291,7 +323,7 @@ public class SimulationRunDialog extends JDialog { */ @Override protected SimulationListener[] getExtraListeners() { - return new SimulationListener[] { new SimulationProgressListener() }; + return new SimulationListener[] { new SimulationProgressListener(), exprListener }; } diff --git a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java b/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java index a7e8386e..6fe9fe1d 100644 --- a/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java +++ b/core/src/net/sf/openrocket/gui/main/componenttree/ComponentTreeRenderer.java @@ -9,6 +9,7 @@ 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 { @@ -21,25 +22,38 @@ public class ComponentTreeRenderer extends DefaultTreeCellRenderer { boolean expanded, boolean leaf, int row, - boolean hasFocus) { + boolean hasFocus1) { - super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + 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", "
"); - this.setToolTipText(comment); - } else { - this.setToolTipText(null); + comment = comment.replace("\n", "
"); + sb.append("
").append(comment); } - return this; + return sb.toString(); } } diff --git a/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java b/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java index bd58782f..4438b207 100644 --- a/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java +++ b/core/src/net/sf/openrocket/gui/plot/PlotConfiguration.java @@ -63,7 +63,7 @@ public class PlotConfiguration implements Cloneable { configs.add(config); //// Stability vs. time - config = new PlotConfiguration("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); @@ -76,7 +76,7 @@ public class PlotConfiguration implements Cloneable { configs.add(config); //// Drag coefficients vs. Mach number - config = new PlotConfiguration("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); @@ -85,7 +85,7 @@ public class PlotConfiguration implements Cloneable { configs.add(config); //// Roll characteristics - config = new PlotConfiguration("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); @@ -100,7 +100,7 @@ public class PlotConfiguration implements Cloneable { configs.add(config); //// Angle of attack and orientation vs. time - config = new PlotConfiguration("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); @@ -113,7 +113,7 @@ public class PlotConfiguration implements Cloneable { configs.add(config); //// Simulation time step and computation time - config = new PlotConfiguration("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); @@ -358,7 +358,7 @@ public class PlotConfiguration implements Cloneable { */ public PlotConfiguration fillAutoAxes(FlightDataBranch data) { PlotConfiguration config = recursiveFillAutoAxes(data).getU(); - System.out.println("BEST FOUND, fitting"); + //System.out.println("BEST FOUND, fitting"); config.fitAxes(data); return config; } @@ -483,13 +483,13 @@ public class PlotConfiguration implements Cloneable { double scale = Math.max(left.getRangeLength(), right.getRangeLength()) / Math.min(left.getRangeLength(), right.getRangeLength()); - System.out.println("Scale: " + scale); + //System.out.println("Scale: " + scale); scale = roundScale(scale); if (right.getRangeLength() > left.getRangeLength()) { scale = 1 / scale; } - System.out.println("Rounded scale: " + scale); + //System.out.println("Rounded scale: " + scale); // Scale right axis, enlarge axes if necessary and scale back min2 *= scale; diff --git a/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java b/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java index d26ea7c2..ada19bfc 100644 --- a/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java +++ b/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java @@ -115,7 +115,7 @@ public class SimulationPlotDialog extends JDialog { is = ClassLoader.getSystemResourceAsStream(file); if (is == null) { - System.out.println("ERROR: File " + file + " not found!"); + //System.out.println("ERROR: File " + file + " not found!"); return; } diff --git a/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java b/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java index 06544f52..515ad0c8 100644 --- a/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java +++ b/core/src/net/sf/openrocket/gui/plot/SimulationPlotPanel.java @@ -119,8 +119,16 @@ public class SimulationPlotPanel extends JPanel { } 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(); @@ -357,7 +365,9 @@ public class SimulationPlotPanel extends JPanel { typeSelectorPanel.add(new PlotTypeSelector(i, type, unit, axis), "wrap"); } - typeSelectorPanel.repaint(); + // In order to consistantly update the ui, we need to validate before repaint. + typeSelectorPanel.validate(); + typeSelectorPanel.repaint(); eventTableModel.fireTableDataChanged(); } diff --git a/core/src/net/sf/openrocket/gui/plugin/DoSomethingPlugin.java b/core/src/net/sf/openrocket/gui/plugin/DoSomethingPlugin.java new file mode 100644 index 00000000..d238c4eb --- /dev/null +++ b/core/src/net/sf/openrocket/gui/plugin/DoSomethingPlugin.java @@ -0,0 +1,16 @@ +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 new file mode 100644 index 00000000..e76e64a2 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/plugin/OpenRocketSwingMenuPlugin.java @@ -0,0 +1,22 @@ +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 new file mode 100644 index 00000000..e27b78ac --- /dev/null +++ b/core/src/net/sf/openrocket/gui/plugin/SwingMenuPlugin.java @@ -0,0 +1,40 @@ +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 new file mode 100644 index 00000000..13b86535 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/ButtonColumn.java @@ -0,0 +1,238 @@ +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 new file mode 100644 index 00000000..9f11cdd6 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/ComponentPresetEditor.java @@ -0,0 +1,505 @@ +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 new file mode 100644 index 00000000..758a8507 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/DeselectableComboBox.java @@ -0,0 +1,83 @@ +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 new file mode 100644 index 00000000..bab36ec5 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/ImagePreviewPanel.java @@ -0,0 +1,105 @@ + +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 new file mode 100644 index 00000000..f51f2146 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/MaterialModel.java @@ -0,0 +1,138 @@ +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 new file mode 100644 index 00000000..9d1b220c --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/PresetEditorDialog.java @@ -0,0 +1,2217 @@ +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 new file mode 100644 index 00000000..a5c2e1be --- /dev/null +++ b/core/src/net/sf/openrocket/gui/preset/PresetResultListener.java @@ -0,0 +1,11 @@ + +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 new file mode 100644 index 00000000..585e4975 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/print/AbstractPrintable.java @@ -0,0 +1,80 @@ +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/AbstractPrintableTransition.java b/core/src/net/sf/openrocket/gui/print/AbstractPrintableTransition.java deleted file mode 100644 index 8e6042de..00000000 --- a/core/src/net/sf/openrocket/gui/print/AbstractPrintableTransition.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.sf.openrocket.gui.print; - -import net.sf.openrocket.rocketcomponent.Transition; - -import javax.swing.*; -import java.awt.*; -import java.awt.image.BufferedImage; - -public abstract class AbstractPrintableTransition extends JPanel { - /** - * The stroke of the transition arc. - */ - private final static BasicStroke thinStroke = new BasicStroke(1.0f); - - /** - * The X margin. - */ - protected int marginX = (int) PrintUnit.INCHES.toPoints(0.25f); - - /** - * The Y margin. - */ - protected int marginY = (int) PrintUnit.INCHES.toPoints(0.25f); - - /** - * 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 AbstractPrintableTransition(boolean isDoubleBuffered, Transition transition) { - super(isDoubleBuffered); - setBackground(Color.white); - init(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 transition component - */ - protected abstract void init(Transition 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 transition. 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() + marginX; - int height = getHeight() + marginY; - // 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); - - draw(g2); - } -} diff --git a/core/src/net/sf/openrocket/gui/print/DesignReport.java b/core/src/net/sf/openrocket/gui/print/DesignReport.java index e6290c3e..54c0f3eb 100644 --- a/core/src/net/sf/openrocket/gui/print/DesignReport.java +++ b/core/src/net/sf/openrocket/gui/print/DesignReport.java @@ -6,13 +6,13 @@ 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.gui.util.SwingPreferences; import net.sf.openrocket.logging.LogHelper; import net.sf.openrocket.masscalc.BasicMassCalculator; import net.sf.openrocket.masscalc.MassCalculator; @@ -75,27 +75,33 @@ import com.itextpdf.text.pdf.PdfWriter; * */ 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): "; @@ -121,19 +127,21 @@ public class DesignReport { 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) { + 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. * @@ -146,44 +154,38 @@ public class DesignReport { 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(); - try { - canvas.setFontAndSize(BaseFont.createFont(PrintUtilities.NORMAL.getFamilyname(), BaseFont.CP1252, - BaseFont.EMBEDDED), PrintUtilities.NORMAL_FONT_SIZE); - } catch (DocumentException e) { - log.error("Could not set font.", e); - } catch (IOException e) { - log.error("Could not create font.", e); - } + 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) { @@ -195,28 +197,29 @@ public class DesignReport { 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) { @@ -230,7 +233,8 @@ public class DesignReport { if (j > 1) { leading = 25; } - addFlightData(rocket, motorId, parent, leading); + FlightData flight = findSimulation(motorId, simulations); + addFlightData(flight, rocket, motorId, parent, leading); addMotorData(rocket, motorId, parent); document.add(parent); } @@ -239,8 +243,8 @@ public class DesignReport { log.error("Could not modify document.", e); } } - - + + /** * Paint a diagram of the rocket into the PDF document. * @@ -261,28 +265,33 @@ public class DesignReport { 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); - g2d.translate(20, 120); - - g2d.scale(0.4d, 0.4d); + 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. * @@ -291,41 +300,41 @@ public class DesignReport { * @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); + + 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)); - motorTable.addCell(ITextHelper.createCell(BURN_TIME, PdfPCell.BOTTOM)); - motorTable.addCell(ITextHelper.createCell(MAX_THRUST, PdfPCell.BOTTOM)); - motorTable.addCell(ITextHelper.createCell(TOTAL_IMPULSE, PdfPCell.BOTTOM)); - motorTable.addCell(ITextHelper.createCell(THRUST_TO_WT, PdfPCell.BOTTOM)); - motorTable.addCell(ITextHelper.createCell(PROPELLANT_WT, PdfPCell.BOTTOM)); - motorTable.addCell(ITextHelper.createCell(SIZE, PdfPCell.BOTTOM)); - + 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++; @@ -334,26 +343,26 @@ public class DesignReport { 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); @@ -365,21 +374,21 @@ public class DesignReport { 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; @@ -388,7 +397,7 @@ public class DesignReport { } } } - + if (totalMotorCount > 1) { int border = Rectangle.TOP; final PdfPCell motorVCell = ITextHelper.createCell("Total:", border); @@ -404,78 +413,67 @@ public class DesignReport { 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 motor data for a motor configuration to the table. + * 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 motor data will be added + * @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 Rocket theRocket, final String motorId, final PdfPTable parent, int leading) { - - // Perform flight simulation - Rocket duplicate = theRocket.copyWithOriginalID(); - FlightData flight = null; - try { - Simulation simulation = ((SwingPreferences)Application.getPreferences()).getBackgroundSimulation(duplicate); - simulation.getOptions().setMotorConfigurationID(motorId); - simulation.simulate(); - flight = simulation.getSimulatedData(); - } catch (SimulationException e1) { - // Ignore - } - - // Output the flight data + 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); @@ -487,8 +485,36 @@ public class DesignReport { } } } - - /** + + /** + * 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 @@ -498,7 +524,7 @@ public class DesignReport { private String stripBrackets(String target) { return stripLeftBracket(stripRightBracket(target)); } - + /** * Strip [ from a string. * @@ -509,7 +535,7 @@ public class DesignReport { private String stripLeftBracket(String target) { return target.replace("[", ""); } - + /** * Strip ] from a string. * @@ -520,5 +546,5 @@ public class DesignReport { 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 index f0be174d..64b617ab 100644 --- a/core/src/net/sf/openrocket/gui/print/FinMarkingGuide.java +++ b/core/src/net/sf/openrocket/gui/print/FinMarkingGuide.java @@ -9,8 +9,13 @@ import net.sf.openrocket.rocketcomponent.Rocket; import net.sf.openrocket.rocketcomponent.RocketComponent; import net.sf.openrocket.startup.Application; -import javax.swing.*; -import java.awt.*; +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; @@ -24,10 +29,10 @@ 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. + * 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 { @@ -42,6 +47,13 @@ public class FinMarkingGuide extends JPanel { */ 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. */ @@ -89,6 +101,7 @@ public class FinMarkingGuide extends JPanel { * 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) { @@ -103,7 +116,8 @@ public class FinMarkingGuide extends JPanel { RocketComponent next = iter.next(); if (next instanceof BodyTube) { current = (BodyTube) next; - } else if (next instanceof FinSet || next instanceof LaunchLug) { + } + else if (next instanceof FinSet || next instanceof LaunchLug) { java.util.List list = results.get(current); if (list == null && current != null) { list = new ArrayList(); @@ -198,9 +212,11 @@ public class FinMarkingGuide extends JPanel { * * |<-------- width ----------->| * - * yLLOffset is computed from the difference between the base rotation of the fin and the radial direction of the lug. + * 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. + * 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 @@ -224,13 +240,15 @@ public class FinMarkingGuide extends JPanel { int width = (int) PrintUnit.INCHES.toPoints(DEFAULT_GUIDE_WIDTH); int column = 0; + for (BodyTube next : markingGuideItems.keySet()) { - double circumferenceInPoints = PrintUnit.METERS.toPoints(next.getOuterRadius() * TWO_PI); + 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) (circumferenceInPoints), width); + drawMarkingGuide(g2, x, y, (int) Math.ceil(circumferenceInPoints), width); //Sort so that fins always precede lugs sort(componentList); @@ -258,7 +276,8 @@ public class FinMarkingGuide extends JPanel { baseRotation += TWO_PI / finCount; } offset = computeYOffset(y, circumferenceInPoints, baseSpacing, baseYOrigin, finRadial, baseRotation); - } else { + } + 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; @@ -274,15 +293,17 @@ public class FinMarkingGuide extends JPanel { if (fin > 0) { offset += baseSpacing; yLastFin = offset; - } else { + } + else { yFirstFin = offset; } drawDoubleArrowLine(g2, x, offset, x + width, offset); - // if (hasMultipleComponents) { - g2.drawString(externalComponent.getName(), x + (width / 3), offset - 2); - // } + // if (hasMultipleComponents) { + g2.drawString(externalComponent.getName(), x + (width / 3), offset - 2); + // } } - } else if (externalComponent instanceof LaunchLug) { + } + 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 @@ -290,7 +311,8 @@ public class FinMarkingGuide extends JPanel { //between their rotational directions. if (yLLOffset < 0) { yLLOffset = yLLOffset * circumferenceInPoints + yLastFin; - } else { + } + else { yLLOffset = yLLOffset * circumferenceInPoints + yFirstFin; } drawDoubleArrowLine(g2, x, (int) yLLOffset, x + width, (int) yLLOffset); @@ -308,7 +330,8 @@ public class FinMarkingGuide extends JPanel { if (column % 2 == 0) { x = MARGIN; y += circumferenceInPoints + MARGIN; - } else { + } + else { x += MARGIN + width; } } @@ -318,12 +341,13 @@ public class FinMarkingGuide extends JPanel { /** * 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 + * @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) { @@ -332,9 +356,11 @@ public class FinMarkingGuide extends JPanel { //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) { + } + else if (baseYOrigin - finRadialDifference * circumferenceInPoints > 0) { offset = (int) (finRadialDifference * circumferenceInPoints + baseYOrigin) + y; - } else { + } + else { offset = (int) (finRadialDifference * circumferenceInPoints - baseYOrigin) + y; } return offset; @@ -344,6 +370,7 @@ public class FinMarkingGuide extends JPanel { * 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) { @@ -381,7 +408,8 @@ public class FinMarkingGuide extends JPanel { * @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 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) { @@ -407,14 +435,15 @@ public class FinMarkingGuide extends JPanel { } /** - * 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). + * 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 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) { @@ -451,6 +480,4 @@ public class FinMarkingGuide extends JPanel { 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 index 0b2b6f95..45650543 100644 --- a/core/src/net/sf/openrocket/gui/print/ITextHelper.java +++ b/core/src/net/sf/openrocket/gui/print/ITextHelper.java @@ -3,6 +3,9 @@ */ 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; @@ -10,19 +13,24 @@ 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; -import java.awt.*; -import java.awt.image.BufferedImage; - /** * 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. * diff --git a/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java b/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java index 456495f3..5bfd924c 100644 --- a/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java +++ b/core/src/net/sf/openrocket/gui/print/OpenRocketPrintable.java @@ -22,29 +22,31 @@ public enum OpenRocketPrintable { 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, 5), + FIN_TEMPLATE("OpenRocketPrintable.Fintemplates", true, 6), // Fin marking guide. - FIN_MARKING_GUIDE("OpenRocketPrintable.Finmarkingguide", false, 6); - + 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. * @@ -57,7 +59,7 @@ public enum OpenRocketPrintable { stageSpecific = staged; order = idx; } - + /** * Get the description of this printable. * @@ -66,7 +68,7 @@ public enum OpenRocketPrintable { public String getDescription() { return trans.get(description); } - + /** * Answers if this enum value has different meaning depending upon the stage. * @@ -75,7 +77,7 @@ public enum OpenRocketPrintable { 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. @@ -85,7 +87,7 @@ public enum OpenRocketPrintable { public int getPrintOrder() { return order; } - + /** * Look up an enum value based on the description. * @@ -102,7 +104,7 @@ public enum OpenRocketPrintable { } return null; } - + /** * Get a list of ordered enum values that do not have stage affinity. * diff --git a/core/src/net/sf/openrocket/gui/print/PaperSize.java b/core/src/net/sf/openrocket/gui/print/PaperSize.java index d3d07410..1908fa28 100644 --- a/core/src/net/sf/openrocket/gui/print/PaperSize.java +++ b/core/src/net/sf/openrocket/gui/print/PaperSize.java @@ -36,7 +36,7 @@ public enum PaperSize { } - + ////////////////////////// private static final LogHelper log = Application.getLogger(); @@ -181,7 +181,7 @@ public enum PaperSize { return null; } - country = country.toUpperCase(); + country = country.toUpperCase(Locale.ENGLISH); for (String c : letterCountries) { if (c.equals(country)) { return LETTER; diff --git a/core/src/net/sf/openrocket/gui/print/PrintController.java b/core/src/net/sf/openrocket/gui/print/PrintController.java index 69e4df05..2e62df2a 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintController.java +++ b/core/src/net/sf/openrocket/gui/print/PrintController.java @@ -12,8 +12,11 @@ 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; @@ -27,103 +30,136 @@ import java.util.Set; * 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 - */ - public void print(OpenRocketDocument doc, Iterator toBePrinted, OutputStream outputFile, - PrintSettings settings) { - - 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) { - } - while (toBePrinted.hasNext()) { - PrintableContext printableContext = toBePrinted.next(); - - Set stages = printableContext.getStageNumber(); - - switch (printableContext.getPrintable()) { - case DESIGN_REPORT: - DesignReport dp = new DesignReport(doc, idoc); - dp.writeToDocument(writer); - idoc.newPage(); - break; - case FIN_TEMPLATE: - final FinSetPrintStrategy finWriter = new FinSetPrintStrategy(idoc, - writer, - stages); - finWriter.writeToDocument(doc.getRocket()); - 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); - tranWriter.writeToDocument(doc.getRocket(), false); - idoc.newPage(); - break; - - case NOSE_CONE_TEMPLATE: - final TransitionStrategy coneWriter = new TransitionStrategy(idoc, writer, stages); - coneWriter.writeToDocument(doc.getRocket(), true); - idoc.newPage(); - break; - - case FIN_MARKING_GUIDE: - final FinMarkingGuideStrategy fmg = new FinMarkingGuideStrategy(idoc, writer); - fmg.writeToDocument(doc.getRocket()); - idoc.newPage(); - break; + + /** + * 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) { } - } - //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()); - } - + } + } + } + + /** + * 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 index 3f4655c6..648e7231 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintFigure.java +++ b/core/src/net/sf/openrocket/gui/print/PrintFigure.java @@ -31,4 +31,8 @@ public class PrintFigure extends RocketFigure { this.scale = theScale; //dpi/0.0254*scaling; updateFigure(); } + + public double getFigureHeightPx() { + return this.figureHeightPx; + } } diff --git a/core/src/net/sf/openrocket/gui/print/PrintUnit.java b/core/src/net/sf/openrocket/gui/print/PrintUnit.java index c603f2f9..734e433b 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintUnit.java +++ b/core/src/net/sf/openrocket/gui/print/PrintUnit.java @@ -7,12 +7,20 @@ 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 long toPoints(double d) { return (long)(d * POINTS_PER_INCH); } + public double toPoints(double d) { return (d * POINTS_PER_INCH); } public double convert(double d, PrintUnit u) { return u.toInches(d); } }, MILLIMETERS { @@ -20,7 +28,7 @@ public enum PrintUnit { 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 long toPoints(double d) { return INCHES.toPoints(toInches(d)); } + public double toPoints(double d) { return INCHES.toPoints(toInches(d)); } public double convert(double d, PrintUnit u) { return u.toMillis(d); } }, CENTIMETERS { @@ -28,7 +36,7 @@ public enum PrintUnit { 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 long toPoints(double d) { return INCHES.toPoints(toInches(d)); } + public double toPoints(double d) { return INCHES.toPoints(toInches(d)); } public double convert(double d, PrintUnit u) { return u.toCentis(d); } }, METERS { @@ -36,7 +44,7 @@ public enum PrintUnit { 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 long toPoints(double d) { return INCHES.toPoints(toInches(d)); } + public double toPoints(double d) { return INCHES.toPoints(toInches(d)); } public double convert(double d, PrintUnit u) { return u.toMeters(d); } }, POINTS { @@ -44,19 +52,20 @@ public enum PrintUnit { 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 long toPoints(double d) { return (long)d; } + 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; @@ -151,7 +160,7 @@ public enum PrintUnit { * overflow, or Long.MAX_VALUE if it would positively overflow. * @see #convert */ - public long toPoints(double length) { + public double toPoints(double length) { throw new AbstractMethodError(); } diff --git a/core/src/net/sf/openrocket/gui/print/PrintUtilities.java b/core/src/net/sf/openrocket/gui/print/PrintUtilities.java index 7f096efc..3e8af143 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintUtilities.java +++ b/core/src/net/sf/openrocket/gui/print/PrintUtilities.java @@ -34,12 +34,12 @@ public class PrintUtilities implements Printable { 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(Font.FontFamily.HELVETICA, NORMAL_FONT_SIZE, Font.BOLD); - public static final Font BIG_BOLD = new Font(Font.FontFamily.HELVETICA, NORMAL_FONT_SIZE + 3, Font.BOLD); - public static final Font BOLD_UNDERLINED = new Font(Font.FontFamily.HELVETICA, NORMAL_FONT_SIZE, + 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(Font.FontFamily.HELVETICA, NORMAL_FONT_SIZE); - public static final Font SMALL = new Font(Font.FontFamily.HELVETICA, SMALL_FONT_SIZE); + 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; diff --git a/core/src/net/sf/openrocket/gui/print/PrintableCenteringRing.java b/core/src/net/sf/openrocket/gui/print/PrintableCenteringRing.java new file mode 100644 index 00000000..00c4e89c --- /dev/null +++ b/core/src/net/sf/openrocket/gui/print/PrintableCenteringRing.java @@ -0,0 +1,196 @@ +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 new file mode 100644 index 00000000..de345fb9 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/print/PrintableComponent.java @@ -0,0 +1,122 @@ +/* + * 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/PrintableFinSet.java b/core/src/net/sf/openrocket/gui/print/PrintableFinSet.java index cf07cb13..8e5389b2 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintableFinSet.java +++ b/core/src/net/sf/openrocket/gui/print/PrintableFinSet.java @@ -6,34 +6,25 @@ package net.sf.openrocket.gui.print; import net.sf.openrocket.rocketcomponent.FinSet; import net.sf.openrocket.util.Coordinate; -import javax.swing.*; -import java.awt.*; +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; -import java.awt.print.PageFormat; -import java.awt.print.Printable; -import java.awt.print.PrinterException; /** * 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 JPanel implements Printable { +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 X margin. - */ - private final int marginX = (int)(PrintUnit.POINTS_PER_INCH * 0.3f); - /** - * The Y margin. - */ - private final int marginY = (int)(PrintUnit.POINTS_PER_INCH * 0.3f); /** * The minimum X coordinate. */ @@ -58,9 +49,7 @@ public class PrintableFinSet extends JPanel implements Printable { * @param points an array of points. */ public PrintableFinSet (Coordinate[] points) { - super(false); init(points); - setBackground(Color.white); } /** @@ -77,8 +66,8 @@ public class PrintableFinSet extends JPanel implements Printable { int maxY = 0; for (Coordinate point : points) { - final long x = PrintUnit.METERS.toPoints(point.x); - final long y = PrintUnit.METERS.toPoints(point.y); + 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); @@ -90,60 +79,6 @@ public class PrintableFinSet extends JPanel implements Printable { setSize(maxX - minX, maxY - minY); } - /** - * Get the X-axis margin value. - * - * @return margin, in points - */ - protected double getMarginX () { - return marginX; - } - - /** - * Get the Y-axis margin value. - * - * @return margin, in points - */ - protected double getMarginY () { - return marginY; - } - - /** - * 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; - } - /** * 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. @@ -151,17 +86,17 @@ public class PrintableFinSet extends JPanel implements Printable { * @return an awt image of the fin set */ public Image createImage () { - int width = getWidth() + marginX; - int height = getHeight() + marginY; - // Create a buffered image in which to draw + 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 + // Create a graphics contents on the buffered image Graphics2D g2d = bufferedImage.createGraphics(); - // Draw graphics + // Draw graphics g2d.setBackground(Color.white); g2d.clearRect(0, 0, width, height); paintComponent(g2d); - // Graphics context no longer needed so dispose it + // Graphics context no longer needed so dispose it g2d.dispose(); return bufferedImage; } @@ -174,13 +109,15 @@ public class PrintableFinSet extends JPanel implements Printable { * @param g the Java2D graphics context */ @Override - public void paintComponent (Graphics g) { - super.paintComponent(g); + 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); @@ -195,5 +132,4 @@ public class PrintableFinSet extends JPanel implements Printable { 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 index 78afe6f0..2cfdfa68 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintableNoseCone.java +++ b/core/src/net/sf/openrocket/gui/print/PrintableNoseCone.java @@ -1,54 +1,54 @@ 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; -import net.sf.openrocket.gui.rocketfigure.TransitionShapes; -import net.sf.openrocket.rocketcomponent.NoseCone; -import net.sf.openrocket.rocketcomponent.Transition; -import net.sf.openrocket.util.Transformation; +public class PrintableNoseCone extends AbstractPrintable { -public class PrintableNoseCone extends AbstractPrintableTransition { - /** * 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(Transition noseCone) { + public PrintableNoseCone(NoseCone noseCone) { super(false, noseCone); } - + @Override - protected void init(Transition component) { - - target = (NoseCone) component; + 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) + marginX, - (int) PrintUnit.METERS.toPoints(target.getLength() + target.getAftShoulderLength()) + marginY); + setSize((int) PrintUnit.METERS.toPoints(2 * radius) + 4, + (int) PrintUnit.METERS.toPoints(target.getLength() + target.getAftShoulderLength()) + 4); } - + /** - * Draw a nose cone. + * 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(marginX + r.getHeight() / 2, marginY); + g2.translate(r.getHeight() / 2, 0); g2.rotate(Math.PI / 2); for (Shape shape : shapes) { g2.draw(shape); diff --git a/core/src/net/sf/openrocket/gui/print/PrintableTransition.java b/core/src/net/sf/openrocket/gui/print/PrintableTransition.java index a70703da..41a9958a 100644 --- a/core/src/net/sf/openrocket/gui/print/PrintableTransition.java +++ b/core/src/net/sf/openrocket/gui/print/PrintableTransition.java @@ -1,5 +1,7 @@ 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; @@ -8,8 +10,6 @@ import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; -import net.sf.openrocket.rocketcomponent.Transition; - /** * 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 @@ -18,8 +18,8 @@ import net.sf.openrocket.rocketcomponent.Transition; * 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 AbstractPrintableTransition { - +public class PrintableTransition extends AbstractPrintable { + /** * Dashed array value. */ @@ -31,38 +31,38 @@ public class PrintableTransition extends AbstractPrintableTransition { 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. * @@ -71,13 +71,20 @@ public class PrintableTransition extends AbstractPrintableTransition { 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; @@ -87,19 +94,19 @@ public class PrintableTransition extends AbstractPrintableTransition { 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 = marginX; + + int x = 0; int tabOffset = 35; - int y = tabOffset + marginY; - + 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; @@ -110,23 +117,23 @@ public class PrintableTransition extends AbstractPrintableTransition { 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); @@ -134,21 +141,21 @@ public class PrintableTransition extends AbstractPrintableTransition { 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; @@ -156,13 +163,13 @@ public class PrintableTransition extends AbstractPrintableTransition { 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. * @@ -179,7 +186,7 @@ public class PrintableTransition extends AbstractPrintableTransition { g2.rotate(Math.toRadians(theta)); g2.translate(-x, -y); } - + /** * Draw a transition. * @@ -199,9 +206,9 @@ public class PrintableTransition extends AbstractPrintableTransition { 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/components/Rule.java b/core/src/net/sf/openrocket/gui/print/components/Rule.java new file mode 100644 index 00000000..b26d6528 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/print/components/Rule.java @@ -0,0 +1,274 @@ +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 new file mode 100644 index 00000000..1df75699 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/print/visitor/CenteringRingStrategy.java @@ -0,0 +1,270 @@ +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/FinSetPrintStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/FinSetPrintStrategy.java index 80e15a21..38704908 100644 --- a/core/src/net/sf/openrocket/gui/print/visitor/FinSetPrintStrategy.java +++ b/core/src/net/sf/openrocket/gui/print/visitor/FinSetPrintStrategy.java @@ -6,16 +6,15 @@ 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.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.*; import java.awt.image.BufferedImage; import java.util.List; import java.util.Set; @@ -45,6 +44,11 @@ public class FinSetPrintStrategy { */ protected Set stages; + /** + * Strategy for fitting multiple components onto a page. + */ + protected PageFitPrintStrategy pageFitPrint; + /** * Constructor. * @@ -52,10 +56,11 @@ public class FinSetPrintStrategy { * @param theWriter The direct iText writer * @param theStages The stages to be printed by this strategy */ - public FinSetPrintStrategy(Document doc, PdfWriter theWriter, Set theStages) { + public FinSetPrintStrategy(Document doc, PdfWriter theWriter, Set theStages, PageFitPrintStrategy pageFit) { document = doc; writer = theWriter; stages = theStages; + pageFitPrint = pageFit; } /** @@ -98,14 +103,16 @@ public class FinSetPrintStrategy { java.awt.Dimension finSize = pfs.getSize(); final Dimension pageSize = getPageSize(); if (fitsOnOnePage(pageSize, finSize.getWidth(), finSize.getHeight())) { - printOnOnePage(pfs); + 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(); } - document.newPage(); } catch (DocumentException e) { log.error("Could not render fin.", e); @@ -153,19 +160,6 @@ public class FinSetPrintStrategy { return wRatio <= 1.0d && hRatio <= 1.0d; } - /** - * Print the fin set. - * - * @param thePfs the printable fin set - */ - private void printOnOnePage (final PrintableFinSet thePfs) { - Dimension d = getPageSize(); - PdfContentByte cb = writer.getDirectContent(); - Graphics2D g2 = cb.createGraphics(d.width, d.height); - thePfs.print(g2); - g2.dispose(); - } - /** * Get the dimensions of the paper page. * diff --git a/core/src/net/sf/openrocket/gui/print/visitor/PageFitPrintStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/PageFitPrintStrategy.java new file mode 100644 index 00000000..10ca7351 --- /dev/null +++ b/core/src/net/sf/openrocket/gui/print/visitor/PageFitPrintStrategy.java @@ -0,0 +1,175 @@ +/* + * 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 index cdeb9247..c155d0cd 100644 --- a/core/src/net/sf/openrocket/gui/print/visitor/PartsDetailVisitorStrategy.java +++ b/core/src/net/sf/openrocket/gui/print/visitor/PartsDetailVisitorStrategy.java @@ -3,27 +3,54 @@ */ package net.sf.openrocket.gui.print.visitor; -import com.itextpdf.text.*; -import com.itextpdf.text.pdf.PdfPCell; -import com.itextpdf.text.pdf.PdfPTable; -import com.itextpdf.text.pdf.PdfWriter; +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.rocketcomponent.*; +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 net.sf.openrocket.util.Coordinate; -import javax.swing.*; -import java.text.NumberFormat; -import java.util.Collection; -import java.util.List; -import java.util.Set; +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. @@ -142,7 +169,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof LaunchLug) { LaunchLug ll = (LaunchLug) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(ll.getMaterial())); grid.addCell(createOuterInnerDiaCell(ll)); @@ -152,7 +179,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof NoseCone) { NoseCone nc = (NoseCone) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + 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())); @@ -163,13 +190,13 @@ public class PartsDetailVisitorStrategy { else if (component instanceof Transition) { Transition tran = (Transition) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + 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(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + fore.setFont(PrintUtilities.NORMAL); Chunk aft = new Chunk(AFT_DIAMETER + toLength(tran.getAftRadius() * 2)); - aft.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + aft.setFont(PrintUtilities.NORMAL); final PdfPCell cell = ITextHelper.createCell(); cell.addElement(fore); cell.addElement(aft); @@ -183,7 +210,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof BodyTube) { BodyTube bt = (BodyTube) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(bt.getMaterial())); grid.addCell(createOuterInnerDiaCell(bt)); grid.addCell(createLengthCell(component.getLength())); @@ -203,7 +230,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof ExternalComponent) { ExternalComponent ext = (ExternalComponent) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(ext.getMaterial())); grid.addCell(ITextHelper.createCell()); @@ -216,7 +243,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof InnerTube) { InnerTube it = (InnerTube) component; grid.addCell(iconToImage(component)); - final PdfPCell pCell = createNameCell(component.getName(), true); + final PdfPCell pCell = createNameCell(component.getName(), true, component.getPresetComponent()); grid.addCell(pCell); grid.addCell(createMaterialCell(it.getMaterial())); grid.addCell(createOuterInnerDiaCell(it)); @@ -229,7 +256,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof RadiusRingComponent) { RadiusRingComponent rrc = (RadiusRingComponent) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(rrc.getMaterial())); if (component instanceof Bulkhead) { grid.addCell(createDiaCell(rrc.getOuterRadius()*2)); @@ -245,7 +272,7 @@ public class PartsDetailVisitorStrategy { else if (component instanceof RingComponent) { RingComponent ring = (RingComponent) component; grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(ring.getMaterial())); grid.addCell(createOuterInnerDiaCell(ring)); grid.addCell(createLengthCell(component.getLength())); @@ -260,7 +287,7 @@ public class PartsDetailVisitorStrategy { cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setPaddingBottom(12f); grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(ring.getMaterial())); grid.addCell(cell); grid.addCell(createLengthCell(ring.getCordLength())); @@ -272,14 +299,19 @@ public class PartsDetailVisitorStrategy { cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setPaddingBottom(12f); grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + 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)); + grid.addCell(createNameCell(SHROUD_LINES, true, component.getPresetComponent())); grid.addCell(createMaterialCell(chute.getLineMaterial())); grid.addCell(createLinesCell(chute.getLineCount())); grid.addCell(createLengthCell(chute.getLineLength())); @@ -291,7 +323,7 @@ public class PartsDetailVisitorStrategy { cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setPaddingBottom(12f); grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(ring.getMaterial())); grid.addCell(createStrip(ring)); grid.addCell(createLengthCell(component.getLength())); @@ -303,7 +335,7 @@ public class PartsDetailVisitorStrategy { cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setPaddingBottom(12f); grid.addCell(iconToImage(component)); - grid.addCell(createNameCell(component.getName(), true)); + grid.addCell(createNameCell(component.getName(), true, component.getPresetComponent())); grid.addCell(createMaterialCell(device.getMaterial())); grid.addCell(cell); grid.addCell(createLengthCell(component.getLength())); @@ -315,7 +347,7 @@ public class PartsDetailVisitorStrategy { cell.setPaddingBottom(12f); grid.addCell(iconToImage(component)); - final PdfPCell nameCell = createNameCell(component.getName(), true); + final PdfPCell nameCell = createNameCell(component.getName(), true, component.getPresetComponent()); nameCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); nameCell.setPaddingBottom(12f); grid.addCell(nameCell); @@ -355,17 +387,17 @@ public class PartsDetailVisitorStrategy { result.setVerticalAlignment(Element.ALIGN_TOP); result.setBorder(Rectangle.BOTTOM); Chunk c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(DIAMETER); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.SMALL_FONT_SIZE)); + c.setFont(PrintUtilities.SMALL); c.append(OUTER); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(" " + toLength(diameter)); p.add(c); result.addElement(p); @@ -385,12 +417,12 @@ public class PartsDetailVisitorStrategy { result.setVerticalAlignment(Element.ALIGN_TOP); result.setBorder(Rectangle.BOTTOM); Chunk c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(LENGTH); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(" " + toLength(component.getStripLength())); p.add(c); result.addElement(p); @@ -398,12 +430,12 @@ public class PartsDetailVisitorStrategy { Phrase pw = new Phrase(); pw.setLeading(14f); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(WIDTH); pw.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(" " + toLength(component.getStripWidth())); pw.add(c); result.addElement(pw); @@ -415,29 +447,56 @@ public class PartsDetailVisitorStrategy { * 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(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(DIAMETER); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.SMALL_FONT_SIZE)); + c.setFont(PrintUtilities.SMALL); c.append(OUTER); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); - c.append(" " + toLength(component.getOuterRadius() * 2)); + c.setFont(PrintUtilities.NORMAL); + c.append(" " + toLength(outerRadius * 2)); p.add(c); - createInnerDiaCell(component, result); + createInnerDiaCell(innerRadius, result, innerLabel); result.addElement(p); return result; } @@ -445,25 +504,26 @@ public class PartsDetailVisitorStrategy { /** * Add inner diameter data to a cell. * - * @param component a component that is a Coaxial + * @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 Coaxial component, PdfPCell cell) { + private void createInnerDiaCell (final double innerRadius, PdfPCell cell, final String innerLabel) { Phrase p = new Phrase(); p.setLeading(14f); Chunk c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(DIAMETER); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.SMALL_FONT_SIZE)); - c.append(INNER); + c.setFont(PrintUtilities.SMALL); + c.append(innerLabel); p.add(c); c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); - c.append(" " + toLength(component.getInnerRadius() * 2)); + c.setFont(PrintUtilities.NORMAL); + c.append(" " + toLength(innerRadius * 2)); p.add(c); cell.addElement(p); } @@ -478,8 +538,6 @@ public class PartsDetailVisitorStrategy { Image img = null; java.awt.Image awtImage = new PrintableFinSet(theFinSet).createImage(); - Collection x = theFinSet.getComponentBounds(); - try { img = Image.getInstance(writer, awtImage, 0.25f); } @@ -544,18 +602,49 @@ public class PartsDetailVisitorStrategy { * @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(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); + Chunk tab1 = + new Chunk(new VerticalPositionMark(), (level - 2) * 10, true); + if (withIndent) { - for (int x = 0; x < (level - 2) * 10; x++) { - c.append(" "); - } + para.add(new Chunk(tab1)); } c.append(v); - result.setColspan(2); - result.addElement(c); + 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; } @@ -571,11 +660,11 @@ public class PartsDetailVisitorStrategy { cell.setLeading(13f, 0); Chunk c = new Chunk(); - c.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.NORMAL_FONT_SIZE)); + c.setFont(PrintUtilities.NORMAL); c.append(toMaterialName(material)); cell.addElement(c); Chunk density = new Chunk(); - density.setFont(new Font(Font.FontFamily.HELVETICA, PrintUtilities.SMALL_FONT_SIZE)); + density.setFont(PrintUtilities.SMALL); density.append(toMaterialDensity(material)); cell.addElement(density); return cell; @@ -624,7 +713,7 @@ public class PartsDetailVisitorStrategy { */ protected String toLength (double length) { final Unit defaultUnit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - return NumberFormat.getNumberInstance().format(defaultUnit.toUnit(length)) + defaultUnit.toString(); + return defaultUnit.toStringUnit(length); } /** @@ -636,7 +725,7 @@ public class PartsDetailVisitorStrategy { */ protected String toMass (double mass) { final Unit defaultUnit = UnitGroup.UNITS_MASS.getDefaultUnit(); - return NumberFormat.getNumberInstance().format(defaultUnit.toUnit(mass)) + defaultUnit.toString(); + return defaultUnit.toStringUnit(mass); } /** diff --git a/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java b/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java index 1988ab8a..b6f1ee04 100644 --- a/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java +++ b/core/src/net/sf/openrocket/gui/print/visitor/TransitionStrategy.java @@ -3,10 +3,10 @@ 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.AbstractPrintableTransition; +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; @@ -15,7 +15,6 @@ import net.sf.openrocket.rocketcomponent.RocketComponent; import net.sf.openrocket.rocketcomponent.Transition; import net.sf.openrocket.startup.Application; -import java.awt.*; import java.awt.image.BufferedImage; import java.util.List; import java.util.Set; @@ -45,6 +44,11 @@ public class TransitionStrategy { */ protected Set stages; + /** + * Strategy for fitting multiple components onto a page. + */ + protected PageFitPrintStrategy pageFitPrint; + /** * Constructor. * @@ -52,10 +56,11 @@ public class TransitionStrategy { * @param theWriter The direct iText writer * @param theStagesToVisit The stages to be visited by this strategy */ - public TransitionStrategy(Document doc, PdfWriter theWriter, Set theStagesToVisit) { + public TransitionStrategy(Document doc, PdfWriter theWriter, Set theStagesToVisit, PageFitPrintStrategy pageFit) { document = doc; writer = theWriter; stages = theStagesToVisit; + pageFitPrint = pageFit; } /** @@ -63,10 +68,12 @@ public class TransitionStrategy { * * @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 void writeToDocument(final RocketComponent root, boolean noseCones) { + public boolean writeToDocument(final RocketComponent root, boolean noseCones) { List rc = root.getChildren(); - goDeep(rc, noseCones); + return goDeep(rc, noseCones); } @@ -75,47 +82,62 @@ public class TransitionStrategy { * * @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 void goDeep(final List theRc, boolean noseCones) { + protected boolean goDeep(final List theRc, boolean noseCones) { for (RocketComponent rocketComponent : theRc) { if (rocketComponent instanceof NoseCone) { if (noseCones) { - render((Transition) rocketComponent); + return render((Transition) rocketComponent); } - } else if (rocketComponent instanceof Transition && !noseCones) { - render((Transition) rocketComponent); - } else if (rocketComponent.getChildCount() > 0) { - goDeep(rocketComponent.getChildren(), noseCones); + } + 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 + * @param component the object to extract info about; a graphical image of the transition shape is drawn to the + * document + * + * @return true, always */ - private void render(final Transition component) { + private boolean render(final Transition component) { try { - AbstractPrintableTransition pfs; + AbstractPrintable pfs; if (component instanceof NoseCone) { - pfs = new PrintableNoseCone(component); - } else { + 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())) { - printOnOnePage(pfs); - } else { + 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) { + } + catch (DocumentException e) { log.error("Could not render the transition.", e); } + return true; } /** @@ -124,6 +146,7 @@ public class TransitionStrategy { * @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) { @@ -136,20 +159,6 @@ public class TransitionStrategy { return wRatio <= 1.0d && hRatio <= 1.0d; } - /** - * Print the transition. - * - * @param theTransition the printable transition - */ - private void printOnOnePage(final AbstractPrintableTransition theTransition) { - Dimension d = getPageSize(); - PdfContentByte cb = writer.getDirectContent(); - Graphics2D g2 = cb.createGraphics(d.width, d.height); - theTransition.print(g2); - g2.dispose(); - document.newPage(); - } - /** * Get the dimensions of the paper page. * diff --git a/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java b/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java index 0f08be21..cd5b9490 100644 --- a/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java +++ b/core/src/net/sf/openrocket/gui/scalefigure/FinPointFigure.java @@ -235,8 +235,8 @@ public class FinPointFigure extends AbstractScaleFigure { double y0 = p.y / EXTRA_SCALE; double delta = BOX_SIZE / scale; - System.out.println("Point: " + x0 + "," + y0); - System.out.println("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++) { @@ -249,7 +249,7 @@ public class FinPointFigure extends AbstractScaleFigure { 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); + //System.out.println("Distance of segment " + i + " is " + u); if (u < delta) return i; } diff --git a/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java b/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java index 854eb17a..bd63d8ba 100644 --- a/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java +++ b/core/src/net/sf/openrocket/gui/scalefigure/RocketFigure.java @@ -77,7 +77,7 @@ public class RocketFigure extends AbstractScaleFigure { private double minX = 0, maxX = 0, maxR = 0; // Figure width and height in SI-units and pixels private double figureWidth = 0, figureHeight = 0; - private int figureWidthPx = 0, figureHeightPx = 0; + protected int figureWidthPx = 0, figureHeightPx = 0; private AffineTransform g2transformation = null; diff --git a/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java b/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java index cf458724..2cef7080 100644 --- a/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java +++ b/core/src/net/sf/openrocket/gui/scalefigure/RocketPanel.java @@ -1,6 +1,7 @@ package net.sf.openrocket.gui.scalefigure; +import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; @@ -18,6 +19,7 @@ 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; @@ -43,6 +45,7 @@ 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; @@ -59,6 +62,8 @@ 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; @@ -74,45 +79,57 @@ 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. @@ -123,32 +140,37 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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; - } - }); + 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); @@ -156,31 +178,77 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change }; 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(); - figure.updateFigure(); + 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 @@ -188,27 +256,48 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change //// 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 scaleSelector = new ScaleSelector(scrollPane); + scaleSelector = new ScaleSelector(scrollPane); add(scaleSelector); - + // Stage selector StageSelector stageSelector = new StageSelector(configuration); add(stageSelector, ""); - + // Motor configuration selector @@ -217,55 +306,55 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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(scrollPane, "grow, spany 2, wmin 300lp, hmin 100lp, wrap"); - + 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(new BasicSlider(theta.getSliderModel(0, 2 * Math.PI), JSlider.VERTICAL, true), + + 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. * @@ -274,7 +363,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change public Caret getExtraCP() { return extraCP; } - + /** * Get the center of gravity figure element. * @@ -283,7 +372,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change public Caret getExtraCG() { return extraCG; } - + /** * Get the extra text figure element. * @@ -292,7 +381,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change public RocketInfo getExtraText() { return extraText; } - + public void setSelectionModel(TreeSelectionModel m) { if (selectionModel != null) { selectionModel.removeTreeSelectionListener(this); @@ -301,8 +390,8 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change selectionModel.addTreeSelectionListener(this); valueChanged((TreeSelectionEvent) null); // updates FigureParameters } - - + + /** * Return the angle of attack used in CP calculation. NaN signifies the default value @@ -312,7 +401,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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. @@ -324,14 +413,14 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change return; cpAOA = aoa; updateExtras(); - figure.updateFigure(); + updateFigures(); fireChangeEvent(); } - + public double getCPTheta() { return cpTheta; } - + public void setCPTheta(double theta) { if (MathUtil.equals(theta, cpTheta) || (Double.isNaN(theta) && Double.isNaN(cpTheta))) @@ -340,50 +429,50 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change if (!Double.isNaN(theta)) figure.setRotation(theta); updateExtras(); - figure.updateFigure(); + 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(); - figure.updateFigure(); + 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(); - figure.updateFigure(); + 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) { @@ -392,8 +481,8 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change } } } - - + + /** @@ -406,7 +495,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change * 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; @@ -414,13 +503,18 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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) { @@ -437,7 +531,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change } } } - + // Currently selected component not clicked if (path == null) { if (event.isShiftDown() && event.getClickCount() == 1 && clicked.length > 1) { @@ -446,18 +540,18 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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); } } - - + + /** @@ -465,15 +559,15 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change * 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); @@ -481,20 +575,20 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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); @@ -502,21 +596,24 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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(); @@ -530,7 +627,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change } length = maxX - minX; } - + for (RocketComponent c : configuration) { if (c instanceof SymmetricComponent) { double d1 = ((SymmetricComponent) c).getForeRadius() * 2; @@ -538,31 +635,31 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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); @@ -570,38 +667,38 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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(simulation); + + backgroundSimulationWorker = new BackgroundSimulationWorker(document, simulation); backgroundSimulationExecutor.execute(backgroundSimulationWorker); } - + /** * Cancels the current background simulation worker, if any. */ @@ -611,22 +708,26 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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 { - - public BackgroundSimulationWorker(Simulation sim) { + + 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); @@ -634,59 +735,71 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change } 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 }; + 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() { - figure.clearRelativeExtra(); 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. @@ -698,14 +811,16 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change 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 @@ -714,29 +829,31 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change * @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); + putValue(Action.SELECTED_KEY, figure.getType() == type && !is3d); } } - + } diff --git a/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java b/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java index 1e966a05..fba7aaa7 100644 --- a/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java +++ b/core/src/net/sf/openrocket/gui/scalefigure/ScaleSelector.java @@ -1,10 +1,12 @@ 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; @@ -15,18 +17,18 @@ 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 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[i]+0.05 && scale < ZOOM_LEVELS[i+1]+0.05) + 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]) { + if (scale > ZOOM_LEVELS[ZOOM_LEVELS.length / 2]) { // scale is large, drop to next lowest full 100% - scale = Math.ceil(scale-1.05); + scale = Math.ceil(scale - 1.05); return Math.max(scale, ZOOM_LEVELS[i]); } // scale is small - return scale/1.5; + return scale / 1.5; } private double getNextScale(double scale) { int i; - for (i=0; i ZOOM_LEVELS[i]-0.05 && scale < ZOOM_LEVELS[i+1]-0.05) - return ZOOM_LEVELS[i+1]; + 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]) { + if (scale > ZOOM_LEVELS[ZOOM_LEVELS.length / 2]) { // scale is large, give next full 100% - scale = Math.floor(scale+1.05); + scale = Math.floor(scale + 1.05); return scale; } - return scale*1.5; + 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/CustomFinImporter.java b/core/src/net/sf/openrocket/gui/util/CustomFinImporter.java index 1d29b216..ae2f7bf4 100644 --- a/core/src/net/sf/openrocket/gui/util/CustomFinImporter.java +++ b/core/src/net/sf/openrocket/gui/util/CustomFinImporter.java @@ -34,12 +34,20 @@ public class CustomFinImporter { facing = FacingDirections.UP; if (!validateImage(pic)) { - throw new LocalizedIOException("CustomFinImport.error.badimage"); + throw new LocalizedIOException("CustomFinImport.badFinImage"); } - + + // Load the fin points.add(Coordinate.NUL); loadFin(pic, points); - optimizePoints(points); + + // Optimize the loaded fin + int count; + do { + count = points.size(); + optimizePoints(points); + } while (count != points.size()); + return points; } @@ -52,22 +60,22 @@ public class CustomFinImporter { 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 - if ((pixel == 0xFFFFFF) || (pixel == 0)) // black or white only - { - if ((x == 0) || (x == width - 1) || (y == 0)) { - // Left, right and top must have no black (fin) - if (pixel == 0) - return false; - } else if (y == height - 1) { - if (pixel == 0) { - bottomEdgeFound = true; - if (startX == -1) - startX = x; - } + // 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; } - } else { - // Found something other than a black or white pixel - return false; } } } @@ -75,11 +83,11 @@ public class CustomFinImporter { } private void loadFin(BufferedImage pic, ArrayList points) { - boolean calledTurnedAround = false; int height = pic.getHeight(); + Boolean offBottom = false; currentX = startX; - currentY = pic.getHeight() - 1; + currentY = height - 1; do { if (checkLeftIsFin(pic, currentX, currentY)) @@ -90,19 +98,17 @@ public class CustomFinImporter { rotateRight(); else { turnAround(); - calledTurnedAround = true; } moveForward(pic); + if (currentY < height - 1) + offBottom = true; if (pixelIsFin(pic, currentX, currentY)) { - if (!calledTurnedAround) { - double x = (currentX - startX) * 0.001; - double y = (height - currentY - 1) * 0.001; - points.add(new Coordinate(x, y)); - } else - calledTurnedAround = false; + double x = (currentX - startX) * 0.001; + double y = (height - currentY - 1) * 0.001; + points.add(new Coordinate(x, y)); } - } while (currentY < height - 1 && currentY >= 0); + } while ((!offBottom) || (currentY < height - 1 && currentY >= 0)); } private boolean pixelIsFin(BufferedImage pic, int x, int y) { @@ -210,18 +216,20 @@ public class CustomFinImporter { 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.001) { + if (pointDistanceFromLine(startPoint, endPoint, testPoint) > 0.0008) { break; } } @@ -239,10 +247,11 @@ public class CustomFinImporter { startIx = nextIx; start = points.listIterator(startIx); startPoint = start.next(); + removedSection = true; break; } } - if (endPoint == startPoint) { + if ((!removedSection) && (endPoint == startPoint)) { startIx = start.nextIndex(); if (start.hasNext()) startPoint = start.next(); diff --git a/core/src/net/sf/openrocket/gui/util/FileHelper.java b/core/src/net/sf/openrocket/gui/util/FileHelper.java index 860379ed..7fcdc2a4 100644 --- a/core/src/net/sf/openrocket/gui/util/FileHelper.java +++ b/core/src/net/sf/openrocket/gui/util/FileHelper.java @@ -1,69 +1,73 @@ package net.sf.openrocket.gui.util; -import java.awt.Component; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import javax.imageio.ImageIO; -import javax.swing.JOptionPane; -import javax.swing.filechooser.FileFilter; - 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(); + extensions[i] = extensions[i].toLowerCase(Locale.ENGLISH); } Arrays.sort(extensions); - + StringBuilder sb = new StringBuilder(); sb.append(trans.get("filetypes.images")); sb.append(" ("); @@ -74,31 +78,31 @@ public final class FileHelper { } } 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 @@ -109,8 +113,8 @@ public final class FileHelper { * @return the resulting file */ public static File forceExtension(File original, String extension) { - - if (!original.getName().toLowerCase().endsWith(extension.toLowerCase())) { + + 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(".")) { @@ -121,15 +125,15 @@ public final class FileHelper { } 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. @@ -148,23 +152,23 @@ public final class FileHelper { } 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 index 4ee74ba4..4ac68dce 100644 --- a/core/src/net/sf/openrocket/gui/util/GUIUtil.java +++ b/core/src/net/sf/openrocket/gui/util/GUIUtil.java @@ -348,6 +348,26 @@ public class GUIUtil { } + 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. * @@ -362,10 +382,10 @@ public class GUIUtil { */ Font font = border.getTitleFont(); if (font == null) { - log.error("Border font is null, reverting to JLabel font"); + log.warn("JRE bug workaround : Border font is null, reverting to JLabel font"); font = new JLabel().getFont(); if (font == null) { - log.error("JLabel font is null, not modifying font"); + log.warn("JRE bug workaround : JLabel font is null, not modifying font"); return; } } diff --git a/core/src/net/sf/openrocket/gui/util/Icons.java b/core/src/net/sf/openrocket/gui/util/Icons.java index 8f304b63..0fa2b67c 100644 --- a/core/src/net/sf/openrocket/gui/util/Icons.java +++ b/core/src/net/sf/openrocket/gui/util/Icons.java @@ -73,6 +73,13 @@ public class Icons { 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"); diff --git a/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java b/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java index 39ded917..e895b929 100644 --- a/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java +++ b/core/src/net/sf/openrocket/gui/util/SimpleFileFilter.java @@ -1,6 +1,7 @@ package net.sf.openrocket.gui.util; import java.io.File; +import java.util.Locale; import javax.swing.filechooser.FileFilter; @@ -12,7 +13,7 @@ import javax.swing.filechooser.FileFilter; * @author Sampo Niskanen */ public class SimpleFileFilter extends FileFilter implements java.io.FileFilter { - + private final String description; private final boolean acceptDir; private final String[] extensions; @@ -25,11 +26,11 @@ public class SimpleFileFilter extends FileFilter implements java.io.FileFilter { * @param description the description of this file filter. * @param extensions an array of extensions that match this filter. */ - public SimpleFileFilter(String description, String ... extensions) { + public SimpleFileFilter(String description, String... extensions) { this(description, true, extensions); } - + /** * Create filter that accepts files with the provided extensions. * @@ -37,12 +38,12 @@ public class SimpleFileFilter extends FileFilter implements java.io.FileFilter { * @param acceptDir whether to accept directories * @param extensions an array of extensions that match this filter. */ - public SimpleFileFilter(String description, boolean acceptDir, String ... extensions) { + 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 SUPPORTED_LOCALES; static { List list = new ArrayList(); - for (String lang : new String[] { "en", "de", "es", "fr", "it", "ru" }) { + 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. */ @@ -62,9 +64,9 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { */ private static final String NODENAME = (DEBUG ? "OpenRocket-debug" : "OpenRocket"); - private final Preferences PREFNODE; + private final Preferences PREFNODE; + - public SwingPreferences() { Preferences root = Preferences.userRoot(); if (DEBUG && CLEARPREFS) { @@ -79,13 +81,13 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { PREFNODE = root.node(NODENAME); } - - + + ////////////////////// - - + + /** * Store the current OpenRocket version into the preferences to allow for preferences migration. */ @@ -106,9 +108,9 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } @Override - public String getString( String directory, String key, String defaultValue ) { + public String getString(String directory, String key, String defaultValue) { Preferences p = PREFNODE.node(directory); - return p.get(key,defaultValue); + return p.get(key, defaultValue); } /** @@ -128,12 +130,12 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } @Override - public void putString(String directory, String key, String value ) { + public void putString(String directory, String key, String value) { Preferences p = PREFNODE.node(directory); - if ( value == null ) { + if (value == null) { p.remove(key); } else { - p.put(key,value); + p.put(key, value); } storeVersion(); } @@ -163,29 +165,29 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } @Override - public int getInt( String key, int defaultValue ) { + public int getInt(String key, int defaultValue) { return PREFNODE.getInt(key, defaultValue); } @Override - public void putInt( String key , int value ) { - PREFNODE.putInt(key, value ); + 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 ); + return PREFNODE.getDouble(key, defaultValue); } - + @Override public void putDouble(String key, double value) { - PREFNODE.putDouble(key,value); + PREFNODE.putDouble(key, value); storeVersion(); } - - - + + + /** * Return a preferences object for the specified node name. * @@ -199,7 +201,7 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { ////////////////// - + public static List getSupportedLocales() { return SUPPORTED_LOCALES; } @@ -328,8 +330,8 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } - - + + public Dimension getWindowSize(Class c) { int x, y; String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null); @@ -370,9 +372,9 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { * you can pass (java.awt.Color) null to the second argument to * disambiguate */ - public Color getColor( String key, Color defaultValue ) { + 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 ) { + if (c == null) { return defaultValue; } return ColorConversion.toAwtColor(c); @@ -381,9 +383,9 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { /** * */ - public void putColor( String key, Color value ) { + public void putColor(String key, Color value) { net.sf.openrocket.util.Color c = ColorConversion.fromAwtColor(value); - super.putColor(key, c); + super.putColor(key, c); } //// Printing @@ -407,7 +409,7 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } - + ///////// Export variables public boolean isExportSelected(FlightDataType type) { @@ -421,7 +423,7 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } - + ///////// Default unit storage public void loadDefaultUnits() { @@ -457,10 +459,10 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { } - + //// Material storage - + /** * Add a user-defined material to the preferences. The preferences are * first checked for an existing material matching the provided one using @@ -468,10 +470,11 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { * * @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; @@ -495,6 +498,7 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { * * @param m the material to remove. */ + @Override public void removeUserMaterial(Material m) { Preferences prefs = PREFNODE.node("userMaterials"); @@ -527,6 +531,7 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { * * @return a set of all user-defined materials. */ + @Override public Set getUserMaterials() { Preferences prefs = PREFNODE.node("userMaterials"); @@ -553,7 +558,27 @@ public class SwingPreferences extends net.sf.openrocket.startup.Preferences { 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 index b4212dc9..6281b6e8 100644 --- a/core/src/net/sf/openrocket/l10n/ClassBasedTranslator.java +++ b/core/src/net/sf/openrocket/l10n/ClassBasedTranslator.java @@ -15,7 +15,7 @@ import net.sf.openrocket.util.BugException; */ public class ClassBasedTranslator implements Translator { - + private final Translator translator; private final String className; @@ -41,7 +41,7 @@ public class ClassBasedTranslator implements Translator { } - + @Override public String get(String key) { String classKey = className + "." + key; @@ -63,7 +63,20 @@ public class ClassBasedTranslator implements Translator { } - + + @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(); @@ -82,11 +95,10 @@ public class ClassBasedTranslator implements Translator { } - - + + // 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 index 5a2bf592..ccf72e58 100644 --- a/core/src/net/sf/openrocket/l10n/DebugTranslator.java +++ b/core/src/net/sf/openrocket/l10n/DebugTranslator.java @@ -22,7 +22,7 @@ public class DebugTranslator implements Translator { } - + @Override public String get(String key) { if (translator != null) { @@ -31,4 +31,22 @@ public class DebugTranslator implements Translator { 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 index dd916b6c..1287822c 100644 --- a/core/src/net/sf/openrocket/l10n/ExceptionSuppressingTranslator.java +++ b/core/src/net/sf/openrocket/l10n/ExceptionSuppressingTranslator.java @@ -29,7 +29,7 @@ public class ExceptionSuppressingTranslator implements Translator { } - + @Override public String get(String key) { try { @@ -42,7 +42,18 @@ public class ExceptionSuppressingTranslator implements Translator { } - + @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; @@ -50,4 +61,6 @@ public class ExceptionSuppressingTranslator implements Translator { } } + + } diff --git a/core/src/net/sf/openrocket/l10n/L10N.java b/core/src/net/sf/openrocket/l10n/L10N.java index 878b3c41..3303292d 100644 --- a/core/src/net/sf/openrocket/l10n/L10N.java +++ b/core/src/net/sf/openrocket/l10n/L10N.java @@ -1,8 +1,13 @@ 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. * @@ -10,6 +15,12 @@ import java.util.regex.Pattern; */ 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 } @@ -54,4 +65,339 @@ public final class L10N { 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/ResourceBundleTranslator.java b/core/src/net/sf/openrocket/l10n/ResourceBundleTranslator.java index 241ecefc..d210e01e 100644 --- a/core/src/net/sf/openrocket/l10n/ResourceBundleTranslator.java +++ b/core/src/net/sf/openrocket/l10n/ResourceBundleTranslator.java @@ -1,6 +1,7 @@ package net.sf.openrocket.l10n; import java.util.Locale; +import java.util.MissingResourceException; import java.util.ResourceBundle; /** @@ -11,6 +12,7 @@ import java.util.ResourceBundle; public class ResourceBundleTranslator implements Translator { private final ResourceBundle bundle; + private final ResourceBundle english; /** * Create a ResourceBundleTranslator using the default Locale. @@ -29,6 +31,7 @@ public class ResourceBundleTranslator implements Translator { */ public ResourceBundleTranslator(String baseName, Locale locale) { this.bundle = ResourceBundle.getBundle(baseName, locale); + this.english = ResourceBundle.getBundle(baseName, Locale.ROOT); } @@ -40,4 +43,27 @@ public class ResourceBundleTranslator implements Translator { 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 index 9eed2cdf..5211ed73 100644 --- a/core/src/net/sf/openrocket/l10n/Translator.java +++ b/core/src/net/sf/openrocket/l10n/Translator.java @@ -22,4 +22,33 @@ public interface Translator { */ 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/LogLevel.java b/core/src/net/sf/openrocket/logging/LogLevel.java index b52d1453..a5783856 100644 --- a/core/src/net/sf/openrocket/logging/LogLevel.java +++ b/core/src/net/sf/openrocket/logging/LogLevel.java @@ -1,5 +1,7 @@ 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 @@ -16,13 +18,13 @@ public enum LogLevel { * 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 @@ -30,13 +32,13 @@ public enum LogLevel { * 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 @@ -44,7 +46,7 @@ public enum LogLevel { * 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 @@ -103,7 +105,7 @@ public enum LogLevel { if (value == null) { return defaultLevel; } - value = value.toUpperCase().trim(); + value = value.toUpperCase(Locale.ENGLISH).trim(); // Find the correct level LogLevel level = defaultLevel; diff --git a/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java b/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java index 4b5d8276..3fd82fdf 100644 --- a/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java +++ b/core/src/net/sf/openrocket/masscalc/BasicMassCalculator.java @@ -2,8 +2,10 @@ 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; @@ -38,6 +40,7 @@ public class BasicMassCalculator extends AbstractMassCalculator { * 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); @@ -80,6 +83,7 @@ public class BasicMassCalculator extends AbstractMassCalculator { /** * Return the CG of the rocket with the provided motor configuration. */ + @Override public Coordinate getCG(Configuration configuration, MotorInstanceConfiguration motors) { checkCache(configuration); calculateStageCache(configuration); @@ -103,7 +107,6 @@ public class BasicMassCalculator extends AbstractMassCalculator { return totalCG; } - /** * Return the longitudinal inertia of the rocket with the specified motor instance * configuration. @@ -111,6 +114,7 @@ public class BasicMassCalculator extends AbstractMassCalculator { * @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); @@ -154,6 +158,7 @@ public class BasicMassCalculator extends AbstractMassCalculator { * @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); @@ -190,8 +195,26 @@ public class BasicMassCalculator extends AbstractMassCalculator { 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); diff --git a/core/src/net/sf/openrocket/masscalc/MassCalculator.java b/core/src/net/sf/openrocket/masscalc/MassCalculator.java index 003650e1..5e657f7a 100644 --- a/core/src/net/sf/openrocket/masscalc/MassCalculator.java +++ b/core/src/net/sf/openrocket/masscalc/MassCalculator.java @@ -70,6 +70,14 @@ public interface MassCalculator extends Monitorable { */ 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. diff --git a/core/src/net/sf/openrocket/material/Material.java b/core/src/net/sf/openrocket/material/Material.java index 00be68b1..055fc336 100644 --- a/core/src/net/sf/openrocket/material/Material.java +++ b/core/src/net/sf/openrocket/material/Material.java @@ -1,5 +1,7 @@ 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; @@ -16,16 +18,18 @@ import net.sf.openrocket.util.MathUtil; public abstract class Material implements Comparable { + private static final Translator trans = Application.getTranslator(); + public enum Type { - LINE("Line", UnitGroup.UNITS_DENSITY_LINE), - SURFACE("Surface", UnitGroup.UNITS_DENSITY_SURFACE), - BULK("Bulk", UnitGroup.UNITS_DENSITY_BULK); + 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 name, UnitGroup units) { - this.name = name; + private Type(String nameKey, UnitGroup units) { + this.name = trans.get(nameKey); this.units = units; } @@ -43,7 +47,7 @@ public abstract class Material implements Comparable { ///// Definitions of different material types ///// public static class Line extends Material { - public Line(String name, double density, boolean userDefined) { + Line(String name, double density, boolean userDefined) { super(name, density, userDefined); } @@ -55,7 +59,7 @@ public abstract class Material implements Comparable { public static class Surface extends Material { - public Surface(String name, double density, boolean userDefined) { + Surface(String name, double density, boolean userDefined) { super(name, density, userDefined); } @@ -71,7 +75,7 @@ public abstract class Material implements Comparable { } public static class Bulk extends Material { - public Bulk(String name, double density, boolean userDefined) { + Bulk(String name, double density, boolean userDefined) { super(name, density, userDefined); } @@ -82,20 +86,26 @@ public abstract class Material implements Comparable { } - + private final String name; private final double density; private final boolean userDefined; - public Material(String name, double density, 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.density = density; this.userDefined = userDefined; + this.density = density; } - - public double getDensity() { return density; } @@ -159,10 +169,15 @@ public abstract class Material implements Comparable { /** - * Return a new material of the specified type. + * 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) { + public static Material newMaterial(Type type, String name, double density, boolean userDefined) { switch (type) { case LINE: return new Material.Line(name, density, userDefined); @@ -178,7 +193,6 @@ public abstract class Material implements Comparable { } } - public String toStorableString() { return getType().name() + "|" + name.replace('|', ' ') + '|' + density; } diff --git a/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java b/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java index 6b7eb2b7..eef78b00 100644 --- a/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java +++ b/core/src/net/sf/openrocket/models/atmosphere/ExtendedISAModel.java @@ -115,8 +115,7 @@ public class ExtendedISAModel extends InterpolatingAtmosphericModel { 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); + //System.out.println("alt=" + alt + ": std:" + cond1 + " mod:" + cond2 + " diff:" + diff); } } diff --git a/core/src/net/sf/openrocket/motor/Manufacturer.java b/core/src/net/sf/openrocket/motor/Manufacturer.java index 831181bb..5d562ed7 100644 --- a/core/src/net/sf/openrocket/motor/Manufacturer.java +++ b/core/src/net/sf/openrocket/motor/Manufacturer.java @@ -4,7 +4,9 @@ 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. @@ -12,8 +14,22 @@ import java.util.Set; * @author Sampo Niskanen */ public class Manufacturer { - - private static Set manufacturers = new HashSet(); + + 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... @@ -98,24 +114,10 @@ public class Manufacturer { "WECO", "WECO FEUERWERKS", "SF", "SACHSEN", "SACHSEN FEUERWERK", "SACHSEN FEUERWERKS")); - - // Check that no duplicates have appeared - for (Manufacturer m1 : manufacturers) { - for (Manufacturer m2 : manufacturers) { - if (m1 == m2) - continue; - for (String name : m1.getAllNames()) { - if (m2.matches(name)) { - throw new IllegalStateException("Manufacturer name clash between " + - "manufacturers " + m1 + " and " + m2 + " name " + name); - } - } - } - } } - - + + private final String displayName; private final String simpleName; private final Set allNames; @@ -181,6 +183,9 @@ public class Manufacturer { return allNames; } + Set getSearchNames() { + return searchNames; + } /** * Return the motor type that this manufacturer produces if it produces only one motor type. @@ -228,22 +233,29 @@ public class Manufacturer { * @param name the manufacturer name to search for. * @return the Manufacturer object corresponding the name. */ - public static synchronized Manufacturer getManufacturer(String name) { - for (Manufacturer m : manufacturers) { - if (m.matches(name)) - return m; + 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); } - - Manufacturer m = new Manufacturer(name.trim(), name.trim(), Motor.Type.UNKNOWN); - manufacturers.add(m); return m; } - - - - private String generateSearchString(String str) { - return str.toLowerCase().replaceAll("[^a-zA-Z0-9]+", " ").trim(); + 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/MotorInstance.java b/core/src/net/sf/openrocket/motor/MotorInstance.java index 6b48e3a4..ab474a8e 100644 --- a/core/src/net/sf/openrocket/motor/MotorInstance.java +++ b/core/src/net/sf/openrocket/motor/MotorInstance.java @@ -56,5 +56,8 @@ public interface MotorInstance extends Cloneable, Monitorable { * 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/ThrustCurveMotor.java b/core/src/net/sf/openrocket/motor/ThrustCurveMotor.java index e1ba1d77..e795c823 100644 --- a/core/src/net/sf/openrocket/motor/ThrustCurveMotor.java +++ b/core/src/net/sf/openrocket/motor/ThrustCurveMotor.java @@ -7,6 +7,7 @@ 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; @@ -43,6 +44,31 @@ public class ThrustCurveMotor implements Motor, Comparable { 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. @@ -398,6 +424,7 @@ public class ThrustCurveMotor implements Motor, Comparable { private final double unitRotationalInertia; private final double unitLongitudinalInertia; + private final Motor parentMotor; private int modID = 0; @@ -411,6 +438,12 @@ public class ThrustCurveMotor implements Motor, Comparable { stepCG = cg[0]; unitRotationalInertia = Inertia.filledCylinderRotational(getDiameter() / 2); unitLongitudinalInertia = Inertia.filledCylinderLongitudinal(getDiameter() / 2, getLength()); + parentMotor = ThrustCurveMotor.this; + } + + @Override + public Motor getParentMotor(){ + return parentMotor; } @Override diff --git a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java b/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java index 07724c8f..b5e2eaee 100644 --- a/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java +++ b/core/src/net/sf/openrocket/optimization/rocketoptimization/modifiers/GenericModifier.java @@ -1,5 +1,7 @@ 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; @@ -53,7 +55,7 @@ public abstract class GenericModifier extends AbstractSimulationModifier { } try { - methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1); + 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) { @@ -64,7 +66,7 @@ public abstract class GenericModifier extends AbstractSimulationModifier { } - + @Override public double getCurrentSIValue(Simulation simulation) throws OptimizationException { T modifiable = getModifiedObject(simulation); @@ -97,7 +99,7 @@ public abstract class GenericModifier extends AbstractSimulationModifier { 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/services/DefaultSimulationModifierService.java b/core/src/net/sf/openrocket/optimization/services/DefaultSimulationModifierService.java index 565330aa..cf77e3c5 100644 --- a/core/src/net/sf/openrocket/optimization/services/DefaultSimulationModifierService.java +++ b/core/src/net/sf/openrocket/optimization/services/DefaultSimulationModifierService.java @@ -4,6 +4,7 @@ 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; @@ -41,7 +42,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi 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); @@ -51,7 +52,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi * 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"); @@ -81,7 +82,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi 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"); @@ -100,7 +101,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi } private static void addModifier(String modifierNameKey, UnitGroup unitGroup, double multiplier, - Class componentClass, String methodName, String autoMethod) { + Class componentClass, String methodName, String autoMethod) { String modifierDescriptionKey = modifierNameKey + ".desc"; @@ -116,8 +117,8 @@ public class DefaultSimulationModifierService implements SimulationModifierServi } - - + + @Override public Collection getModifiers(OpenRocketDocument document) { List modifiers = new ArrayList(); @@ -151,7 +152,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi } } - + // Add override modifiers if mass/CG is overridden if (c.isMassOverridden()) { SimulationModifier mod = new GenericComponentModifier( @@ -173,7 +174,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi modifiers.add(mod); } - + // Conditional motor mount parameters if (c instanceof MotorMount) { MotorMount mount = (MotorMount) c; @@ -199,7 +200,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi } } - + // Inner component positioning if (c instanceof InternalComponent) { RocketComponent parent = c.getParent(); @@ -213,7 +214,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi modifiers.add(mod); } - + // Custom min/max for fin set position if (c instanceof FinSet) { RocketComponent parent = c.getParent(); @@ -227,7 +228,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi modifiers.add(mod); } - + // Custom min/max for launch lug position if (c instanceof LaunchLug) { RocketComponent parent = c.getParent(); @@ -241,7 +242,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi modifiers.add(mod); } - + // Recovery device deployment altitude and delay if (c instanceof RecoveryDevice) { RecoveryDevice device = (RecoveryDevice) c; @@ -266,15 +267,15 @@ public class DefaultSimulationModifierService implements SimulationModifierServi } } - + // 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() + ".shapeparameter"), - trans.get("optimization.modifier." + c.getClass().getSimpleName().toLowerCase() + ".shapeparameter.desc"), + 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()); @@ -303,7 +304,7 @@ public class DefaultSimulationModifierService implements SimulationModifierServi * 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; diff --git a/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java b/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java index 152ccaf7..ad2d6401 100644 --- a/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java +++ b/core/src/net/sf/openrocket/optimization/services/OptimizationServiceHelper.java @@ -8,8 +8,6 @@ import java.util.ServiceLoader; import net.sf.openrocket.document.OpenRocketDocument; import net.sf.openrocket.optimization.rocketoptimization.OptimizableParameter; import net.sf.openrocket.optimization.rocketoptimization.SimulationModifier; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.util.TestRockets; public final class OptimizationServiceHelper { @@ -37,7 +35,7 @@ public final class OptimizationServiceHelper { } - + /** * Return the optimization parameters for an OpenRocketDocument. This queries the * getParameters() method from all available services and returns a collection of all @@ -58,10 +56,4 @@ public final class OptimizationServiceHelper { } - public static void main(String[] args) { - Rocket r = TestRockets.makeBigBlue(); - OpenRocketDocument document = new OpenRocketDocument(r); - System.out.println("Simulation modifiers: " + getSimulationModifiers(document)); - System.out.println("Optimization parameters: " + getOptimizableParameters(document)); - } } diff --git a/core/src/net/sf/openrocket/plugin/Configurable.java b/core/src/net/sf/openrocket/plugin/Configurable.java new file mode 100644 index 00000000..b8ebf6e2 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/Configurable.java @@ -0,0 +1,29 @@ +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 new file mode 100644 index 00000000..86ba323e --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/SwingConfigurator.java @@ -0,0 +1,37 @@ +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 new file mode 100644 index 00000000..7d14f5fd --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/AirStartSimulationExtension.java @@ -0,0 +1,42 @@ +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 new file mode 100644 index 00000000..aea94be6 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/ExampleMain.java @@ -0,0 +1,21 @@ +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 new file mode 100644 index 00000000..4579f9e3 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/ExamplePlugin.java @@ -0,0 +1,17 @@ +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 new file mode 100644 index 00000000..ddf157dc --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/ExamplePluginInterface.java @@ -0,0 +1,9 @@ +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 new file mode 100644 index 00000000..8a6317b3 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/ExampleService.java @@ -0,0 +1,24 @@ +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 new file mode 100644 index 00000000..aa015180 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/ExampleSingletonPlugin.java @@ -0,0 +1,13 @@ +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 new file mode 100644 index 00000000..ea178c09 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/OpenRocketSimulationListener.java @@ -0,0 +1,88 @@ +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 new file mode 100644 index 00000000..e4a4fc3c --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/example/stuff.txt @@ -0,0 +1,135 @@ + + + +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 new file mode 100644 index 00000000..eca8a2a0 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/framework/AbstractService.java @@ -0,0 +1,45 @@ +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 new file mode 100644 index 00000000..f75cf36c --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/framework/JSPFPluginFactory.java @@ -0,0 +1,50 @@ +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 new file mode 100644 index 00000000..25b6cbfd --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/framework/PluginFactory.java @@ -0,0 +1,11 @@ +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 new file mode 100644 index 00000000..ee56b8e4 --- /dev/null +++ b/core/src/net/sf/openrocket/plugin/framework/Service.java @@ -0,0 +1,30 @@ +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 index 87343e93..6e7bd7aa 100644 --- a/core/src/net/sf/openrocket/preset/ComponentPreset.java +++ b/core/src/net/sf/openrocket/preset/ComponentPreset.java @@ -1,73 +1,377 @@ 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.RocketComponent; +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 abstract class ComponentPreset { +public class ComponentPreset implements Comparable { - private final Manufacturer manufacturer; - private final String partNo; - private final String partDescription; - private final RocketComponent prototype; + private final TypedPropertyMap properties = new TypedPropertyMap(); + private String digest = ""; - public ComponentPreset(Manufacturer manufacturer, String partNo, String partDescription, - RocketComponent prototype) { - this.manufacturer = manufacturer; - this.partNo = partNo; - this.partDescription = partDescription; - this.prototype = prototype.copy(); + 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 }), - if (prototype.getParent() != null) { - throw new IllegalArgumentException("Prototype component cannot have a parent"); + 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; } - if (prototype.getChildCount() > 0) { - throw new IllegalArgumentException("Prototype component cannot have children"); + + 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() { + } /** - * Return the component class that this preset defines. + * Convenience method to retrieve the Type of this ComponentPreset. + * + * @return */ - public Class getComponentClass() { - return prototype.getClass(); + public Type getType() { + return properties.get(TYPE); } /** - * Return the manufacturer of this preset component. + * Convenience method to retrieve the Manufacturer of this ComponentPreset. + * @return */ public Manufacturer getManufacturer() { - return manufacturer; + return properties.get(MANUFACTURER); } /** - * Return the part number. This is the part identifier (e.g. "BT-50"). + * Convenience method to retrieve the PartNo of this ComponentPreset. + * @return */ public String getPartNo() { - return partNo; + return properties.get(PARTNO); + } + + public String getDigest() { + return digest; + } + + public boolean has(Object key) { + return properties.containsKey(key); } /** - * Return the part description. This is a longer description of the component. + * Package scope so the ComponentPresetFactory can call it. + * @param other */ - public String getPartDescription() { - return partDescription; + void putAll(TypedPropertyMap other) { + if (other == null) { + return; + } + properties.putAll(other); } /** - * Return a prototype component. This component may be modified freely. + * Package scope so the ComponentPresetFactory can call it. + * @param key + * @param value */ - public RocketComponent getPrototype() { - return prototype.copy(); + 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 new file mode 100644 index 00000000..7d2677b3 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/ComponentPresetFactory.java @@ -0,0 +1,280 @@ +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 new file mode 100644 index 00000000..c28fb093 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/InvalidComponentPresetException.java @@ -0,0 +1,56 @@ +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 new file mode 100644 index 00000000..c3e44731 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/TypedKey.java @@ -0,0 +1,69 @@ +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 new file mode 100644 index 00000000..cb43f12c --- /dev/null +++ b/core/src/net/sf/openrocket/preset/TypedPropertyMap.java @@ -0,0 +1,86 @@ +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 new file mode 100644 index 00000000..9c95197f --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/BaseColumnParser.java @@ -0,0 +1,42 @@ +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 new file mode 100644 index 00000000..d1782097 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/BaseComponentLoader.java @@ -0,0 +1,50 @@ +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 new file mode 100644 index 00000000..4cdb3986 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/BaseUnitColumnParser.java @@ -0,0 +1,53 @@ +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 new file mode 100644 index 00000000..dcb7ccc5 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/BodyTubeLoader.java @@ -0,0 +1,30 @@ +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 new file mode 100644 index 00000000..b9d01066 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/BulkHeadLoader.java @@ -0,0 +1,36 @@ +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 new file mode 100644 index 00000000..ad465694 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/CenteringRingLoader.java @@ -0,0 +1,24 @@ +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 new file mode 100644 index 00000000..e4f54134 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/DoubleColumnParser.java @@ -0,0 +1,21 @@ +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 new file mode 100644 index 00000000..bd9a5c18 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/DoubleUnitColumnParser.java @@ -0,0 +1,57 @@ +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 new file mode 100644 index 00000000..0fa6a6ec --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/EngineBlockLoader.java @@ -0,0 +1,24 @@ +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 new file mode 100644 index 00000000..d871be1c --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/IntegerColumnParser.java @@ -0,0 +1,21 @@ +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 new file mode 100644 index 00000000..8242e8f7 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/LaunchLugLoader.java @@ -0,0 +1,30 @@ +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 new file mode 100644 index 00000000..42a79722 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/LineMaterialColumnParser.java @@ -0,0 +1,35 @@ +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 new file mode 100644 index 00000000..7d019c01 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/ManufacturerColumnParser.java @@ -0,0 +1,20 @@ +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 new file mode 100644 index 00000000..ce382ec9 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/MassColumnParser.java @@ -0,0 +1,30 @@ +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 new file mode 100644 index 00000000..2d559bb7 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/MaterialColumnParser.java @@ -0,0 +1,39 @@ +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 new file mode 100644 index 00000000..7ab176b8 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/MaterialHolder.java @@ -0,0 +1,134 @@ +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 new file mode 100644 index 00000000..b7ef55b4 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/MaterialLoader.java @@ -0,0 +1,62 @@ +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 new file mode 100644 index 00000000..8c8f4077 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/NoseConeLoader.java @@ -0,0 +1,44 @@ +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 new file mode 100644 index 00000000..4f53e40e --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/ParachuteLoader.java @@ -0,0 +1,51 @@ +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 new file mode 100644 index 00000000..cfaf091d --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileColumnParser.java @@ -0,0 +1,22 @@ +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 new file mode 100644 index 00000000..c0ca293c --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileLoader.java @@ -0,0 +1,276 @@ +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 new file mode 100644 index 00000000..d84fa1d8 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileTranslator.java @@ -0,0 +1,150 @@ +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 new file mode 100644 index 00000000..13ac8620 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/RocksimComponentFileType.java @@ -0,0 +1,77 @@ +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 new file mode 100644 index 00000000..05ea4e88 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/ShapeColumnParser.java @@ -0,0 +1,64 @@ +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 new file mode 100644 index 00000000..403ea0f6 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/StreamerLoader.java @@ -0,0 +1,59 @@ +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 new file mode 100644 index 00000000..c4d96a70 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/StringColumnParser.java @@ -0,0 +1,20 @@ +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 new file mode 100644 index 00000000..703d128c --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/SurfaceMaterialColumnParser.java @@ -0,0 +1,34 @@ +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 new file mode 100644 index 00000000..a67695b5 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/TransitionLoader.java @@ -0,0 +1,30 @@ +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 new file mode 100644 index 00000000..3a5706bc --- /dev/null +++ b/core/src/net/sf/openrocket/preset/loader/TubeCouplerLoader.java @@ -0,0 +1,24 @@ +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 new file mode 100644 index 00000000..ca8c18fd --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/BaseComponentDTO.java @@ -0,0 +1,282 @@ +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 new file mode 100644 index 00000000..536944f2 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/BodyTubeDTO.java @@ -0,0 +1,100 @@ + +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 new file mode 100644 index 00000000..1db3dd7d --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/BulkHeadDTO.java @@ -0,0 +1,78 @@ + +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 new file mode 100644 index 00000000..9866a15a --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/CenteringRingDTO.java @@ -0,0 +1,41 @@ + +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 new file mode 100644 index 00000000..6c3f61fa --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/EngineBlockDTO.java @@ -0,0 +1,40 @@ + +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 new file mode 100644 index 00000000..e723861b --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/LaunchLugDTO.java @@ -0,0 +1,100 @@ + +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 new file mode 100644 index 00000000..abcebda7 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/MaterialDTO.java @@ -0,0 +1,114 @@ +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 new file mode 100644 index 00000000..93a83b35 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/MaterialTypeDTO.java @@ -0,0 +1,35 @@ + +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 new file mode 100644 index 00000000..0a071d6c --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/NoseConeDTO.java @@ -0,0 +1,154 @@ +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 new file mode 100644 index 00000000..69da4e85 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentDTO.java @@ -0,0 +1,93 @@ +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 new file mode 100644 index 00000000..a27712c7 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentLoader.java @@ -0,0 +1,44 @@ +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 new file mode 100644 index 00000000..934d4be5 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/OpenRocketComponentSaver.java @@ -0,0 +1,206 @@ +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 new file mode 100644 index 00000000..f7056c05 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/ParachuteDTO.java @@ -0,0 +1,140 @@ + +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 new file mode 100644 index 00000000..d85fbcb0 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/ShapeDTO.java @@ -0,0 +1,41 @@ + +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 new file mode 100644 index 00000000..7ed0dd84 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/StreamerDTO.java @@ -0,0 +1,102 @@ + +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 new file mode 100644 index 00000000..1aaaac65 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/TransitionDTO.java @@ -0,0 +1,197 @@ + +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 new file mode 100644 index 00000000..3cc09658 --- /dev/null +++ b/core/src/net/sf/openrocket/preset/xml/TubeCouplerDTO.java @@ -0,0 +1,40 @@ + +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 index a102e87f..6f4d7dbe 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/BodyComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/BodyComponent.java @@ -1,5 +1,7 @@ package net.sf.openrocket.rocketcomponent; +import net.sf.openrocket.preset.ComponentPreset; + /** @@ -49,10 +51,7 @@ public abstract class BodyComponent extends ExternalComponent { @Override - protected void loadFromPreset(RocketComponent preset) { - BodyComponent c = (BodyComponent) preset; - this.setLength(c.getLength()); - + protected void loadFromPreset(ComponentPreset preset) { super.loadFromPreset(preset); } diff --git a/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java b/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java index 64c1b4a9..65317a3c 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java +++ b/core/src/net/sf/openrocket/rocketcomponent/BodyTube.java @@ -6,6 +6,7 @@ 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; @@ -62,6 +63,11 @@ public class BodyTube extends SymmetricComponent implements MotorMount, Coaxial /************ Get/set component parameter methods ************/ + @Override + public ComponentPreset.Type getPresetType() { + return ComponentPreset.Type.BODY_TUBE; + } + /** * Return the outer radius of the body tube. * @@ -134,14 +140,22 @@ public class BodyTube extends SymmetricComponent implements MotorMount, Coaxial @Override - protected void loadFromPreset(RocketComponent preset) { - BodyTube c = (BodyTube) preset; - this.setOuterRadius(c.getOuterRadius()); - + 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(); diff --git a/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java b/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java index 24a1552f..36822c4d 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java +++ b/core/src/net/sf/openrocket/rocketcomponent/Bulkhead.java @@ -1,6 +1,8 @@ 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; @@ -12,6 +14,11 @@ public class Bulkhead extends RadiusRingComponent { setLength(0.002); } + @Override + public Type getPresetType() { + return ComponentPreset.Type.BULK_HEAD; + } + @Override public double getInnerRadius() { return 0; @@ -25,6 +32,7 @@ public class Bulkhead extends RadiusRingComponent { @Override public void setOuterRadiusAutomatic(boolean auto) { super.setOuterRadiusAutomatic(auto); + clearPreset(); } @Override diff --git a/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java b/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java index 21b73e2a..0dc9e1ee 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java +++ b/core/src/net/sf/openrocket/rocketcomponent/CenteringRing.java @@ -1,5 +1,9 @@ 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; @@ -10,6 +14,8 @@ public class CenteringRing extends RadiusRingComponent { setInnerRadiusAutomatic(true); setLength(0.002); } + + private static final Translator trans = Application.getTranslator(); @Override @@ -54,7 +60,7 @@ public class CenteringRing extends RadiusRingComponent { @Override public String getComponentName() { - return "Centering ring"; + return trans.get ("CenteringRing.CenteringRing"); } @Override @@ -67,4 +73,9 @@ public class CenteringRing extends RadiusRingComponent { return false; } + @Override + public Type getPresetType() { + return ComponentPreset.Type.CENTERING_RING; + } + } diff --git a/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java b/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java index 2c2c590b..660bbba1 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java +++ b/core/src/net/sf/openrocket/rocketcomponent/EngineBlock.java @@ -1,8 +1,15 @@ 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); @@ -17,7 +24,7 @@ public class EngineBlock extends ThicknessRingComponent { @Override public String getComponentName() { - return "Engine block"; + return trans.get ("EngineBlock.EngineBlock"); } @Override @@ -30,4 +37,9 @@ public class EngineBlock extends ThicknessRingComponent { 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 index 8d958da6..4377a8c3 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/ExternalComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/ExternalComponent.java @@ -4,7 +4,7 @@ import java.util.List; import net.sf.openrocket.l10n.Translator; import net.sf.openrocket.material.Material; -import net.sf.openrocket.material.Material.Type; +import net.sf.openrocket.preset.ComponentPreset; import net.sf.openrocket.startup.Application; import net.sf.openrocket.unit.UnitGroup; @@ -17,7 +17,7 @@ import net.sf.openrocket.unit.UnitGroup; */ public abstract class ExternalComponent extends RocketComponent { - + public enum Finish { //// Rough ROUGH("ExternalComponent.Rough", 500e-6), @@ -29,35 +29,35 @@ public abstract class ExternalComponent extends RocketComponent { 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. @@ -66,13 +66,13 @@ public abstract class ExternalComponent extends RocketComponent { 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. */ @@ -80,7 +80,7 @@ public abstract class ExternalComponent extends RocketComponent { public double getComponentMass() { return material.getDensity() * getComponentVolume(); } - + /** * ExternalComponent has aerodynamic effect, so return true. */ @@ -88,7 +88,7 @@ public abstract class ExternalComponent extends RocketComponent { public boolean isAerodynamic() { return true; } - + /** * ExternalComponent has effect on the mass, so return true. */ @@ -96,63 +96,66 @@ public abstract class ExternalComponent extends RocketComponent { 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); - clearPreset(); } - + 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(RocketComponent preset) { + protected void loadFromPreset(ComponentPreset preset) { super.loadFromPreset(preset); - + // Surface finish is left unchanged - - ExternalComponent c = (ExternalComponent) preset; - - Material mat = c.getMaterial(); - if (c.isMassOverridden()) { - double mass = c.getOverrideMass(); - double volume = getComponentVolume(); - double density; - if (volume > 0.00001) { - density = mass / volume; - } else { - density = 1000; + + 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); } - mat = Material.newMaterial(Type.BULK, mat.getName(), density, true); + */ } - - setMaterial(mat); } - - + + @Override protected List copyFrom(RocketComponent c) { ExternalComponent src = (ExternalComponent) c; @@ -160,5 +163,5 @@ public abstract class ExternalComponent extends RocketComponent { 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 index 5e40810b..4b8d5805 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/FinSet.java +++ b/core/src/net/sf/openrocket/rocketcomponent/FinSet.java @@ -7,6 +7,7 @@ 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; @@ -675,7 +676,7 @@ public abstract class FinSet extends ExternalComponent { double y = -getTabHeight(); int n = points.length; - points = Arrays.copyOf(points, points.length + 4); + 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); diff --git a/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java b/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java index b0bb0ad7..ac52a0f8 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java +++ b/core/src/net/sf/openrocket/rocketcomponent/FreeformFinSet.java @@ -258,7 +258,7 @@ public class FreeformFinSet extends FinSet { if (index == 0) { - System.out.println("Set point zero to x:" + x); + //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)); diff --git a/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java b/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java index 0b8c92d2..937edbf5 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java +++ b/core/src/net/sf/openrocket/rocketcomponent/InnerTube.java @@ -6,6 +6,7 @@ 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; @@ -77,7 +78,27 @@ public class InnerTube extends ThicknessRingComponent 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 ////////////// diff --git a/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java b/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java index 5614e077..43709436 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java +++ b/core/src/net/sf/openrocket/rocketcomponent/LaunchLug.java @@ -4,6 +4,8 @@ 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; @@ -43,6 +45,7 @@ public class LaunchLug extends ExternalComponent implements Coaxial { return; this.radius = radius; this.thickness = Math.min(this.thickness, this.radius); + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); } @@ -65,6 +68,7 @@ public class LaunchLug extends ExternalComponent implements Coaxial { if (MathUtil.equals(this.thickness, thickness)) return; this.thickness = MathUtil.clamp(thickness, 0, radius); + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); } @@ -109,6 +113,29 @@ public class LaunchLug extends ExternalComponent implements Coaxial { + @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); diff --git a/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java b/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java index 49c139b0..81e5a63d 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/MassComponent.java @@ -40,6 +40,27 @@ public class MassComponent extends MassObject { } + 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 diff --git a/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java b/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java index a4de3a9c..6ef65ed2 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java +++ b/core/src/net/sf/openrocket/rocketcomponent/NoseCone.java @@ -1,6 +1,8 @@ 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; /** @@ -111,6 +113,18 @@ public class NoseCone extends Transition { /********** 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. */ diff --git a/core/src/net/sf/openrocket/rocketcomponent/Parachute.java b/core/src/net/sf/openrocket/rocketcomponent/Parachute.java index 640810bb..aabb6117 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/Parachute.java +++ b/core/src/net/sf/openrocket/rocketcomponent/Parachute.java @@ -2,6 +2,8 @@ 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; @@ -32,6 +34,7 @@ public class Parachute extends RecoveryDevice { if (MathUtil.equals(this.diameter, d)) return; this.diameter = d; + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); } @@ -62,6 +65,7 @@ public class Parachute extends RecoveryDevice { if (this.lineCount == n) return; this.lineCount = n; + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } @@ -94,6 +98,7 @@ public class Parachute extends RecoveryDevice { if (MathUtil.equals(getArea(), area)) return; diameter = MathUtil.safeSqrt(area / Math.PI) * 2; + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); } @@ -118,5 +123,29 @@ public class Parachute extends RecoveryDevice { 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/RadiusRingComponent.java b/core/src/net/sf/openrocket/rocketcomponent/RadiusRingComponent.java index 46a35143..6d0ccb65 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/RadiusRingComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/RadiusRingComponent.java @@ -1,5 +1,6 @@ package net.sf.openrocket.rocketcomponent; +import net.sf.openrocket.preset.ComponentPreset; import net.sf.openrocket.util.Coordinate; import net.sf.openrocket.util.MathUtil; @@ -16,6 +17,22 @@ public abstract class RadiusRingComponent extends RingComponent implements Coaxi 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) { @@ -44,6 +61,7 @@ public abstract class RadiusRingComponent extends RingComponent implements Coaxi innerRadiusAutomatic = false; } + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } @@ -65,6 +83,7 @@ public abstract class RadiusRingComponent extends RingComponent implements Coaxi outerRadiusAutomatic = false; } + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } diff --git a/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java b/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java index 4156bfbe..3c5a88f1 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java +++ b/core/src/net/sf/openrocket/rocketcomponent/RecoveryDevice.java @@ -2,6 +2,7 @@ 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; @@ -22,16 +23,14 @@ import net.sf.openrocket.util.Pair; */ public abstract class RecoveryDevice extends MassObject { private static final Translator trans = Application.getTranslator(); - + public static enum DeployEvent { - //// Launch (plus NN seconds) LAUNCH(trans.get("RecoveryDevice.DeployEvent.LAUNCH")) { @Override public boolean isActivationEvent(FlightEvent e, RocketComponent source) { return e.getType() == FlightEvent.Type.LAUNCH; } }, - //// First ejection charge of this stage EJECTION(trans.get("RecoveryDevice.DeployEvent.EJECTION")) { @Override public boolean isActivationEvent(FlightEvent e, RocketComponent source) { @@ -41,35 +40,42 @@ public abstract class RecoveryDevice extends MassObject { return charge.getStageNumber() == source.getStageNumber(); } }, - //// Apogee APOGEE(trans.get("RecoveryDevice.DeployEvent.APOGEE")) { @Override public boolean isActivationEvent(FlightEvent e, RocketComponent source) { return e.getType() == FlightEvent.Type.APOGEE; } }, - //// Specific altitude during descent 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(); + + double alt = ((RecoveryDevice) source).getDeployAltitude(); + Pair altitude = (Pair) e.getData(); return (altitude.getU() >= alt) && (altitude.getV() <= alt); } }, - //// Never + 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; @@ -83,7 +89,7 @@ public abstract class RecoveryDevice extends MassObject { public String toString() { return description; } - + } @@ -96,7 +102,7 @@ public abstract class RecoveryDevice extends MassObject { private Material.Surface material; - + public RecoveryDevice() { this(Application.getPreferences().getDefaultComponentMaterial(RecoveryDevice.class, Material.Type.SURFACE)); @@ -106,19 +112,19 @@ public abstract class RecoveryDevice extends MassObject { 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() { @@ -130,7 +136,7 @@ public abstract class RecoveryDevice extends MassObject { cd = getComponentCD(mach); return cd; } - + public void setCD(double cd) { if (MathUtil.equals(this.cd, cd) && !isCDAutomatic()) return; @@ -138,7 +144,7 @@ public abstract class RecoveryDevice extends MassObject { this.cdAutomatic = false; fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE); } - + public boolean isCDAutomatic() { return cdAutomatic; @@ -159,11 +165,12 @@ public abstract class RecoveryDevice extends MassObject { public final void setMaterial(Material mat) { if (!(mat instanceof Material.Surface)) { - throw new IllegalArgumentException("Attempted to set non-surface material "+mat); + throw new IllegalArgumentException("Attempted to set non-surface material " + mat); } if (mat.equals(material)) return; - this.material = (Material.Surface)mat; + this.material = (Material.Surface) mat; + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } @@ -173,7 +180,7 @@ public abstract class RecoveryDevice extends MassObject { public DeployEvent getDeployEvent() { return deployEvent; } - + public void setDeployEvent(DeployEvent deployEvent) { if (this.deployEvent == deployEvent) return; @@ -181,11 +188,11 @@ public abstract class RecoveryDevice extends MassObject { fireComponentChangeEvent(ComponentChangeEvent.EVENT_CHANGE); } - + public double getDeployAltitude() { return deployAltitude; } - + public void setDeployAltitude(double deployAltitude) { if (MathUtil.equals(this.deployAltitude, deployAltitude)) return; @@ -210,10 +217,21 @@ public abstract class RecoveryDevice extends MassObject { } - + @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/Rocket.java b/core/src/net/sf/openrocket/rocketcomponent/Rocket.java index 226f9527..d493ca49 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/Rocket.java +++ b/core/src/net/sf/openrocket/rocketcomponent/Rocket.java @@ -42,7 +42,7 @@ public class Rocket extends RocketComponent { * 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. @@ -121,9 +121,6 @@ public class Rocket extends RocketComponent { fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); } - - - /** * Return the number of stages in this rocket. * diff --git a/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java b/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java index b1a57dbf..9000a540 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/RocketComponent.java @@ -1,8 +1,6 @@ package net.sf.openrocket.rocketcomponent; -import java.util.ArrayDeque; import java.util.Collection; -import java.util.Deque; import java.util.EventListener; import java.util.Iterator; import java.util.List; @@ -21,13 +19,14 @@ 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: @@ -48,38 +47,38 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab /** 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. @@ -87,56 +86,56 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * 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. @@ -147,26 +146,26 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -176,8 +175,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * @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 @@ -187,8 +186,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * @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 @@ -197,7 +196,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * @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 @@ -208,8 +207,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * @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 @@ -223,9 +222,9 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -233,24 +232,24 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * @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. @@ -267,8 +266,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -281,10 +280,10 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab // 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. @@ -299,8 +298,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab else return name; } - - + + /** * Create a string describing the basic component structure from this component downwards. * @return a string containing the rocket structure @@ -315,7 +314,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.unlock("toDebugString"); } } - + private void toDebugString(StringBuilder sb) { sb.append(this.getClass().getSimpleName()).append('@').append(System.identityHashCode(this)); sb.append("[\"").append(this.getName()).append('"'); @@ -325,8 +324,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } 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 @@ -336,16 +335,16 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab */ 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 @@ -372,14 +371,14 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } 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(); @@ -387,23 +386,23 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -412,7 +411,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return color; } - + /** * Set the color of the object to use in 2D figures. */ @@ -420,18 +419,18 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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; @@ -439,10 +438,10 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab this.lineStyle = style; fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); } - - - - + + + + /** * Get the current override mass. The mass is not necessarily in use * at the moment. @@ -453,7 +452,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return overrideMass; } - + /** * Set the current override mass. The mass is not set to use by this * method. @@ -468,7 +467,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -479,7 +478,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return massOverriden; } - + /** * Set whether the mass is currently overridden. * @@ -493,11 +492,11 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab massOverriden = o; fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } - - - - - + + + + + /** * Return the current override CG. The CG is not necessarily overridden. * @@ -507,7 +506,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return getComponentCG().setX(overrideCGX); } - + /** * Return the x-coordinate of the current override CG. * @@ -517,7 +516,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return overrideCGX; } - + /** * Set the current override CG to (x,0,0). * @@ -533,7 +532,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab else fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); } - + /** * Return whether the CG is currently overridden. * @@ -543,7 +542,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return cgOverriden; } - + /** * Set whether the CG is currently overridden. * @@ -557,9 +556,9 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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, @@ -574,8 +573,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return overrideSubcomponents; } - - + + /** * Set whether the mass and/or CG override overrides all subcomponent values * as well. See {@link #getOverrideSubcomponents()} for details. @@ -590,7 +589,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -605,10 +604,10 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return isCGOverridden() || isMassOverridden(); } - - - - + + + + /** * Get the user-defined name of the component. */ @@ -616,7 +615,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -632,8 +631,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -644,7 +643,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return comment; } - + /** * Set the comment of the component. * @@ -660,9 +659,9 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab this.comment = comment; fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); } - - - + + + /** * Return the preset component that this component is based upon. * @@ -671,7 +670,17 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -682,17 +691,20 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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) { @@ -700,25 +712,25 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } else { rocket = null; } - + try { if (rocket != null) { rocket.freeze(); } - - loadFromPreset(preset.getPrototype()); - + + 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. @@ -731,11 +743,13 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab * * @param preset the preset to load from */ - protected void loadFromPreset(RocketComponent preset) { - // No-op + 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. @@ -746,9 +760,9 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab presetComponent = null; fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE); } - - - + + + /** * Returns the unique ID of the component. * @@ -757,7 +771,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab public final String getID() { return id; } - + /** * Generate a new ID for this component. */ @@ -765,10 +779,10 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -781,7 +795,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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, @@ -791,8 +805,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -808,38 +822,38 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -853,7 +867,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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; @@ -873,7 +887,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } return result; } - + /** * Get the position value of the component. The exact meaning of the value is * dependent on the current relative positioning. @@ -884,8 +898,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.verify(); return position; } - - + + /** * Set the position value of the component. The exact meaning of the value * depends on the current relative positioning. @@ -903,11 +917,11 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab checkState(); this.position = value; } - - - + + + /////////// Coordinate changes /////////// - + /** * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null). */ @@ -915,8 +929,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -941,33 +955,33 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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); @@ -983,28 +997,28 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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)) { @@ -1013,14 +1027,14 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1042,11 +1056,11 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab mutex.unlock("getTotalLength"); } } - - - + + + /////////// Total mass and CG calculation //////////// - + /** * Return the (possibly overridden) mass of component. * @@ -1058,7 +1072,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab return overrideMass; return getComponentMass(); } - + /** * Return the (possibly overridden) center of gravity and mass. * @@ -1071,14 +1085,14 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -1090,7 +1104,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -1102,12 +1116,12 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -1122,8 +1136,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1138,32 +1152,32 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab */ 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. * @@ -1174,13 +1188,13 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1190,24 +1204,24 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab */ 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. * @@ -1219,15 +1233,15 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1242,30 +1256,30 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1278,7 +1292,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab this.checkComponentStructure(); return children.indexOf(child); } - + /** * Get the parent component of this component. Returns <code>null</code> if the component * has no parent. @@ -1289,7 +1303,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab checkState(); return parent; } - + /** * Get the root component of the component tree. * @@ -1302,7 +1316,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1318,8 +1332,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1337,7 +1351,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } 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. @@ -1349,7 +1363,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab if (parent == null) { throw new IllegalArgumentException("getStageNumber() called for root component"); } - + RocketComponent stage = this; while (!(stage instanceof Stage)) { stage = stage.parent; @@ -1360,8 +1374,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } 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, @@ -1380,8 +1394,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } return null; } - - + + // TODO: Move these methods elsewhere (used only in SymmetricComponent) public final RocketComponent getPreviousComponent() { checkState(); @@ -1393,7 +1407,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab StringBuffer sb = new StringBuffer(); sb.append("Inconsistent internal state: "); sb.append("this=").append(this).append('[') - .append(System.identityHashCode(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); @@ -1412,34 +1426,34 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -1451,7 +1465,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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). @@ -1465,8 +1479,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab getRoot().removeComponentChangeListener(l); } } - - + + /** * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to * <code>addComponentChangeListener()</code> except that it uses a @@ -1481,7 +1495,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab checkState(); getRocket().addChangeListener(l); } - + /** * Removes a ChangeListener from the rocket tree. This is identical to * removeComponentChangeListener() except it uses a ChangeListener. @@ -1496,8 +1510,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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). @@ -1518,8 +1532,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } getRoot().fireComponentChangeEvent(e); } - - + + /** * Fires a ComponentChangeEvent of the given type. The source of the event is set to * this component. @@ -1530,8 +1544,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1544,8 +1558,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1568,7 +1582,7 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } } } - + // Check whether the list contains exactly the searched-for component (with == operator) private boolean containsExact(List<RocketComponent> haystack, RocketComponent needle) { for (RocketComponent c : haystack) { @@ -1578,10 +1592,10 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } return false; } - - + + /////////// Iterators ////////// - + /** * Returns an iterator that iterates over all children and sub-children. * <p> @@ -1603,8 +1617,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab public final Iterator<RocketComponent> deepIterator(boolean returnSelf) { return iterator(returnSelf); } - - + + /** * Returns an iterator that iterates over all children and sub-children, including itself. * <p> @@ -1619,9 +1633,9 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab public final Iterator<RocketComponent> deepIterator() { return iterator(); } - - - + + + /** * Returns an iterator that iterates over all children and sub-children. * <p> @@ -1640,8 +1654,8 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab checkState(); return new RocketComponentIterator(this, returnSelf); } - - + + /** * Returns an iterator that iterates over this component, its children and sub-children. * <p> @@ -1653,11 +1667,30 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. @@ -1673,21 +1706,21 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -1699,37 +1732,41 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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 @@ -1750,34 +1787,34 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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; @@ -1792,22 +1829,22 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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. * @@ -1815,17 +1852,17 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab */ private static class RocketComponentIterator implements Iterator<RocketComponent> { // Stack holds iterators which still have some components left. - private final Deque<Iterator<RocketComponent>> iteratorStack = new ArrayDeque<Iterator<RocketComponent>>(); - + 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; @@ -1834,15 +1871,15 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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(); @@ -1850,38 +1887,38 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab 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) { @@ -1889,12 +1926,12 @@ public abstract class RocketComponent implements ChangeSource, Cloneable, Iterab } } } - + @Override public void remove() { throw new UnsupportedOperationException("remove() not supported by " + "RocketComponent iterator"); } } - + } diff --git a/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java b/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java index ec244ee0..f6f342c6 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java +++ b/core/src/net/sf/openrocket/rocketcomponent/Sleeve.java @@ -1,5 +1,7 @@ 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; @@ -12,6 +14,7 @@ import net.sf.openrocket.util.MathUtil; * @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; @@ -91,7 +94,7 @@ public class Sleeve extends RingComponent { @Override public String getComponentName() { - return "Sleeve"; + return trans.get ("Sleeve.Sleeve"); } @Override diff --git a/core/src/net/sf/openrocket/rocketcomponent/Streamer.java b/core/src/net/sf/openrocket/rocketcomponent/Streamer.java index 8d73c457..058392e9 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/Streamer.java +++ b/core/src/net/sf/openrocket/rocketcomponent/Streamer.java @@ -1,5 +1,9 @@ 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 { @@ -8,6 +12,7 @@ public class Streamer extends RecoveryDevice { public static final double MAX_COMPUTED_CD = 0.4; + private static final Translator trans = Application.getTranslator(); private double stripLength; private double stripWidth; @@ -27,6 +32,7 @@ public class Streamer extends RecoveryDevice { if (MathUtil.equals(this.stripLength, stripLength)) return; this.stripLength = stripLength; + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); } @@ -39,6 +45,7 @@ public class Streamer extends RecoveryDevice { return; this.stripWidth = stripWidth; this.length = stripWidth; + clearPreset(); fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE); } @@ -83,6 +90,27 @@ public class Streamer extends RecoveryDevice { + @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(); @@ -95,7 +123,7 @@ public class Streamer extends RecoveryDevice { @Override public String getComponentName() { - return "Streamer"; + return trans.get ("Streamer.Streamer"); } @Override diff --git a/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java b/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java index d37af27e..b7143c68 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/StructuralComponent.java @@ -1,6 +1,7 @@ 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 { @@ -12,6 +13,30 @@ public abstract class StructuralComponent extends InternalComponent { 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; @@ -24,6 +49,7 @@ public abstract class StructuralComponent extends InternalComponent { 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 index 5dc18354..7b455fa8 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/SymmetricComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/SymmetricComponent.java @@ -6,6 +6,7 @@ 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; @@ -146,10 +147,14 @@ public abstract class SymmetricComponent extends BodyComponent implements Radial @Override - protected void loadFromPreset(RocketComponent preset) { - SymmetricComponent c = (SymmetricComponent) preset; - this.setThickness(c.getThickness()); - this.setFilled(c.isFilled()); + 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); } @@ -293,9 +298,8 @@ public abstract class SymmetricComponent extends BodyComponent implements Radial // Integrate for volume, CG, wetted area and planform area - final double l = length / DIVISIONS; - final double pil = Math.PI * l; // PI * l - final double pil3 = Math.PI * l / 3; // PI * l/3 + final double step = length / DIVISIONS; + final double pi3 = Math.PI / 3.0; r1 = getRadius(0); x = 0; wetArea = 0; @@ -312,25 +316,44 @@ public abstract class SymmetricComponent extends BodyComponent implements Radial * 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; - r2 = getRadius(x + l); + // 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 = pil3 * (r1 * r1 + r1 * r2 + r2 * r2); - if (filled || r1 < thickness || r2 < thickness) { - // Filled piece + dFullV = pi3 * l * (r1 * r1 + r1 * r2 + r2 * r2); + + if ( filled ) { dV = dFullV; } else { - // Hollow piece - final double height = thickness * hyp / l; - dV = MathUtil.max(pil * height * (r1 + r2 - height), 0); + // 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; @@ -343,7 +366,7 @@ public abstract class SymmetricComponent extends BodyComponent implements Radial final double p = l * (r1 + r2); planArea += p; planCenter += (x + l / 2) * p; - + // Update for next iteration r1 = r2; x += l; @@ -358,10 +381,10 @@ public abstract class SymmetricComponent extends BodyComponent implements Radial volume = 0; cg = new Coordinate(length / 2, 0, 0, 0); } else { - // getComponentMass is safe now - // Use super.getComponentMass() to ensure only the transition shape mass - // is used, not the shoulders - cg = new Coordinate(cgx / volume, 0, 0, super.getComponentMass()); + // 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 ); } } @@ -444,7 +467,7 @@ public abstract class SymmetricComponent extends BodyComponent implements Radial final double l = length / DIVISIONS; r1 = getRadius(0); - System.out.println(r1); + //System.out.println(r1); x = 0; longitudinalInertia = 0; diff --git a/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java b/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java index 4bded707..c2d0a9bd 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java +++ b/core/src/net/sf/openrocket/rocketcomponent/ThicknessRingComponent.java @@ -1,5 +1,6 @@ package net.sf.openrocket.rocketcomponent; +import net.sf.openrocket.preset.ComponentPreset; import net.sf.openrocket.util.Coordinate; import net.sf.openrocket.util.MathUtil; @@ -16,7 +17,24 @@ 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) { @@ -45,6 +63,8 @@ public abstract class ThicknessRingComponent extends RingComponent { if (thickness > outerRadius) thickness = outerRadius; + clearPreset(); + fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } @@ -64,6 +84,8 @@ public abstract class ThicknessRingComponent extends RingComponent { this.thickness = thickness; + clearPreset(); + fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE); } diff --git a/core/src/net/sf/openrocket/rocketcomponent/Transition.java b/core/src/net/sf/openrocket/rocketcomponent/Transition.java index f3a6f9b6..6b12f156 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/Transition.java +++ b/core/src/net/sf/openrocket/rocketcomponent/Transition.java @@ -1,28 +1,31 @@ package net.sf.openrocket.rocketcomponent; -import static java.lang.Math.sin; -import static net.sf.openrocket.util.MathUtil.*; - -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; +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; @@ -32,30 +35,39 @@ public class Transition extends SymmetricComponent { 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() { @@ -72,35 +84,39 @@ public class Transition extends SymmetricComponent { } 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()) { @@ -116,62 +132,66 @@ public class Transition extends SymmetricComponent { } 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"); @@ -183,142 +203,144 @@ public class Transition extends SymmetricComponent { 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 //////////// - + /** @@ -328,20 +350,20 @@ public class Transition extends SymmetricComponent { 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) @@ -352,7 +374,7 @@ public class Transition extends SymmetricComponent { return r1 + type.getRadius(x, r2 - r1, length, shapeParameter); } } - + /** * Numerically solve clipLength from the equation * r1 == type.getRadius(clipLength,r2,clipLength+length) @@ -360,27 +382,27 @@ public class Transition extends SymmetricComponent { */ 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; @@ -389,7 +411,7 @@ public class Transition extends SymmetricComponent { if (n > 10) break; } - + while (true) { clipLength = (min + max) / 2; if ((max - min) < CLIP_PRECISION) @@ -402,14 +424,14 @@ public class Transition extends SymmetricComponent { } } } - - + + @Override public double getInnerRadius(double x) { return Math.max(getRadius(x) - thickness, 0); } - - + + @Override public Collection<Coordinate> getComponentBounds() { @@ -420,33 +442,33 @@ public class Transition extends SymmetricComponent { addBound(bounds, getLength() + aftShoulderLength, aftShoulderRadius); return bounds; } - + @Override - public double getComponentMass() { - double mass = super.getComponentMass(); + public double getComponentVolume() { + double volume = super.getComponentVolume(); if (getForeShoulderLength() > 0.001) { final double or = getForeShoulderRadius(); final double ir = Math.max(getForeShoulderRadius() - getForeShoulderThickness(), 0); - mass += ringMass(or, ir, getForeShoulderLength(), getMaterial().getDensity()); + volume += ringVolume( or, ir, getForeShoulderLength() ); } if (isForeShoulderCapped()) { final double ir = Math.max(getForeShoulderRadius() - getForeShoulderThickness(), 0); - mass += ringMass(ir, 0, getForeShoulderThickness(), getMaterial().getDensity()); + volume += ringVolume(ir, 0, getForeShoulderThickness() ); } - + if (getAftShoulderLength() > 0.001) { final double or = getAftShoulderRadius(); final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); - mass += ringMass(or, ir, getAftShoulderLength(), getMaterial().getDensity()); + volume += ringVolume(or, ir, getAftShoulderLength() ); } if (isAftShoulderCapped()) { final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); - mass += ringMass(ir, 0, getAftShoulderThickness(), getMaterial().getDensity()); + volume += ringVolume(ir, 0, getAftShoulderThickness() ); } - - return mass; + + return volume; } - + @Override public Coordinate getComponentCG() { Coordinate cg = super.getComponentCG(); @@ -461,7 +483,7 @@ public class Transition extends SymmetricComponent { getForeShoulderThickness() - getForeShoulderLength(), getMaterial().getDensity())); } - + if (getAftShoulderLength() > 0.001) { final double ir = Math.max(getAftShoulderRadius() - getAftShoulderThickness(), 0); cg = cg.average(ringCG(getAftShoulderRadius(), ir, getLength(), @@ -475,8 +497,8 @@ public class Transition extends SymmetricComponent { } return cg; } - - + + /* * The moments of inertia are not explicitly corrected for the shoulders. * However, since the mass is corrected, the inertia is automatically corrected @@ -493,13 +515,13 @@ public class Transition extends SymmetricComponent { //// 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. @@ -513,8 +535,63 @@ public class Transition extends SymmetricComponent { 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. @@ -522,7 +599,7 @@ public class Transition extends SymmetricComponent { * @author Sampo Niskanen <sampo.niskanen@iki.fi> */ public static enum Shape { - + /** * Conical shape. */ @@ -540,7 +617,7 @@ public class Transition extends SymmetricComponent { 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 @@ -556,12 +633,12 @@ public class Transition extends SymmetricComponent { 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; @@ -569,17 +646,17 @@ public class Transition extends SymmetricComponent { 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))); @@ -589,7 +666,7 @@ public class Transition extends SymmetricComponent { return MathUtil.safeSqrt(R * R - (L - x) * (L - x)) - y0; } }, - + /** * Ellipsoidal shape. */ @@ -597,7 +674,7 @@ public class Transition extends SymmetricComponent { 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. + //// 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) { @@ -608,7 +685,7 @@ public class Transition extends SymmetricComponent { return MathUtil.safeSqrt(2 * radius * x - x * x); // radius/length * sphere } }, - + //// Power series POWER(trans.get("Shape.Powerseries"), trans.get("Shape.Powerseries.desc1"), @@ -617,12 +694,12 @@ public class Transition extends SymmetricComponent { 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; @@ -638,29 +715,29 @@ public class Transition extends SymmetricComponent { } 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; @@ -668,28 +745,28 @@ public class Transition extends SymmetricComponent { 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. + //// 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; @@ -697,7 +774,7 @@ public class Transition extends SymmetricComponent { 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); @@ -705,7 +782,7 @@ public class Transition extends SymmetricComponent { 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 "+ @@ -737,18 +814,18 @@ public class Transition extends SymmetricComponent { // } // } ; - + // 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; @@ -756,29 +833,29 @@ public class Transition extends SymmetricComponent { 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. @@ -786,35 +863,35 @@ public class Transition extends SymmetricComponent { 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 @@ -828,8 +905,8 @@ public class Transition extends SymmetricComponent { * @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()). */ @@ -837,5 +914,22 @@ public class Transition extends SymmetricComponent { 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/TubeCoupler.java b/core/src/net/sf/openrocket/rocketcomponent/TubeCoupler.java index 5e22ec0c..4f50099c 100644 --- a/core/src/net/sf/openrocket/rocketcomponent/TubeCoupler.java +++ b/core/src/net/sf/openrocket/rocketcomponent/TubeCoupler.java @@ -1,6 +1,8 @@ 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; @@ -13,7 +15,12 @@ public class TubeCoupler extends ThicknessRingComponent implements RadialParent setLength(0.06); } - + @Override + public Type getPresetType() { + return ComponentPreset.Type.TUBE_COUPLER; + } + + // Make setter visible @Override public void setOuterRadiusAutomatic(boolean auto) { diff --git a/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java b/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java index 85be9120..0aab853a 100644 --- a/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java +++ b/core/src/net/sf/openrocket/simulation/AbstractSimulationStepper.java @@ -115,7 +115,7 @@ public abstract class AbstractSimulationStepper implements SimulationStepper { protected MassData calculateMassData(SimulationStatus status) throws SimulationException { MassData mass; Coordinate cg; - double longitudinalInertia, rotationalInertia; + double longitudinalInertia, rotationalInertia, propellantMass; // Call pre-listener mass = SimulationListenerHelper.firePreMassCalculation(status); @@ -127,7 +127,8 @@ public abstract class AbstractSimulationStepper implements SimulationStepper { cg = calc.getCG(status.getConfiguration(), status.getMotorConfiguration()); longitudinalInertia = calc.getLongitudinalInertia(status.getConfiguration(), status.getMotorConfiguration()); rotationalInertia = calc.getRotationalInertia(status.getConfiguration(), status.getMotorConfiguration()); - mass = new MassData(cg, longitudinalInertia, rotationalInertia); + propellantMass = calc.getPropellantMass(status.getConfiguration(), status.getMotorConfiguration()); + mass = new MassData(cg, longitudinalInertia, rotationalInertia, propellantMass); // Call post-listener mass = SimulationListenerHelper.firePostMassCalculation(status, mass); @@ -135,6 +136,7 @@ public abstract class AbstractSimulationStepper implements SimulationStepper { checkNaN(mass.getCG()); checkNaN(mass.getLongitudinalInertia()); checkNaN(mass.getRotationalInertia()); + checkNaN(mass.getPropellantMass()); return mass; } diff --git a/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java b/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java index 305516ad..17352062 100644 --- a/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java +++ b/core/src/net/sf/openrocket/simulation/BasicEventSimulationEngine.java @@ -6,6 +6,7 @@ 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; @@ -31,6 +32,7 @@ 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 @@ -468,15 +470,14 @@ public class BasicEventSimulationEngine implements SimulationEngine { // Check for launch rod if (!status.isLaunchRodCleared()) { - status.getWarnings().add(Warning.fromString("Recovery device device deployed while on " + - "the launch guide.")); + status.getWarnings().add(Warning.RECOVERY_LAUNCH_ROD); } // Check current velocity if (status.getRocketVelocity().length() > 20) { // TODO: LOW: Custom warning. - status.getWarnings().add(Warning.fromString("Recovery device deployment at high " + - "speed (" + status.getWarnings().add(Warning.fromString(trans.get("Warning.RECOVERY_HIGH_SPEED") + + " (" + UnitGroup.UNITS_VELOCITY.toStringUnit(status.getRocketVelocity().length()) + ").")); } diff --git a/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java b/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java index dc67e853..0d9c3954 100644 --- a/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java +++ b/core/src/net/sf/openrocket/simulation/BasicLandingStepper.java @@ -109,6 +109,8 @@ public class BasicLandingStepper extends AbstractSimulationStepper { 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()); } @@ -121,6 +123,7 @@ public class BasicLandingStepper extends AbstractSimulationStepper { 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); diff --git a/core/src/net/sf/openrocket/simulation/FlightDataBranch.java b/core/src/net/sf/openrocket/simulation/FlightDataBranch.java index f3eb3d9c..76bef764 100644 --- a/core/src/net/sf/openrocket/simulation/FlightDataBranch.java +++ b/core/src/net/sf/openrocket/simulation/FlightDataBranch.java @@ -68,7 +68,16 @@ public class FlightDataBranch implements Monitorable { } } - + /** + * 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. @@ -97,8 +106,8 @@ public class FlightDataBranch implements Monitorable { 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++) { @@ -106,10 +115,13 @@ public class FlightDataBranch implements Monitorable { } values.put(type, list); minValues.put(type, value); - maxValues.put(type, value); - + maxValues.put(type, value); } - list.set(list.size() - 1, value); + + if (list.size() > 0){ + list.set(list.size() - 1, value); + } + double min = minValues.get(type); double max = maxValues.get(type); diff --git a/core/src/net/sf/openrocket/simulation/FlightDataType.java b/core/src/net/sf/openrocket/simulation/FlightDataType.java index 26862420..adb4b51b 100644 --- a/core/src/net/sf/openrocket/simulation/FlightDataType.java +++ b/core/src/net/sf/openrocket/simulation/FlightDataType.java @@ -1,9 +1,11 @@ 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; @@ -22,221 +24,355 @@ import net.sf.openrocket.unit.UnitGroup; */ 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"), UnitGroup.UNITS_FLIGHT_TIME, 1); + 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"), UnitGroup.UNITS_DISTANCE, 10); + 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"), UnitGroup.UNITS_VELOCITY, 11); + 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"), UnitGroup.UNITS_ACCELERATION, 12); + 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"), UnitGroup.UNITS_VELOCITY, 20); + 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"), UnitGroup.UNITS_ACCELERATION, 21); + 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"), UnitGroup.UNITS_DISTANCE, 30); + 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"), UnitGroup.UNITS_DISTANCE, 31); + 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"), UnitGroup.UNITS_DISTANCE, 32); + 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"), UnitGroup.UNITS_ANGLE, 33); + 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"), UnitGroup.UNITS_VELOCITY, 34); + 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"), UnitGroup.UNITS_ACCELERATION, 35); + 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"), UnitGroup.UNITS_ANGLE, 36); + 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"), UnitGroup.UNITS_ANGLE, 37); + 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"), UnitGroup.UNITS_ANGLE, 40); + 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"), UnitGroup.UNITS_ROLL, 41); + 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"), UnitGroup.UNITS_ROLL, 42); + 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"), UnitGroup.UNITS_ROLL, 43); + 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"), UnitGroup.UNITS_MASS, 50); + 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"), UnitGroup.UNITS_INERTIA, 51); + 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"), UnitGroup.UNITS_INERTIA, 52); + 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"), UnitGroup.UNITS_LENGTH, 53); + 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"), UnitGroup.UNITS_LENGTH, 54); + 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"), UnitGroup.UNITS_COEFFICIENT, 55); + 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"), UnitGroup.UNITS_COEFFICIENT, 60); + 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"), UnitGroup.UNITS_COEFFICIENT, 61); + 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"), UnitGroup.UNITS_FORCE, 70); + 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"), UnitGroup.UNITS_FORCE, 71); + 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"), UnitGroup.UNITS_COEFFICIENT, 72); + 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"), UnitGroup.UNITS_COEFFICIENT, 73); + 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"), UnitGroup.UNITS_COEFFICIENT, 80); + 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"), UnitGroup.UNITS_COEFFICIENT, 81); + 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"), UnitGroup.UNITS_COEFFICIENT, 82); + 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"), UnitGroup.UNITS_COEFFICIENT, 90); + 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"), UnitGroup.UNITS_COEFFICIENT, 91); + 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"), UnitGroup.UNITS_COEFFICIENT, 92); + 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"), UnitGroup.UNITS_COEFFICIENT, 93); + 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"), UnitGroup.UNITS_COEFFICIENT, 94); + 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"), UnitGroup.UNITS_COEFFICIENT, 95); + 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"), UnitGroup.UNITS_COEFFICIENT, 96); + 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"), UnitGroup.UNITS_COEFFICIENT, 97); + 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"), UnitGroup.UNITS_COEFFICIENT, 98); + 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"), UnitGroup.UNITS_ACCELERATION, 99); + 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"), UnitGroup.UNITS_LENGTH, 100); + 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"), UnitGroup.UNITS_AREA, 101); + 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"), UnitGroup.UNITS_ANGLE, 106); + 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"), UnitGroup.UNITS_ANGLE, 107); + 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"), UnitGroup.UNITS_VELOCITY, 110); + 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"), UnitGroup.UNITS_TEMPERATURE, 111); + 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"), UnitGroup.UNITS_PRESSURE, 112); + 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"), UnitGroup.UNITS_VELOCITY, 113); + 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"), UnitGroup.UNITS_TIME_STEP, 200); + 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"), UnitGroup.UNITS_SHORT_TIME, 201); - + 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} based on a string description. This returns known data types - * if possible, or a new type otherwise. + * 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. */ - public static synchronized FlightDataType getType(String s, UnitGroup u) { - FlightDataType type = EXISTING_TYPES.get(s.toLowerCase()); + @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) { - return type; + // 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; + } } - type = newType(s, u, DEFAULT_PRIORITY); - 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, UnitGroup u, int priority) { - FlightDataType type = new FlightDataType(s, u, priority); - EXISTING_TYPES.put(s.toLowerCase(), type); + 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, UnitGroup units, int priority) { + 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().hashCode(); + 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; + return name; //+" ("+symbol+") "+units.getDefaultUnit().toString(); } @Override diff --git a/core/src/net/sf/openrocket/simulation/MassData.java b/core/src/net/sf/openrocket/simulation/MassData.java index 1d910df0..74386364 100644 --- a/core/src/net/sf/openrocket/simulation/MassData.java +++ b/core/src/net/sf/openrocket/simulation/MassData.java @@ -13,15 +13,17 @@ 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) { + 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; } @@ -39,6 +41,9 @@ public class MassData { return rotationalInertia; } + public double getPropellantMass() { + return propellantMass; + } @Override @@ -50,20 +55,20 @@ public class MassData { 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.rotationalInertia, other.rotationalInertia)) && MathUtil.equals(this.propellantMass, other.propellantMass) ; } @Override public int hashCode() { - return (int) (cg.hashCode() ^ Double.doubleToLongBits(longitudinalInertia) ^ Double.doubleToLongBits(rotationalInertia)); + 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 + "]"; + + ", rotationalInertia=" + rotationalInertia + ", propellantMass="+propellantMass + "]"; } } diff --git a/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java b/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java index 6b7aad9d..8548ec91 100644 --- a/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java +++ b/core/src/net/sf/openrocket/simulation/RK4SimulationStepper.java @@ -605,12 +605,14 @@ public class RK4SimulationStepper extends AbstractSimulationStepper { } 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) { diff --git a/core/src/net/sf/openrocket/simulation/SimulationConditions.java b/core/src/net/sf/openrocket/simulation/SimulationConditions.java index f2412717..ffd9e003 100644 --- a/core/src/net/sf/openrocket/simulation/SimulationConditions.java +++ b/core/src/net/sf/openrocket/simulation/SimulationConditions.java @@ -4,6 +4,7 @@ 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; @@ -27,6 +28,7 @@ public class SimulationConditions implements Monitorable, Cloneable { private Rocket rocket; private String motorID = null; + private Simulation simulation; // The parent simulation private double launchRodLength = 1; @@ -262,9 +264,14 @@ public class SimulationConditions implements Monitorable, Cloneable { 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; diff --git a/core/src/net/sf/openrocket/simulation/SimulationOptions.java b/core/src/net/sf/openrocket/simulation/SimulationOptions.java index 7734ec5d..a1b6bae9 100644 --- a/core/src/net/sf/openrocket/simulation/SimulationOptions.java +++ b/core/src/net/sf/openrocket/simulation/SimulationOptions.java @@ -5,8 +5,10 @@ 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; @@ -14,6 +16,7 @@ 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; @@ -31,6 +34,8 @@ import net.sf.openrocket.util.WorldCoordinate; */ public class SimulationOptions implements ChangeSource, Cloneable { + private static final LogHelper log = Application.getLogger(); + public static final double MAX_LAUNCH_ROD_ANGLE = Math.PI / 3; /** @@ -93,7 +98,6 @@ public class SimulationOptions implements ChangeSource, Cloneable { this.rocket = rocket; } - public Rocket getRocket() { return rocket; } diff --git a/core/src/net/sf/openrocket/simulation/customexpression/CustomExpression.java b/core/src/net/sf/openrocket/simulation/customexpression/CustomExpression.java new file mode 100644 index 00000000..e233deff --- /dev/null +++ b/core/src/net/sf/openrocket/simulation/customexpression/CustomExpression.java @@ -0,0 +1,528 @@ +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 new file mode 100644 index 00000000..243f7b15 --- /dev/null +++ b/core/src/net/sf/openrocket/simulation/customexpression/CustomExpressionSimulationListener.java @@ -0,0 +1,44 @@ +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 new file mode 100644 index 00000000..6e638d91 --- /dev/null +++ b/core/src/net/sf/openrocket/simulation/customexpression/Functions.java @@ -0,0 +1,269 @@ +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 new file mode 100644 index 00000000..6fb084de --- /dev/null +++ b/core/src/net/sf/openrocket/simulation/customexpression/IndexExpression.java @@ -0,0 +1,56 @@ +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 new file mode 100644 index 00000000..1667b61e --- /dev/null +++ b/core/src/net/sf/openrocket/simulation/customexpression/RangeExpression.java @@ -0,0 +1,117 @@ +/* + * 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/listeners/AbstractSimulationListener.java b/core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java index ebb2ad94..3f156f38 100644 --- a/core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java +++ b/core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java @@ -1,5 +1,7 @@ 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; @@ -8,6 +10,7 @@ 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; @@ -27,6 +30,16 @@ public class AbstractSimulationListener implements SimulationListener, Simulatio //// 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 @@ -57,9 +70,15 @@ public class AbstractSimulationListener implements SimulationListener, Simulatio return false; } + /** + * Return an array of any flight data types this listener creates. + */ + @Override + public FlightDataType[] getFlightDataTypes(){ + return new FlightDataType[] {}; + } + - - //// SimulationEventListener //// @Override @@ -83,7 +102,7 @@ public class AbstractSimulationListener implements SimulationListener, Simulatio } - + //// SimulationComputationListener //// @Override diff --git a/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java b/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java index be46c50f..3089d053 100644 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java +++ b/core/src/net/sf/openrocket/simulation/listeners/SimulationComputationListener.java @@ -1,9 +1,12 @@ 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; @@ -64,4 +67,5 @@ public interface SimulationComputationListener extends SimulationListener { 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 index 6cbb87f3..8ac0e11a 100644 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationEventListener.java +++ b/core/src/net/sf/openrocket/simulation/listeners/SimulationEventListener.java @@ -1,9 +1,12 @@ 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; @@ -56,6 +59,10 @@ public interface SimulationEventListener { */ 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 index 98b28aad..322db8e7 100644 --- a/core/src/net/sf/openrocket/simulation/listeners/SimulationListener.java +++ b/core/src/net/sf/openrocket/simulation/listeners/SimulationListener.java @@ -1,5 +1,8 @@ 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; @@ -7,6 +10,25 @@ 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. * @@ -57,4 +79,11 @@ public interface SimulationListener { */ 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/example/DampingMoment.java b/core/src/net/sf/openrocket/simulation/listeners/example/DampingMoment.java new file mode 100644 index 00000000..b9d2e463 --- /dev/null +++ b/core/src/net/sf/openrocket/simulation/listeners/example/DampingMoment.java @@ -0,0 +1,129 @@ +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/RollControlListener.java b/core/src/net/sf/openrocket/simulation/listeners/example/RollControlListener.java index 80993218..68063cb4 100644 --- a/core/src/net/sf/openrocket/simulation/listeners/example/RollControlListener.java +++ b/core/src/net/sf/openrocket/simulation/listeners/example/RollControlListener.java @@ -22,8 +22,7 @@ public class RollControlListener extends AbstractSimulationListener { 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", - UnitGroup.UNITS_ANGLE); + 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; diff --git a/core/src/net/sf/openrocket/startup/Application.java b/core/src/net/sf/openrocket/startup/Application.java index 7718b67e..18d1af77 100644 --- a/core/src/net/sf/openrocket/startup/Application.java +++ b/core/src/net/sf/openrocket/startup/Application.java @@ -1,5 +1,6 @@ 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; @@ -23,6 +24,8 @@ public final class Application { private static Translator baseTranslator = new DebugTranslator(null); private static MotorDatabase motorSetDatabase; + + private static ComponentPresetDao componentPresetDao; private static Preferences preferences; @@ -159,6 +162,15 @@ public final class Application { 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 new file mode 100644 index 00000000..79838ece --- /dev/null +++ b/core/src/net/sf/openrocket/startup/ConcurrentComponentPresetDatabaseLoader.java @@ -0,0 +1,140 @@ +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 new file mode 100644 index 00000000..2eba9b42 --- /dev/null +++ b/core/src/net/sf/openrocket/startup/ConcurrentLoadingThrustCurveMotorSetDatabase.java @@ -0,0 +1,302 @@ +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/OSXStartup.java b/core/src/net/sf/openrocket/startup/OSXStartup.java new file mode 100644 index 00000000..ad14186b --- /dev/null +++ b/core/src/net/sf/openrocket/startup/OSXStartup.java @@ -0,0 +1,115 @@ +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 index 0a5e62b9..73a29cc2 100644 --- a/core/src/net/sf/openrocket/startup/Preferences.java +++ b/core/src/net/sf/openrocket/startup/Preferences.java @@ -5,8 +5,8 @@ import java.util.Map; import java.util.Set; import net.sf.openrocket.database.Databases; -import net.sf.openrocket.l10n.Translator; 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; @@ -22,7 +22,7 @@ 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. @@ -45,26 +45,30 @@ public abstract class Preferences { 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 ); + 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 @@ -74,10 +78,10 @@ public abstract class Preferences { * @param defaultValue * @return */ - public abstract String getString( String directory, String key, String defaultValue); - - public abstract void putString( String directory, String key, String value ); - + public abstract String getString(String directory, String key, String defaultValue); + + public abstract void putString(String directory, String key, String value); + /* * ****************************************************************************************** */ @@ -173,7 +177,7 @@ public abstract class Preferences { putString(key, value.name()); } } - + public Color getDefaultColor(Class<? extends RocketComponent> c) { String color = get("componentColors", c, DEFAULT_COLORS); if (color == null) @@ -192,8 +196,8 @@ public abstract class Preferences { return; putString("componentColors", c.getSimpleName(), stringifyColor(color)); } - - + + /** * Retrieve a Line style for the given component. * @param c @@ -262,16 +266,16 @@ public abstract class Preferences { 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 ) { + public final Color getColor(String key, Color defaultValue) { + Color c = parseColor(getString(key, null)); + if (c == null) { return defaultValue; } return c; @@ -282,10 +286,10 @@ public abstract class Preferences { * @param key * @param value */ - public final void putColor( String key, Color value ) { - putString( key, stringifyColor(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 @@ -319,7 +323,7 @@ public abstract class Preferences { String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue(); return string; } - + /** * Special helper function which allows for a map of default values. * @@ -358,11 +362,17 @@ public abstract class Preferences { 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 */ @@ -377,18 +387,9 @@ public abstract class Preferences { * Within a holder class so they will load only when needed. */ private static class DefaultMaterialHolder { - private static final Translator trans = Application.getTranslator(); - - //// Elastic cord (round 2mm, 1/16 in) - private static final Material DEFAULT_LINE_MATERIAL = - Databases.findMaterial(Material.Type.LINE, trans.get("Databases.materials.Elasticcordround2mm"), - 0.0018, false); - //// Ripstop nylon - private static final Material DEFAULT_SURFACE_MATERIAL = - Databases.findMaterial(Material.Type.SURFACE, trans.get("Databases.materials.Ripstopnylon"), 0.067, false); - //// Cardboard - private static final Material DEFAULT_BULK_MATERIAL = - Databases.findMaterial(Material.Type.BULK, trans.get("Databases.materials.Cardboard"), 680, false); + 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 = @@ -402,6 +403,6 @@ public abstract class Preferences { 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 index d288ea76..31f83184 100644 --- a/core/src/net/sf/openrocket/startup/Startup.java +++ b/core/src/net/sf/openrocket/startup/Startup.java @@ -38,7 +38,6 @@ public class Startup { private static final int LOG_BUFFER_LENGTH = 50; - /** * OpenRocket startup main method. */ @@ -54,13 +53,12 @@ public class Startup { // 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. @@ -86,7 +84,7 @@ public class Startup { /** * Initializes the loggins system. */ - private static void initializeLogging() { + public static void initializeLogging() { DelegatorLogger delegator = new DelegatorLogger(); // Log buffer diff --git a/core/src/net/sf/openrocket/startup/Startup2.java b/core/src/net/sf/openrocket/startup/Startup2.java index 11ceb190..6b7b49cd 100644 --- a/core/src/net/sf/openrocket/startup/Startup2.java +++ b/core/src/net/sf/openrocket/startup/Startup2.java @@ -4,31 +4,24 @@ import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; 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.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.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.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.BuildProperties; /** @@ -43,11 +36,6 @@ public class Startup2 { private static final String THRUSTCURVE_DIRECTORY = "datafiles/thrustcurves/"; - /** Block motor loading for this many milliseconds */ - private static AtomicInteger blockLoading = new AtomicInteger(Integer.MAX_VALUE); - - - /** * Run when starting up OpenRocket after Application has been set up. * @@ -66,6 +54,11 @@ public class Startup2 { 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() { @@ -90,6 +83,25 @@ public class Startup2 { 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(); @@ -119,9 +131,12 @@ public class Startup2 { // 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)) { @@ -132,10 +147,16 @@ public class Startup2 { log.info("Checking update status"); checkUpdateStatus(updateInfo); - // Block motor loading for 1.5 seconds to allow window painting to be faster - blockLoading.set(1500); } + /** + * 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. @@ -154,78 +175,6 @@ public class Startup2 { } - private static void loadMotor() { - - log.info("Starting motor loading from " + THRUSTCURVE_DIRECTORY + " in background thread."); - ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(true) { - - @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()); - - // Start loading - log.info("Loading motors from " + THRUSTCURVE_DIRECTORY); - long t0 = System.currentTimeMillis(); - int fileCount; - int thrustCurveCount; - - // Load the packaged thrust curves - List<Motor> list; - FileIterator iterator = DirectoryIterator.findDirectory(THRUSTCURVE_DIRECTORY, - new SimpleFileFilter("", false, "eng", "rse")); - if (iterator == null) { - throw new IllegalStateException("Thrust curve directory " + THRUSTCURVE_DIRECTORY + - "not found, distribution built wrong"); - } - list = MotorLoaderHelper.load(iterator); - for (Motor m : list) { - this.addMotor((ThrustCurveMotor) m); - } - fileCount = iterator.getFileCount(); - - thrustCurveCount = list.size(); - - // Load the user-defined thrust curves - for (File file : ((SwingPreferences) Application.getPreferences()).getUserThrustCurveFiles()) { - log.info("Loading motors from " + file); - list = MotorLoaderHelper.load(file); - for (Motor m : list) { - this.addMotor((ThrustCurveMotor) m); - } - fileCount++; - thrustCurveCount += list.size(); - } - - long t1 = System.currentTimeMillis(); - - // Count statistics - int distinctMotorCount = 0; - int distinctThrustCurveCount = 0; - distinctMotorCount = motorSets.size(); - for (ThrustCurveMotorSet set : motorSets) { - distinctThrustCurveCount += set.getMotorCount(); - } - log.info("Motor loading done, took " + (t1 - t0) + " ms to load " - + fileCount + " files/directories containing " - + thrustCurveCount + " thrust curves which contained " - + distinctMotorCount + " distinct motors with " - + distinctThrustCurveCount + " distinct thrust curves."); - } - - }; - db.startLoading(); - Application.setMotorSetDatabase(db); - } - private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) { if (updateInfo == null) return; diff --git a/core/src/net/sf/openrocket/startup/VersionHelper.java b/core/src/net/sf/openrocket/startup/VersionHelper.java index 097f1dc4..0b3d9182 100644 --- a/core/src/net/sf/openrocket/startup/VersionHelper.java +++ b/core/src/net/sf/openrocket/startup/VersionHelper.java @@ -1,6 +1,7 @@ package net.sf.openrocket.startup; import java.awt.GraphicsEnvironment; +import java.util.Locale; import javax.swing.JOptionPane; @@ -59,8 +60,8 @@ public class VersionHelper { */ static void checkOpenJDK() { - if (System.getProperty("java.runtime.name", "").toLowerCase().indexOf("icedtea") >= 0 || - System.getProperty("java.vm.name", "").toLowerCase().indexOf("openjdk") >= 0) { + 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)"); @@ -79,7 +80,7 @@ public class VersionHelper { } - + /////////// Helper methods ////////// /** @@ -97,7 +98,7 @@ public class VersionHelper { } System.err.println(); - + if (!GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, message, "Error starting OpenRocket", diff --git a/core/src/net/sf/openrocket/unit/FixedUnitGroup.java b/core/src/net/sf/openrocket/unit/FixedUnitGroup.java new file mode 100644 index 00000000..8cb6fde4 --- /dev/null +++ b/core/src/net/sf/openrocket/unit/FixedUnitGroup.java @@ -0,0 +1,35 @@ +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 new file mode 100644 index 00000000..740e4776 --- /dev/null +++ b/core/src/net/sf/openrocket/unit/FractionalUnit.java @@ -0,0 +1,245 @@ +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/Unit.java b/core/src/net/sf/openrocket/unit/Unit.java index 4703b31b..dda76944 100644 --- a/core/src/net/sf/openrocket/unit/Unit.java +++ b/core/src/net/sf/openrocket/unit/Unit.java @@ -70,42 +70,6 @@ public abstract class Unit { return true; } - - // Testcases for toString(double) - public static void main(String arg[]) { - System.out.println(NOUNIT2.toString(0.0049)); - System.out.println(NOUNIT2.toString(0.0050)); - System.out.println(NOUNIT2.toString(0.0051)); - System.out.println(NOUNIT2.toString(0.00123)); - System.out.println(NOUNIT2.toString(0.0123)); - System.out.println(NOUNIT2.toString(0.1234)); - System.out.println(NOUNIT2.toString(1.2345)); - System.out.println(NOUNIT2.toString(12.345)); - System.out.println(NOUNIT2.toString(123.456)); - System.out.println(NOUNIT2.toString(1234.5678)); - System.out.println(NOUNIT2.toString(12345.6789)); - System.out.println(NOUNIT2.toString(123456.789)); - System.out.println(NOUNIT2.toString(1234567.89)); - System.out.println(NOUNIT2.toString(12345678.9)); - - System.out.println(NOUNIT2.toString(-0.0049)); - System.out.println(NOUNIT2.toString(-0.0050)); - System.out.println(NOUNIT2.toString(-0.0051)); - System.out.println(NOUNIT2.toString(-0.00123)); - System.out.println(NOUNIT2.toString(-0.0123)); - System.out.println(NOUNIT2.toString(-0.1234)); - System.out.println(NOUNIT2.toString(-1.2345)); - System.out.println(NOUNIT2.toString(-12.345)); - System.out.println(NOUNIT2.toString(-123.456)); - System.out.println(NOUNIT2.toString(-1234.5678)); - System.out.println(NOUNIT2.toString(-12345.6789)); - System.out.println(NOUNIT2.toString(-123456.789)); - System.out.println(NOUNIT2.toString(-1234567.89)); - System.out.println(NOUNIT2.toString(-12345678.9)); - - } - - @Override public String toString() { return unit; @@ -115,6 +79,7 @@ public abstract class Unit { 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"); /** @@ -134,9 +99,12 @@ public abstract class Unit { if (Math.abs(val) >= 100) { return intFormat.format(val); } - if (Math.abs(val) <= 0.005) { + 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); @@ -146,7 +114,6 @@ public abstract class Unit { val *= 10; } val = Math.rint(val) / mul * sign; - return decFormat.format(val); } diff --git a/core/src/net/sf/openrocket/unit/UnitGroup.java b/core/src/net/sf/openrocket/unit/UnitGroup.java index f72f22a9..48ae67a9 100644 --- a/core/src/net/sf/openrocket/unit/UnitGroup.java +++ b/core/src/net/sf/openrocket/unit/UnitGroup.java @@ -27,6 +27,7 @@ public class UnitGroup { 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; @@ -37,6 +38,7 @@ public class UnitGroup { */ 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; @@ -62,11 +64,17 @@ public class UnitGroup { public static final UnitGroup UNITS_ROUGHNESS; public static final UnitGroup UNITS_COEFFICIENT; + public static final UnitGroup UNITS_FREQUENCY; - // 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; + 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" /* @@ -79,15 +87,47 @@ public class UnitGroup { 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")); @@ -101,6 +141,19 @@ public class UnitGroup { 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)); @@ -111,6 +164,7 @@ public class UnitGroup { 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")); @@ -127,6 +181,12 @@ public class UnitGroup { 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)); @@ -154,6 +214,7 @@ public class UnitGroup { 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)); @@ -225,6 +286,7 @@ public class UnitGroup { 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")); @@ -234,18 +296,20 @@ public class UnitGroup { // This is not used by OpenRocket, and not extensively tested: - // UNITS_FREQUENCY = new UnitGroup(); + 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(1, "Hz")); - // UNITS_FREQUENCY.addUnit(new FrequencyUnit(1000, "kHz")); - // UNITS_FREQUENCY.setDefaultUnit(3); + 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); @@ -269,8 +333,36 @@ public class UnitGroup { 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() { @@ -293,6 +385,7 @@ public class UnitGroup { 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"); @@ -318,6 +411,7 @@ public class UnitGroup { 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"); @@ -382,7 +476,14 @@ public class UnitGroup { 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 @@ -419,6 +520,14 @@ public class UnitGroup { 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); @@ -440,6 +549,17 @@ public class UnitGroup { 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. @@ -480,7 +600,28 @@ public class UnitGroup { 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.,-]+)(.*?)$"); @@ -531,6 +672,15 @@ public class UnitGroup { /////////////////////////// + @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. diff --git a/core/src/net/sf/openrocket/util/AlphanumComparator.java b/core/src/net/sf/openrocket/util/AlphanumComparator.java new file mode 100644 index 00000000..c7a7b488 --- /dev/null +++ b/core/src/net/sf/openrocket/util/AlphanumComparator.java @@ -0,0 +1,139 @@ +/* + * 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/ArrayUtils.java b/core/src/net/sf/openrocket/util/ArrayUtils.java new file mode 100644 index 00000000..d0293940 --- /dev/null +++ b/core/src/net/sf/openrocket/util/ArrayUtils.java @@ -0,0 +1,250 @@ +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 index 042d3671..aeed54a1 100644 --- a/core/src/net/sf/openrocket/util/Base64.java +++ b/core/src/net/sf/openrocket/util/Base64.java @@ -3,7 +3,6 @@ package net.sf.openrocket.util; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import java.util.Random; public class Base64 { @@ -81,7 +80,7 @@ public class Base64 { if (p==0) break; if (p!=4) { - throw new IllegalArgumentException("Data ended when decoding Base64, p="+p); + throw new IllegalArgumentException("Data ended when decoding Base64, data=" + data + ", p="+p); } int l = decodeGroup(block, array, length); @@ -166,67 +165,4 @@ public class Base64 { return 3; } - - - public static void main(String[] arg) { - 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 = encode(array); - - System.out.println(encoded); - System.exit(0); -// for (int i=0; i<1000; i++) { -// int pos = rnd.nextInt(encoded.length()); -// String s1 = encoded.substring(0, pos); -// String s2 = encoded.substring(pos); -// switch (rnd.nextInt(15)) { -// case 0: -// encoded = s1 + " " + s2; -// break; -// case 1: -// encoded = s1 + "\u0009" + s2; -// break; -// case 2: -// encoded = s1 + "\n" + s2; -// break; -// case 3: -// encoded = s1 + "\u000B" + s2; -// break; -// case 4: -// encoded = s1 + "\r" + s2; -// break; -// case 5: -// encoded = s1 + "\u000C" + s2; -// break; -// case 6: -// encoded = s1 + "\u001C" + s2; -// break; -// } -// } - - byte[] decoded = null; - try { - decoded = decode(encoded); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - System.err.println("Bad data:\n"+encoded); - System.exit(1); - } - - if (!Arrays.equals(array, decoded)) { - System.err.println("Data differs! n="+n); - System.exit(1); - } - System.out.println("n="+n+" ok!"); - } - } - - } diff --git a/core/src/net/sf/openrocket/util/BuildProperties.java b/core/src/net/sf/openrocket/util/BuildProperties.java index 46bc3c20..9e88e93e 100644 --- a/core/src/net/sf/openrocket/util/BuildProperties.java +++ b/core/src/net/sf/openrocket/util/BuildProperties.java @@ -32,7 +32,7 @@ public class BuildProperties { static { try { - InputStream is = ClassLoader.getSystemResourceAsStream("build.properties"); + InputStream is = BuildProperties.class.getClassLoader().getResourceAsStream("build.properties"); if (is == null) { throw new MissingResourceException( "build.properties not found, distribution built wrong" + diff --git a/core/src/net/sf/openrocket/util/Chars.java b/core/src/net/sf/openrocket/util/Chars.java index eeba22bc..1b2857a2 100644 --- a/core/src/net/sf/openrocket/util/Chars.java +++ b/core/src/net/sf/openrocket/util/Chars.java @@ -13,6 +13,8 @@ public class Chars { 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'; diff --git a/core/src/net/sf/openrocket/util/Coordinate.java b/core/src/net/sf/openrocket/util/Coordinate.java index 3bc981aa..0f65ffa4 100644 --- a/core/src/net/sf/openrocket/util/Coordinate.java +++ b/core/src/net/sf/openrocket/util/Coordinate.java @@ -12,8 +12,11 @@ import net.sf.openrocket.startup.Application; * * @author Sampo Niskanen <sampo.niskanen@iki.fi> */ -public final class Coordinate implements Serializable { +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 /* @@ -68,8 +71,6 @@ public final class Coordinate implements Serializable { private double length = -1; /* Cached when calculated */ - - public Coordinate() { this(0, 0, 0, 0); } @@ -315,6 +316,10 @@ public final class Coordinate implements Serializable { 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 new file mode 100644 index 00000000..d3a3fa62 --- /dev/null +++ b/core/src/net/sf/openrocket/util/ExpressionParser.java @@ -0,0 +1,67 @@ +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/GeodeticComputationStrategy.java b/core/src/net/sf/openrocket/util/GeodeticComputationStrategy.java index f8a37a09..0721e893 100644 --- a/core/src/net/sf/openrocket/util/GeodeticComputationStrategy.java +++ b/core/src/net/sf/openrocket/util/GeodeticComputationStrategy.java @@ -1,5 +1,7 @@ package net.sf.openrocket.util; +import java.util.Locale; + import net.sf.openrocket.l10n.Translator; import net.sf.openrocket.startup.Application; @@ -13,7 +15,7 @@ import net.sf.openrocket.startup.Application; */ public enum GeodeticComputationStrategy { - + /** * Perform computations using a flat Earth approximation. addCoordinate computes the * location using a direct meters-per-degree scaling and getCoriolisAcceleration always @@ -131,7 +133,7 @@ public enum GeodeticComputationStrategy { } }; - + private static final Translator trans = Application.getTranslator(); private static final double PRECISION_LIMIT = 0.5e-13; @@ -141,14 +143,14 @@ public enum GeodeticComputationStrategy { * Return the name of this geodetic computation method. */ public String getName() { - return trans.get(name().toLowerCase() + ".name"); + return trans.get(name().toLowerCase(Locale.ENGLISH) + ".name"); } /** * Return a description of the geodetic computation methods. */ public String getDescription() { - return trans.get(name().toLowerCase() + ".desc"); + return trans.get(name().toLowerCase(Locale.ENGLISH) + ".desc"); } @Override @@ -169,9 +171,9 @@ public enum GeodeticComputationStrategy { public abstract Coordinate getCoriolisAcceleration(WorldCoordinate location, Coordinate velocity); - - - + + + private static Coordinate computeCoriolisAcceleration(WorldCoordinate latlon, Coordinate velocity) { double sinlat = Math.sin(latlon.getLatitudeRad()); @@ -189,14 +191,14 @@ public enum GeodeticComputationStrategy { // 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) - ); + 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 @@ -226,8 +228,8 @@ public enum GeodeticComputationStrategy { * point, in radians clockwise from north. */ private static double[] dirct1(double glat1, double glon1, - double azimuth, double dist, - double axis, double flat) { + double azimuth, double dist, + double axis, double flat) { double r = 1.0 - flat; double tu = r * Math.sin(glat1) / Math.cos(glat1); @@ -264,7 +266,7 @@ public enum GeodeticComputationStrategy { 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; + d / 4.0 - cz) * sy * d + tu; } while (Math.abs(y - c) > PRECISION_LIMIT); baz = cu * cy * cf - su * sy; @@ -285,5 +287,5 @@ public enum GeodeticComputationStrategy { return ret; } - + } diff --git a/core/src/net/sf/openrocket/util/InvalidExpressionException.java b/core/src/net/sf/openrocket/util/InvalidExpressionException.java new file mode 100644 index 00000000..118cefe0 --- /dev/null +++ b/core/src/net/sf/openrocket/util/InvalidExpressionException.java @@ -0,0 +1,22 @@ +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/JarUtil.java b/core/src/net/sf/openrocket/util/JarUtil.java index b73438ed..545cfa58 100644 --- a/core/src/net/sf/openrocket/util/JarUtil.java +++ b/core/src/net/sf/openrocket/util/JarUtil.java @@ -18,8 +18,15 @@ public class JarUtil { */ public static File getCurrentJarFile() { // Find the jar file this class is contained in + URL jarUrl = null; - CodeSource codeSource = Database.class.getProtectionDomain().getCodeSource(); + 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(); diff --git a/core/src/net/sf/openrocket/util/LinearInterpolator.java b/core/src/net/sf/openrocket/util/LinearInterpolator.java index e94a3976..e16726bb 100644 --- a/core/src/net/sf/openrocket/util/LinearInterpolator.java +++ b/core/src/net/sf/openrocket/util/LinearInterpolator.java @@ -1,7 +1,8 @@ package net.sf.openrocket.util; import java.util.Iterator; -import java.util.Map; +import java.util.List; +import java.util.SortedMap; import java.util.TreeMap; public class LinearInterpolator implements Cloneable { @@ -14,7 +15,7 @@ public class LinearInterpolator implements Cloneable { */ public LinearInterpolator() { } - + /** * Construct a <code>LinearInterpolator</code> with the given points. * @@ -27,8 +28,11 @@ public class LinearInterpolator implements Cloneable { 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. * @@ -38,7 +42,7 @@ public class LinearInterpolator implements Cloneable { public void addPoint(double x, double y) { sortMap.put(x, y); } - + /** * Add the points to the linear interpolation. * @@ -56,41 +60,75 @@ public class LinearInterpolator implements Cloneable { 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) { - Map.Entry<Double,Double> e1, e2; double x1, x2; - double y1, y2; + 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. - e1 = sortMap.floorEntry(x); + // let's just make certain that our map is not empty. + if ( sortMap.isEmpty() ) { + throw new IllegalStateException("No points added yet to the interpolator."); + } - if (e1 == null) { - // x smaller than any value in the set - e1 = sortMap.firstEntry(); - if (e1 == null) { - throw new IllegalStateException("No points added yet to the interpolator."); - } - return e1.getValue(); + // 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(); } - x1 = e1.getKey(); - e2 = sortMap.higherEntry(x1); + // 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); - if (e2 == null) { - // x larger than any value in the set - return e1.getValue(); + // 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(); - x2 = e2.getKey(); - y1 = e1.getValue(); - y2 = e2.getValue(); + // 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(); @@ -99,8 +137,8 @@ public class LinearInterpolator implements Cloneable { } return x; } - - + + @SuppressWarnings("unchecked") @Override public LinearInterpolator clone() { @@ -113,16 +151,4 @@ public class LinearInterpolator implements Cloneable { } } - - public static void main(String[] args) { - LinearInterpolator interpolator = new LinearInterpolator( - new double[] {1, 1.5, 2, 4, 5}, - new double[] {0, 1, 0, 2, 2} - ); - - for (double x=0; x < 6; x+=0.1) { - System.out.printf("%.1f: %.2f\n", x, interpolator.getValue(x)); - } - } - } diff --git a/core/src/net/sf/openrocket/util/MathUtil.java b/core/src/net/sf/openrocket/util/MathUtil.java index c88e8585..09a31689 100644 --- a/core/src/net/sf/openrocket/util/MathUtil.java +++ b/core/src/net/sf/openrocket/util/MathUtil.java @@ -310,7 +310,7 @@ public class MathUtil { 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 diff --git a/core/src/net/sf/openrocket/util/PolyInterpolator.java b/core/src/net/sf/openrocket/util/PolyInterpolator.java index f97d45c4..134f7178 100644 --- a/core/src/net/sf/openrocket/util/PolyInterpolator.java +++ b/core/src/net/sf/openrocket/util/PolyInterpolator.java @@ -228,35 +228,4 @@ public class PolyInterpolator { } } - - - - public static void main(String[] arg) { - - 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); - - 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); - - 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); - - - for (double x=0.6; x <= 1.11; x += 0.01) { - System.out.println(x + " " + eval(x,r0) + " " + eval(x,r1) + " " + eval(x,r2)); - } - - } } diff --git a/core/src/net/sf/openrocket/util/Quaternion.java b/core/src/net/sf/openrocket/util/Quaternion.java index 5f277662..e82eb9d2 100644 --- a/core/src/net/sf/openrocket/util/Quaternion.java +++ b/core/src/net/sf/openrocket/util/Quaternion.java @@ -318,39 +318,4 @@ public class Quaternion { return String.format("Quaternion[%f,%f,%f,%f,norm=%f]", w, x, y, z, this.norm()); } - public static void main(String[] arg) { - - Quaternion q = new Quaternion(Math.random() - 0.5, Math.random() - 0.5, - Math.random() - 0.5, Math.random() - 0.5); - q.normalize(); - - q = new Quaternion(-0.998717, 0.000000, 0.050649, -0.000000); - - Coordinate coord = new Coordinate(10 * (Math.random() - 0.5), - 10 * (Math.random() - 0.5), 10 * (Math.random() - 0.5)); - - System.out.println("Quaternion: " + q); - System.out.println("Coordinate: " + coord); - coord = q.invRotate(coord); - System.out.println("Rotated: " + coord); - coord = q.rotate(coord); - System.out.println("Back: " + coord); - - - q = new Quaternion(0.237188, 0.570190, -0.514542, 0.594872); - q.normalize(); - Coordinate c = new Coordinate(148578428.914, 8126778.954, -607.741); - - System.out.println("Rotated: " + q.rotate(c)); - - // Coordinate c = new Coordinate(0,1,0); - // Coordinate rot = new Coordinate(Math.PI/4,0,0); - // - // System.out.println("Before: "+c); - // c = rotation(rot).invRotate(c); - // System.out.println("After: "+c); - - - } - } diff --git a/core/src/net/sf/openrocket/util/SimpleStack.java b/core/src/net/sf/openrocket/util/SimpleStack.java new file mode 100644 index 00000000..6bdd9671 --- /dev/null +++ b/core/src/net/sf/openrocket/util/SimpleStack.java @@ -0,0 +1,29 @@ +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/TestRockets.java b/core/src/net/sf/openrocket/util/TestRockets.java index 0dfc5629..7a670e16 100644 --- a/core/src/net/sf/openrocket/util/TestRockets.java +++ b/core/src/net/sf/openrocket/util/TestRockets.java @@ -2,6 +2,7 @@ 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; @@ -81,12 +82,12 @@ public class TestRockets { 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)); @@ -104,7 +105,7 @@ public class TestRockets { nose.setType((Shape) randomEnum(Shape.class)); stage.addChild(nose); - + Transition shoulder = new Transition(); setBasics(shoulder); shoulder.setAftRadius(rnd(0.06)); @@ -128,7 +129,7 @@ public class TestRockets { shoulder.setType((Shape) randomEnum(Shape.class)); stage.addChild(shoulder); - + BodyTube body = new BodyTube(); setBasics(body); body.setThickness(rnd(0.002)); @@ -142,7 +143,7 @@ public class TestRockets { body.setOuterRadiusAutomatic(rnd.nextBoolean()); stage.addChild(body); - + Transition boattail = new Transition(); setBasics(boattail); boattail.setAftRadius(rnd(0.03)); @@ -166,7 +167,7 @@ public class TestRockets { boattail.setType((Shape) randomEnum(Shape.class)); stage.addChild(boattail); - + MassComponent mass = new MassComponent(); setBasics(mass); mass.setComponentMass(rnd(0.05)); @@ -176,9 +177,9 @@ public class TestRockets { mass.setRadius(rnd(0.05)); nose.addChild(mass); - - - + + + return rocket; } @@ -203,7 +204,7 @@ public class TestRockets { ExternalComponent e = (ExternalComponent) c; e.setFinish((Finish) randomEnum(Finish.class)); double d = rnd(100); - e.setMaterial(Material.newMaterial(Type.BULK, "Testmat " + d, d, rnd.nextBoolean())); + e.setMaterial(Databases.findMaterial(Type.BULK, "Testmat " + d, d)); } if (c instanceof InternalComponent) { @@ -214,7 +215,7 @@ public class TestRockets { } - + private double rnd(double scale) { return (rnd.nextDouble() * 0.2 + 0.9) * scale; } @@ -232,9 +233,9 @@ public class TestRockets { } - - - + + + public Rocket makeSmallFlyable() { double noseconeLength = 0.10, noseconeRadius = 0.01; double bodytubeLength = 0.20, bodytubeRadius = 0.01, bodytubeThickness = 0.001; @@ -242,7 +243,7 @@ public class TestRockets { 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; @@ -258,11 +259,11 @@ public class TestRockets { finset = new TrapezoidFinSet(finCount, finRootChord, finTipChord, finSweep, finHeight); - + // Stage construction rocket.addChild(stage); - + // Component construction stage.addChild(nosecone); stage.addChild(bodytube); @@ -284,7 +285,7 @@ public class TestRockets { rocket.getDefaultConfiguration().setAllStages(); - + return rocket; } @@ -331,7 +332,7 @@ public class TestRockets { rocket.addChild(stage); rocket.setPerfectFinish(false); - + // Component construction stage.addChild(nosecone); stage.addChild(bodytube); @@ -355,12 +356,12 @@ public class TestRockets { rocket.getDefaultConfiguration().setAllStages(); - + return rocket; } - + public static Rocket makeIsoHaisu() { Rocket rocket; Stage stage; @@ -397,7 +398,7 @@ public class TestRockets { tube3.setOverrideMass(0.730); stage.addChild(tube3); - + LaunchLug lug = new LaunchLug(); tube1.addChild(lug); @@ -411,7 +412,7 @@ public class TestRockets { coupler.setPositionValue(-0.14); tube1.addChild(coupler); - + // Parachute MassComponent mass = new MassComponent(0.05, 0.05, 0.280); mass.setRelativePosition(Position.TOP); @@ -430,7 +431,7 @@ public class TestRockets { mass.setPositionValue(0.25); tube1.addChild(mass); - + auxfinset = new TrapezoidFinSet(); auxfinset.setName("CONTROL"); auxfinset.setFinCount(2); @@ -445,9 +446,9 @@ public class TestRockets { auxfinset.setBaseRotation(Math.PI / 2); tube1.addChild(auxfinset); - - - + + + coupler = new TubeCoupler(); coupler.setOuterRadiusAutomatic(true); coupler.setLength(0.28); @@ -457,8 +458,8 @@ public class TestRockets { coupler.setOverrideMass(0.360); tube2.addChild(coupler); - - + + // Parachute mass = new MassComponent(0.1, 0.05, 0.028); mass.setRelativePosition(Position.TOP); @@ -479,8 +480,8 @@ public class TestRockets { mass.setPositionValue(0.19); tube2.addChild(mass); - - + + InnerTube inner = new InnerTube(); inner.setOuterRadius(0.08 / 2); inner.setInnerRadius(0.0762 / 2); @@ -489,7 +490,7 @@ public class TestRockets { inner.setOverrideMass(0.388); tube3.addChild(inner); - + CenteringRing center = new CenteringRing(); center.setInnerRadiusAutomatic(true); center.setOuterRadiusAutomatic(true); @@ -500,7 +501,7 @@ public class TestRockets { center.setPositionValue(0); tube3.addChild(center); - + center = new CenteringRing(); center.setInnerRadiusAutomatic(true); center.setOuterRadiusAutomatic(true); @@ -511,7 +512,7 @@ public class TestRockets { center.setPositionValue(0.28); tube3.addChild(center); - + center = new CenteringRing(); center.setInnerRadiusAutomatic(true); center.setOuterRadiusAutomatic(true); @@ -522,10 +523,10 @@ public class TestRockets { center.setPositionValue(0.83); tube3.addChild(center); - - - - + + + + finset = new TrapezoidFinSet(); finset.setRootChord(0.495); finset.setTipChord(0.1); @@ -537,17 +538,17 @@ public class TestRockets { 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); @@ -560,10 +561,10 @@ public class TestRockets { 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 index 32dffd84..0b86876d 100644 --- a/core/src/net/sf/openrocket/util/TextUtil.java +++ b/core/src/net/sf/openrocket/util/TextUtil.java @@ -1,12 +1,32 @@ 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 @@ -164,4 +184,17 @@ public class TextUtil { 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 index 2c546974..8656a4f2 100644 --- a/core/src/net/sf/openrocket/util/Transformation.java +++ b/core/src/net/sf/openrocket/util/Transformation.java @@ -257,23 +257,4 @@ public class Transformation implements java.io.Serializable { return this.translate.equals(o.translate); } - public static void main(String[] arg) { - Transformation t; - - t = new Transformation(); - t.print("Empty"); - t = new Transformation(1,2,3); - t.print("1,2,3"); - t = new Transformation(new Coordinate(2,3,4)); - t.print("coord 2,3 4"); - - t = Transformation.rotate_y(0.01); - t.print("rotate_y 0.01"); - - t = new Transformation(-1,0,0); - t = t.applyTransformation(Transformation.rotate_y(0.01)); - t = t.applyTransformation(new Transformation(1,0,0)); - t.print("shift-rotate-shift"); - } - } diff --git a/core/src/net/sf/openrocket/util/enums/EnumConversion.java b/core/src/net/sf/openrocket/util/enums/EnumConversion.java new file mode 100644 index 00000000..4b8624f6 --- /dev/null +++ b/core/src/net/sf/openrocket/util/enums/EnumConversion.java @@ -0,0 +1,7 @@ +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 new file mode 100644 index 00000000..78210612 --- /dev/null +++ b/core/src/net/sf/openrocket/util/enums/EnumName.java @@ -0,0 +1,63 @@ +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/L10NGenerator.java b/core/src/net/sf/openrocket/utils/L10NGenerator.java new file mode 100644 index 00000000..de64a101 --- /dev/null +++ b/core/src/net/sf/openrocket/utils/L10NGenerator.java @@ -0,0 +1,56 @@ +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/test/net/sf/openrocket/communication/HttpURLConnectionMock.java b/core/test/net/sf/openrocket/communication/HttpURLConnectionMock.java index ab5c48ab..57f5d520 100644 --- a/core/test/net/sf/openrocket/communication/HttpURLConnectionMock.java +++ b/core/test/net/sf/openrocket/communication/HttpURLConnectionMock.java @@ -14,12 +14,13 @@ 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 { @@ -88,7 +89,7 @@ public class HttpURLConnectionMock extends HttpURLConnection { } - + @Override public void connect() { if (!connected) { @@ -99,17 +100,17 @@ public class HttpURLConnectionMock extends HttpURLConnection { connected = true; } } - + @Override public void disconnect() { } - + @Override public boolean usingProxy() { return false; } - + @@ -117,69 +118,69 @@ public class HttpURLConnectionMock extends HttpURLConnection { public boolean getInstanceFollowRedirects() { return this.instanceFollowRedirects; } - + @Override public void setInstanceFollowRedirects(boolean followRedirects) { assertFalse(connected); this.instanceFollowRedirects = followRedirects; } - + @Override public String getRequestMethod() { - return this.requestMethod; + 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())); - this.requestProperties.put(key.toLowerCase(), value); + 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(), value); + this.requestProperties.put(key.toLowerCase(Locale.ENGLISH), value); } - - + + @Override public String getRequestProperty(String key) { - return this.requestProperties.get(key.toLowerCase()); + 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(); @@ -189,9 +190,9 @@ public class HttpURLConnectionMock extends HttpURLConnection { public void setContentEncoding(String encoding) { this.contentEncoding = encoding; } - - - + + + @Override public int getContentLength() { connect(); @@ -199,7 +200,7 @@ public class HttpURLConnectionMock extends HttpURLConnection { return 0; return content.length; } - + public void setContent(byte[] content) { this.content = content; } @@ -211,8 +212,8 @@ public class HttpURLConnectionMock extends HttpURLConnection { fail("UTF-8"); } } - - + + @Override public String getContentType() { connect(); @@ -222,35 +223,35 @@ public class HttpURLConnectionMock extends HttpURLConnection { 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); @@ -261,8 +262,8 @@ public class HttpURLConnectionMock extends HttpURLConnection { inputStream = new ByteArrayInputStream(content); return inputStream; } - - + + @Override public OutputStream getOutputStream() throws IOException { assertTrue(doOutput); @@ -283,29 +284,26 @@ public class HttpURLConnectionMock extends HttpURLConnection { 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); @@ -314,7 +312,7 @@ public class HttpURLConnectionMock extends HttpURLConnection { throw e; } } - + private void assertNotNull(Object o) { try { org.junit.Assert.assertNotNull(o); @@ -323,7 +321,7 @@ public class HttpURLConnectionMock extends HttpURLConnection { throw e; } } - + private void assertTrue(boolean o) { try { org.junit.Assert.assertTrue(o); @@ -332,7 +330,7 @@ public class HttpURLConnectionMock extends HttpURLConnection { throw e; } } - + private void assertFalse(boolean o) { try { org.junit.Assert.assertFalse(o); @@ -341,209 +339,196 @@ public class HttpURLConnectionMock extends HttpURLConnection { 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/gui/print/PrintUnitTest.java b/core/test/net/sf/openrocket/gui/print/PrintUnitTest.java new file mode 100644 index 00000000..f92d18bc --- /dev/null +++ b/core/test/net/sf/openrocket/gui/print/PrintUnitTest.java @@ -0,0 +1,49 @@ +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/l10n/TestDebugTranslator.java b/core/test/net/sf/openrocket/l10n/TestDebugTranslator.java new file mode 100644 index 00000000..698094f9 --- /dev/null +++ b/core/test/net/sf/openrocket/l10n/TestDebugTranslator.java @@ -0,0 +1,24 @@ +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/TestL10N.java b/core/test/net/sf/openrocket/l10n/TestL10N.java new file mode 100644 index 00000000..6194931a --- /dev/null +++ b/core/test/net/sf/openrocket/l10n/TestL10N.java @@ -0,0 +1,29 @@ +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 index db7dbfc7..992bcc2c 100644 --- a/core/test/net/sf/openrocket/l10n/TestResourceBundleTranslator.java +++ b/core/test/net/sf/openrocket/l10n/TestResourceBundleTranslator.java @@ -5,18 +5,35 @@ 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 testSuccessfulUS() { - ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages", Locale.US); - assertEquals("messages.properties", trans.get("debug.currentFile")); + public void testSuccessfulDefault() { + ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages"); + assertEquals("messages_de.properties", trans.get("debug.currentFile")); } @Test - public void testSuccessfulFR() { + public void testSuccessfulNonDefault() { ResourceBundleTranslator trans = new ResourceBundleTranslator("l10n.messages", Locale.FRENCH); assertEquals("messages_fr.properties", trans.get("debug.currentFile")); } @@ -31,4 +48,20 @@ public class TestResourceBundleTranslator { } } + @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/motor/ManufacturerTest.java b/core/test/net/sf/openrocket/motor/ManufacturerTest.java index 6870c5f2..cd0ce25e 100644 --- a/core/test/net/sf/openrocket/motor/ManufacturerTest.java +++ b/core/test/net/sf/openrocket/motor/ManufacturerTest.java @@ -24,6 +24,18 @@ public class ManufacturerTest { } + 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() { diff --git a/core/test/net/sf/openrocket/preset/BodyTubeComponentTests.java b/core/test/net/sf/openrocket/preset/BodyTubeComponentTests.java new file mode 100644 index 00000000..891d9ed3 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/BodyTubeComponentTests.java @@ -0,0 +1,142 @@ +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 new file mode 100644 index 00000000..33d75293 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/BodyTubePresetTests.java @@ -0,0 +1,271 @@ +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 new file mode 100644 index 00000000..6a1c8463 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/BulkHeadComponentTests.java @@ -0,0 +1,103 @@ +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 new file mode 100644 index 00000000..2f393bac --- /dev/null +++ b/core/test/net/sf/openrocket/preset/BulkHeadPresetTests.java @@ -0,0 +1,173 @@ +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 new file mode 100644 index 00000000..dac3f8fd --- /dev/null +++ b/core/test/net/sf/openrocket/preset/CenteringRingComponentTests.java @@ -0,0 +1,116 @@ +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 new file mode 100644 index 00000000..718e4be5 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/CenteringRingPresetTests.java @@ -0,0 +1,271 @@ +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 new file mode 100644 index 00000000..759a3b7b --- /dev/null +++ b/core/test/net/sf/openrocket/preset/EngineBlockComponentTests.java @@ -0,0 +1,116 @@ +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 new file mode 100644 index 00000000..d032b513 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/EngineBlockPresetTests.java @@ -0,0 +1,271 @@ +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 new file mode 100644 index 00000000..e232aa62 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/LaunchLugComponentTests.java @@ -0,0 +1,126 @@ +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 new file mode 100644 index 00000000..207931d3 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/LaunchLugPresetTests.java @@ -0,0 +1,271 @@ +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 new file mode 100644 index 00000000..37f7dd4e --- /dev/null +++ b/core/test/net/sf/openrocket/preset/NoseConeComponentTests.java @@ -0,0 +1,174 @@ +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 new file mode 100644 index 00000000..56e849c5 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/NoseConePresetTests.java @@ -0,0 +1,208 @@ +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 new file mode 100644 index 00000000..e6b3110a --- /dev/null +++ b/core/test/net/sf/openrocket/preset/ParachutePresetTests.java @@ -0,0 +1,138 @@ +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 new file mode 100644 index 00000000..e2489960 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/ParachuterComponentTests.java @@ -0,0 +1,128 @@ +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 new file mode 100644 index 00000000..84b7c03b --- /dev/null +++ b/core/test/net/sf/openrocket/preset/PresetAssertHelper.java @@ -0,0 +1,43 @@ +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 new file mode 100644 index 00000000..099a8d54 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/StreamerComponentTests.java @@ -0,0 +1,92 @@ +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 new file mode 100644 index 00000000..a16fd14c --- /dev/null +++ b/core/test/net/sf/openrocket/preset/StreamerPresetTests.java @@ -0,0 +1,108 @@ +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 new file mode 100644 index 00000000..9826613c --- /dev/null +++ b/core/test/net/sf/openrocket/preset/TransitionComponentTests.java @@ -0,0 +1,210 @@ +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 new file mode 100644 index 00000000..26593dd8 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/TransitionPresetTests.java @@ -0,0 +1,222 @@ +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 new file mode 100644 index 00000000..829f664f --- /dev/null +++ b/core/test/net/sf/openrocket/preset/TubeCouplerComponentTests.java @@ -0,0 +1,117 @@ +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 new file mode 100644 index 00000000..7ef16ede --- /dev/null +++ b/core/test/net/sf/openrocket/preset/TubeCouplerPresetTests.java @@ -0,0 +1,271 @@ +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 new file mode 100644 index 00000000..bbc609d9 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/xml/BaseComponentDTOTest.java @@ -0,0 +1,72 @@ +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 new file mode 100644 index 00000000..4325fae2 --- /dev/null +++ b/core/test/net/sf/openrocket/preset/xml/OpenRocketComponentSaverTest.java @@ -0,0 +1,112 @@ +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 index fb231dc0..aa3fc486 100644 --- a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompare.java +++ b/core/test/net/sf/openrocket/rocketcomponent/ComponentCompare.java @@ -18,7 +18,7 @@ public class ComponentCompare { "getStageNumber", "getComponentName", // Rocket specific methods: "getModID", "getMassModID", "getAerodynamicModID", "getTreeModID", "getFunctionalModID", - "getMotorConfigurationIDs", "getDefaultConfiguration" + "getMotorConfigurationIDs", "getDefaultConfiguration", "getMotorMounts" }; diff --git a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java b/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java index 46c8f21d..647750cc 100644 --- a/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java +++ b/core/test/net/sf/openrocket/rocketcomponent/ComponentCompareTest.java @@ -1,16 +1,19 @@ package net.sf.openrocket.rocketcomponent; -import static org.junit.Assert.*; +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 { +public class ComponentCompareTest extends BaseTestCase { @Test public void testComponentEquality() { diff --git a/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java b/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java index abec65ce..321efbe8 100644 --- a/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java +++ b/core/test/net/sf/openrocket/rocketcomponent/FinSetTest.java @@ -1,8 +1,6 @@ package net.sf.openrocket.rocketcomponent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.Color; @@ -20,7 +18,7 @@ import org.junit.Test; public class FinSetTest extends BaseTestCase { - + @Test public void testFreeformConvert() { testFreeformConvert(new TrapezoidFinSet()); @@ -55,14 +53,14 @@ public class FinSetTest extends BaseTestCase { 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(); @@ -79,7 +77,7 @@ public class FinSetTest extends BaseTestCase { assertTrue(l1.changed); assertEquals(ComponentChangeEvent.NONFUNCTIONAL_CHANGE, l1.changetype); - + // Create copy RocketComponent rocketcopy = rocket.copy(); diff --git a/core/test/net/sf/openrocket/rocketcomponent/SymmetricComponentVolumeTest.java b/core/test/net/sf/openrocket/rocketcomponent/SymmetricComponentVolumeTest.java new file mode 100644 index 00000000..9d554d72 --- /dev/null +++ b/core/test/net/sf/openrocket/rocketcomponent/SymmetricComponentVolumeTest.java @@ -0,0 +1,450 @@ +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/simulation/customexpression/TestExpressions.java b/core/test/net/sf/openrocket/simulation/customexpression/TestExpressions.java new file mode 100644 index 00000000..d67bca0a --- /dev/null +++ b/core/test/net/sf/openrocket/simulation/customexpression/TestExpressions.java @@ -0,0 +1,23 @@ +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 new file mode 100644 index 00000000..093f0596 --- /dev/null +++ b/core/test/net/sf/openrocket/unit/FractionalUnitTest.java @@ -0,0 +1,206 @@ +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 new file mode 100644 index 00000000..6b96a5f1 --- /dev/null +++ b/core/test/net/sf/openrocket/unit/UnitToStringTest.java @@ -0,0 +1,170 @@ +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/util/ArrayUtilsTest.java b/core/test/net/sf/openrocket/util/ArrayUtilsTest.java new file mode 100644 index 00000000..ee8b5e96 --- /dev/null +++ b/core/test/net/sf/openrocket/util/ArrayUtilsTest.java @@ -0,0 +1,126 @@ +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 new file mode 100644 index 00000000..edf13005 --- /dev/null +++ b/core/test/net/sf/openrocket/util/Base64Test.java @@ -0,0 +1,42 @@ +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/ExpressionParserTest.java b/core/test/net/sf/openrocket/util/ExpressionParserTest.java new file mode 100644 index 00000000..efbabe9c --- /dev/null +++ b/core/test/net/sf/openrocket/util/ExpressionParserTest.java @@ -0,0 +1,94 @@ +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/LinearInterpolatorTest.java b/core/test/net/sf/openrocket/util/LinearInterpolatorTest.java new file mode 100644 index 00000000..600f82b1 --- /dev/null +++ b/core/test/net/sf/openrocket/util/LinearInterpolatorTest.java @@ -0,0 +1,32 @@ +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 index f11ba89c..6b9c1e1a 100644 --- a/core/test/net/sf/openrocket/util/MathUtilTest.java +++ b/core/test/net/sf/openrocket/util/MathUtilTest.java @@ -13,6 +13,23 @@ 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() { diff --git a/core/test/net/sf/openrocket/util/PolyInterpolatorTest.java b/core/test/net/sf/openrocket/util/PolyInterpolatorTest.java new file mode 100644 index 00000000..cb9201f1 --- /dev/null +++ b/core/test/net/sf/openrocket/util/PolyInterpolatorTest.java @@ -0,0 +1,212 @@ +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 new file mode 100644 index 00000000..26a2dc26 --- /dev/null +++ b/core/test/net/sf/openrocket/util/QuaternionTest.java @@ -0,0 +1,48 @@ +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/SimpleStackTest.java b/core/test/net/sf/openrocket/util/SimpleStackTest.java new file mode 100644 index 00000000..16cd312b --- /dev/null +++ b/core/test/net/sf/openrocket/util/SimpleStackTest.java @@ -0,0 +1,43 @@ +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/TextUtilTest.java b/core/test/net/sf/openrocket/util/TextUtilTest.java index 8ac8319d..4c040fbb 100644 --- a/core/test/net/sf/openrocket/util/TextUtilTest.java +++ b/core/test/net/sf/openrocket/util/TextUtilTest.java @@ -2,13 +2,36 @@ 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])); diff --git a/core/test/net/sf/openrocket/util/TransformationTest.java b/core/test/net/sf/openrocket/util/TransformationTest.java new file mode 100644 index 00000000..cb63b3f2 --- /dev/null +++ b/core/test/net/sf/openrocket/util/TransformationTest.java @@ -0,0 +1,81 @@ +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/web/html/actions/updates.php b/core/web/html/actions/updates.php index 7275e6e1..83b20e5c 100644 --- a/core/web/html/actions/updates.php +++ b/core/web/html/actions/updates.php @@ -80,19 +80,30 @@ header("Content-type: text/plain"); $version = $_GET["version"]; $updates = ""; -$unstable = "12.03"; +$unstable = "12.09"; $stable = "1.0.0"; -if (preg_match("/^1\.1\.9$/", $version)) { +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" . - "5: Guided tours\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" . @@ -115,6 +126,8 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . @@ -122,6 +135,8 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . @@ -132,6 +147,8 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . @@ -140,6 +157,8 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . @@ -149,6 +168,8 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . @@ -159,6 +180,8 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . @@ -170,12 +193,16 @@ if (preg_match("/^1\.1\.9$/", $version)) { ""; } 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" . diff --git a/core/web/html/download.html b/core/web/html/download.html index 4418d3c5..a99f29d2 100644 --- a/core/web/html/download.html +++ b/core/web/html/download.html @@ -48,6 +48,23 @@ <div class="content"> <div class="news"> <h2>Recent news:</h2> + <p><span class="date">16.9.2012:</span> Version 12.09 is + <a href="download.html">released</a>!</p> + <p>This version contains a huge number of new features by many contributors:</p> + <ul> + <li>3D rocket design view</li> + <li>Component Presets</li> + <li>Custom expressions in simulations</li> + <li>Printing for centering ring and clustered centering ring components</li> + <li>Support simple arthmatic in dimension entry</li> + <li>Support deploying recovery device at stage separation</li> + <li>Support for fractional inches (1/64) for unit length</li> + <li>Added preference for windspeed units separately</li> + <li>Added "most recently used files" in File Menu</li> + <li>Improved printed accurracy in fin marking guide</li> + <li>Calibration rulers added to printed templates</li> + <li>Translations in Czech and Polish, numerous updates</li> + </ul> <p><span class="date">10.3.2012:</span> Version 12.03 for desktop and Android is <a href="download.html">released</a>!</p> <p>In this release the version numbering scheme has been changed. @@ -64,26 +81,6 @@ 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.</p> - <p><span class="date">24.11.2011:</span> Version 1.1.9 is - <a href="download.html">released</a>!</p> - <p>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 <em>Geodetic calculations</em> option in the simulation - options. It's not <em>(yet)</em> a full spherical computation model, but - should be accurate enough for almost all sub-orbital needs.</p> - <p>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.</p> - <p><span class="date">25.8.2011:</span> Version 1.1.8 is - <a href="download.html">released</a>!</p> - <p>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.</p> - <p>The web pages have also been somewhat updated and Boris du Reau has - created <a href="http://openrocket.trans.free.fr/">a separate site</a> - for coordinating the localization efforts for OpenRocket.</p> </div> <div class="contentholder"> <h2>Ready packages</h2> @@ -104,20 +101,20 @@ <a href="http://sourceforge.net/donate/index.php?group_id=260357"><img src="project-support.jpg" width="88" height="32" alt="Support This Project" /></a> </div> <div class="downloadbox"> - <a class="main" href="https://sourceforge.net/projects/openrocket/files/openrocket/12.03/OpenRocket-12.03.jar/download"> + <a class="main" href="https://sourceforge.net/projects/openrocket/files/openrocket/12.09/OpenRocket-12.09.jar/download"> <strong>Download now!</strong> - <span>OpenRocket-12.03.jar</span> + <span>OpenRocket-12.09.jar</span> </a> <span class="alternative"> - <a href="https://sourceforge.net/projects/openrocket/files/openrocket/12.03/ReleaseNotes/view">Release notes</a> | - <a href="https://sourceforge.net/projects/openrocket/files/openrocket/12.03/OpenRocket-12.03-src.zip/download">Source code</a> + <a href="https://sourceforge.net/projects/openrocket/files/openrocket/12.09/ReleaseNotes/view">Release notes</a> | + <a href="https://sourceforge.net/projects/openrocket/files/openrocket/12.09/OpenRocket-12.09-src.zip/download">Source code</a> </span> </div> <p>OpenRocket can be started in most graphical environments (including Windows) by double-clicking the package icon. No installation is required.</p> <p>From the command line OpenRocket can be started by - <span class="command">java -jar OpenRocket-12.03.jar</span></p> + <span class="command">java -jar OpenRocket-12.09.jar</span></p> <h3>Android version</h3> <p>The Android version allows opening OpenRocket files, viewing simulations and motors. Later versions will allow running diff --git a/core/web/html/index.html b/core/web/html/index.html index c42a1b1b..f2bfdce5 100644 --- a/core/web/html/index.html +++ b/core/web/html/index.html @@ -49,12 +49,12 @@ <h2>Introduction</h2> <div class="rightpane"> <div class="downloadbox"> - <a class="main" href="https://sourceforge.net/projects/openrocket/files/openrocket/12.03/OpenRocket-12.03.jar/download"> + <a class="main" href="https://sourceforge.net/projects/openrocket/files/openrocket/12.09/OpenRocket-12.09.jar/download"> <strong>Download now!</strong> - <span>OpenRocket-12.03.jar</span> + <span>OpenRocket-12.09.jar</span> </a> <span class="alternative"> - <a href="https://sourceforge.net/projects/openrocket/files/openrocket/12.03/ReleaseNotes/view">Release notes</a> | + <a href="https://sourceforge.net/projects/openrocket/files/openrocket/12.09/ReleaseNotes/view">Release notes</a> | <a href="download.html">Other versions</a> </span> </div> @@ -96,6 +96,23 @@ <div class="clear"></div> <div class="news"> <h2>News</h2> + <p><span class="date">16.9.2012:</span> Version 12.09 is + <a href="download.html">released</a>!</p> + <p>This version contains a huge number of new features by many contributors:</p> + <ul> + <li>3D rocket design view</li> + <li>Component Presets</li> + <li>Custom expressions in simulations</li> + <li>Printing for centering ring and clustered centering ring components</li> + <li>Support simple arthmatic in dimension entry</li> + <li>Support deploying recovery device at stage separation</li> + <li>Support for fractional inches (1/64) for unit length</li> + <li>Added preference for windspeed units separately</li> + <li>Added "most recently used files" in File Menu</li> + <li>Improved printed accurracy in fin marking guide</li> + <li>Calibration rulers added to printed templates</li> + <li>Translations in Czech and Polish, numerous updates</li> + </ul> <p><span class="date">10.3.2012:</span> Version 12.03 for desktop and Android is <a href="download.html">released</a>!</p> <p>In this release the version numbering scheme has been changed. diff --git a/core/web/htp/download.htp b/core/web/htp/download.htp index 336b8b5f..aed535f1 100644 --- a/core/web/htp/download.htp +++ b/core/web/htp/download.htp @@ -62,7 +62,7 @@ <ol> <li>Go to <em>Settings</em> → <em>Applications</em> and check <em>Unknown sources</em>.</li> - <li>Download <a href="https://sourceforge.net/projects/openrocket/files/openrocket/${version}/OpenRocket-Android-${version}.apk/download">OpenRocket-Android-<use version>.apk</a> + <li>Download <a href="https://sourceforge.net/projects/openrocket/files/openrocket/${androidversion}/OpenRocket-Android-${androidversion}.apk/download">OpenRocket-Android-<use androidversion>.apk</a> on your device and accept installation.</li> </ol> diff --git a/core/web/htp/htp.def b/core/web/htp/htp.def index d2aedaa1..5e6d4bcc 100644 --- a/core/web/htp/htp.def +++ b/core/web/htp/htp.def @@ -1,4 +1,5 @@ -<set version="12.03"> +<set version="12.09"> +<set androidversion="12.03"> <def name="downloadbox"> <div class="downloadbox"> diff --git a/core/web/htp/news.htp b/core/web/htp/news.htp index be4153e2..538c9136 100644 --- a/core/web/htp/news.htp +++ b/core/web/htp/news.htp @@ -9,6 +9,27 @@ <!--- Remember to move the position of "onlyrecent" below! ---> + <p><span class="date">16.9.2012:</span> Version 12.09 is + <a href="download.html">released</a>!</p> + + <p>This version contains a huge number of new features by many contributors:</p> + + <ul> + <li>3D rocket design view</li> + <li>Component Presets</li> + <li>Custom expressions in simulations</li> + <li>Printing for centering ring and clustered centering ring components</li> + <li>Support simple arthmatic in dimension entry</li> + <li>Support deploying recovery device at stage separation</li> + <li>Support for fractional inches (1/64) for unit length</li> + <li>Added preference for windspeed units separately</li> + <li>Added "most recently used files" in File Menu</li> + <li>Improved printed accurracy in fin marking guide</li> + <li>Calibration rulers added to printed templates</li> + <li>Translations in Czech and Polish, numerous updates</li> + </ul> + + <p><span class="date">10.3.2012:</span> Version 12.03 for desktop and Android is <a href="download.html">released</a>!</p> @@ -29,6 +50,10 @@ designation class. The application has also been translated to Italian by Mauro Biasutti and Russian by the Sky Dart Team.</p> + + <if not onlyrecent><!--- Older items not shown on download page: ---> + + <p><span class="date">24.11.2011:</span> Version 1.1.9 is <a href="download.html">released</a>!</p> @@ -56,9 +81,6 @@ for coordinating the localization efforts for OpenRocket.</p> - <if not onlyrecent><!--- Older items not shown on download page: ---> - - <p><span class="date">12.8.2011:</span> Version 1.1.7 is <a href="download.html">released</a>!</p>